For Loops

Simple For Loops

We are going to create a very simple program that loops seven times and prints “I am looping” each time. This is the code that we would use:

screenshot-repl-it-2016-11-14-19-23-34

 

The variable named number is a count variable. For understanding I have called it number but the Python standard is to call it i. The current loop turn is represented by number. In the range brackets I have written that I want to loop the indented code 10 times.

Don’t forget the colon at the end and remember that everything you want to repeat must be indented (press tab key once).screenshot-repl-it-2016-11-14-19-24-29

Practice Task 1

Using the Loop Turn inside the Loop

Let’s make our for loops a bit more complicated. We can refer to the loop turn that we are currently on inside the loop itself using the number variable:
screenshot-repl-it-2016-11-14-19-40-25

This would output: screenshot-repl-it-2016-11-14-19-40-43

Python will always start counting at 0 rather than 1 so our loop is not as we expected. Therefore we need to specify in our range brackets that we want to start at 1 and continue up until (but not including) 11:
screenshot-repl-it-2016-11-14-19-47-06

This would now output the range we expected:

screenshot-repl-it-2016-11-14-19-47-24

Practice Task 2

Using a Variable as the Range

We don’t have to put just numbers in a range bracket. We could use a variable. For example in a very simple program where we have asked the user to enter how many times they want to print something:
screenshot-repl-it-2016-11-14-19-52-22

This could output:screenshot-repl-it-2016-11-14-19-52-41

Lastly, below is a for loop where the user inputs both the range and the text to be repeated (I have named the count variable ‘i’ in this example as per Python’s standard naming system):

for6

And when we run the above program is looks like this:

for7

Practice Task 3

For Loops not working? Tick off these common errors:

Correct for loop line?
Have you indented properly?

< Back to Section Six