For Loops 1 Range - Lakelands Computing

Title
Go to content
For Loops part 1 - using for i in range:
For  loops are a type of interation. They are a count controlled loop. This means they will run a block of code a certain number of times - Think of it as repeat x times.

  • for i in range (0,5):
    • print ("hi")

This would print hi 5 times (try it in the trinket)

for i in range (0,5):
    • print ("count : ", i)

And this would print count 0, count 1 etc. (again run it in the trinket)

You can see from this second example that i is increased each time the loop loops . The increase is 1 by default, but this can be changed by adding a third number into the brackets after range:

  • for i in range (0,10,2):
    • print ("count : ", i)

This would now print count 0, count 2, count 4 etc upto 8.  The third number in the brackets, the 2 in this case is the step value. It can be a negative to count backwards. You can change the first and second numbers too, they are the start and end number:

  • for i in range (10,100,10)
    • print ("count : ", i)

This would start at 10 and count up in tens until it reached 90, it stops 1 step before the end number when used like this.

You can use variable names in the place of the actual values, and do calculations as part of the loop too. This makes can make it more dynamic - have a look at the payment caluclator bit in the trinket for an example.

Remember it is for i in range (startNumber, endNumber, amountToChangeBy)
All Text copyright Lakelands Academy & Mr T Purslow 2020.
All images copyright free / creative commons unless otherwise stated.
You are welcome to use under a Creative Commons Attribution-nonCommercial-ShareAlike License.
All Text copyright Lakelands Academy & Mr T Purslow 2020.  All images copyright free / creative commons unless otherwise stated. You are welcome to use under a Creative Commons Attribution-nonCommercial-ShareAlike License.
All Text copyright Lakelands Academy & Mr T Purslow 2020.  All images copyright free / creative commons unless otherwise stated. You are welcome to use under a Creative Commons Attribution-nonCommercial-ShareAlike License.
Back to content