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:
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).
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:
This would output:
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:
This would now output the range we expected:
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:
This could output:
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):
And when we run the above program is looks like this: