Flow of Control
The for loop and range()
Use a for loop with range().
Repetition (iteration) runs statements again and again. To print your name 100,000 times, you would not write 100,000 print statements; you would write a loop. Every loop needs an exit condition, or it would run forever (an infinite loop).
The for loop goes through the items of a sequence, running its body once for each item. For example, for letter in 'MANGO': print(letter) prints M, A, N, G and O, one per line. The number of repetitions is known in advance: one per item. The body of the loop is indented under the for line.
The range() function makes a sequence of whole numbers: range([start], stop[, step]).
- It starts at start (0 if you leave it out).
- It goes up to, but never includes, stop.
- It moves in jumps of step (1 if you leave it out). The step can be negative, to count down, but it can never be 0.
Examples:
- list(range(1, 10, 2)) is [1, 3, 5, 7, 9].
- list(range(5, 0, -1)) is [5, 4, 3, 2, 1].
An if can sit inside a loop. To print only the odd numbers of a list: for n in [3, 8, 11, 14], the body checks if n % 2 != 0 and, if so, prints n. It prints 3 and 11.
Practise this lesson
Questions that get harder as you improve, a Tutor that helps without giving the answer away, and progress you can see. Free for every learner.
No account, no email address. Opens the real product.