Lesson 9: For Loops
We also use the FOR loop when something in the code is supposed to repeat. However, the FOR loop is a loop with a fixed number of repetitions.
In for loops, there is something called i (or any variable name). i is the loop control variable. On the first iteration, i is set to the start value, and on each subsequent iteration, it updates accordingly. When the loop reaches the end of the set range, it will execute for the last time and terminate.
Iteration: The repetition of a process where a change occurs, bringing us one step closer to the result.
Using for variable in iterable object:
An iterable object can be, for example:
- String – iteration is performed by traversing individual characters.
- List – iteration is performed by traversing individual elements in the list.
Using the range() Function
range() is a function that generates numbers based on the arguments in round brackets:
range(n)– returns numbers from0ton-1range(m, n)– returns numbers frommton-1range(m, n, k)– returns numbers frommton-1with a step ofk
Examples of range():
# range(5)
for number in range(5):
print(number)
# Output: 0, 1, 2, 3, 4
# range(2, 5)
for number in range(2, 5):
print(number)
# Output: 2, 3, 4
# range(3, 10, 2)
for number in range(3, 10, 2):
print(number)
# Output: 3, 5, 7, 9
When we look at this in an exercise: Add together 10 numbers inputted from the keyboard:
sum = 0
for i in range(10):
number = int(input("Wrtie a nuber:"))
sum += number
print("The sum of these numbers is: ", sum)Output
Wrtie a nuber:5
Wrtie a nuber:4
Wrtie a nuber:5
Wrtie a nuber:2
Wrtie a nuber:3
Wrtie a nuber:4
Wrtie a nuber:6
Wrtie a nuber:7
Wrtie a nuber:8
Wrtie a nuber:9
The sum of these numbers is: 53
You can almost always replace a FOR loop with a WHILE loop, but FOR loops are much cleaner when you know how many times you want to iterate!
Want XP, levels and progress tracking? Play this lesson in the CodeStart game.
Play Lesson 9