Quiz
Warm-up from lesson 4-3: with score = 85, which branch runs? if score >= 90: print("A") elif score >= 80: print("B") else: print("C")
Don't repeat yourself, loop
Suppose you need to print the numbers 0 through 4. Five print lines would work, but five thousand would not. A loop tells Python to run a block repeatedly.
for i in range(5): print(i)
Output: 0, 1, 2, 3, 4, one per line. The pieces:
range(5)produces the sequence 0, 1, 2, 3, 4. It starts at 0 and stops before 5, giving exactly 5 numbersfor i in ...runs the indented block once per number, and each time, the variableiholds the current number- The indented block is the loop body, same indentation rule as
iffrom lesson 4-2
Each run of the body is called an iteration. i is a normal variable (unit 3), it just gets reassigned automatically each iteration.
range can also take a start: range(1, 4) gives 1, 2, 3 (again stopping before the end).
Code exercise · python
Run both loops. Notice range(5) starts at 0, while range(1, 4) starts at 1 and stops before 4.
Code exercise · python
Your turn. Use one for loop with range to print the numbers 1 through 10, one per line.