Chapter 25: for loop

We can use a for loop instead of a while loop, as both function similarly. In programming, any type of loop can be used depending on the situation.

The behaviour of a for loop depends on the number of parameters provided:

  • With one parameter, it acts as the ending value.

  • With two parameters, the first is the starting value, and the second is the ending value.

  • With three parameters, the first is the starting value, the second is the ending value, and the third specifies the step.

for i in range(10): #range is 0 to 9
    print(f"i: {i}")
Output: 
0
1
2
3
4
5
6
7
8
9
for i in range (2, 10): #range is 2 to 9 (starting from 2)
    print(f"i: {i}")
Output:
2
3
4
5
6
7
8
9
for i in range (2, 10, 2): #range is 2 to 9 (step 2: every second value)
    print(f"i: {i}")
Output:
2
4
6
8