Friday 25 September 2020

Part Two: Lesson Three: The for Loop

Computers are very good at doing repetitive tasks over and over again and doing that very quickly using iterations. The for loop is one way to achieve that.

Let us say we have a list of names and we would like to say a personalised greeting to each we could do that as follows:

          names = [‘Ali’, ‘Mike’, ‘Jay’, ‘Mary’, ‘Sarah’]

          print(‘hello’, ‘Ali’)

          print(‘hello’, ‘Mike’)

          print(‘hello’, ‘Jay’)

          print(‘hello’, ‘Mary’)

          print(‘hello’, ‘Sarah’)

          print(‘Thank you’)

This is quite an inefficient way to write the code especially if the items in the list are increased to say hundreds.

A more efficient way is to use a for loop. We would say for each item in the list, display the personalised greeting. It would look like this:

          names = [‘Ali’, ‘Mike’, ‘Jay’, Mary’, Sarah’]

          for n in names:

                   print(‘hello’,  n)

          print(‘Thank you’)

Here n is referred to as the iteration variable. We can use any variable here.

Notice the colon after the for statement and also the indentation that follows. This is essential so as to let Python know that the print statement is part of the for loop and would continue looping till all items have been iterated over. After the iteration completes then the ‘Thank you’ message is displayed because it is not part of the indentation. If we indent this line too then ‘Thank you’ would be displayed with each iteration.

Let us try printing numbers from a list of 1 to 10.

          numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

          for x in numbers:

                   print(x)

this prints numbers from 1 to 10.

An easier way to create a list of numbers are to use the range() function. Range 1 to 11 would provide numbers from 1 up to 10 but not including 11.

          numbers = range(1, 11)

          for x in numbers:

                   print(x)

We could include the intervals in between the numbers perhaps at steps of 2 by adding it as an argument to make the increment at 2 steps

          numbers = range(1, 11, 2)

          for x in numbers:

                   print(x)

This would print out only the odd numbers starting from 1 then 3 and so on.

Lastly, we could use the in statement with our for loop and range function to make it even more concise

          for x in range(1, 11, 2):

                   print(x)

We have now achieved the same result but using just 2 lines of code.

The for loop can be used with other collections like tuples and dictionaries as well.

In the next lesson, we would study the while loop.

No comments:

Post a Comment