Loops: while and for
Part of the free LogicWiz Python course, Module 2: Decisions and loops. The examples and practice run in the app.
Shankar bhaiya needs token slips 1 to 50 for the lunch rush. Fifty print lines? No: three lines with a loop.
You'll learn to
- Repeat with a while loop and a counter
- Avoid infinite loops
- Use for with range(start, stop, step), including counting backwards
- Remember that range stops **before** stop
Learn
A while loop
i = 1
while i <= 5:
print("Token", i)
i += 1
print("Done")
Step through it. Python checks i <= 5, runs the block, goes back up and checks again. When the check is False, it continues after the loop. Change 5 to 50: that is Shankar bhaiya's 50 tokens.
The three parts of a while loop
Every counting while loop has three parts:
- Start:
i = 1before the loop - Condition:
while i <= 5:checked before every round - Update:
i += 1inside the loop
Forget the update and i stays 1 forever, so the condition is always True: an infinite loop. If your program never stops, check the update first.
for with range()
for i in range(5):
print(i, end=" ")
print()
for i in range(1, 6):
print(i, end=" ")
print()
for i in range(2, 11, 2):
print(i, end=" ")
print()
range(5) gives 0, 1, 2, 3, 4: five numbers, starting at 0. range(1, 6) gives 1 to 5. The third number is the step: range(2, 11, 2) counts in twos.
range(start, stop, step)
| You write | You get |
|---|---|
range(5) |
0 1 2 3 4 |
range(1, 5) |
1 2 3 4 |
range(1, 10, 3) |
1 4 7 |
range(5, 0, -1) |
5 4 3 2 1 |
The stop is never included. To go up to n, write range(1, n + 1). for does the start, the check and the update for you, so it cannot forget the update.
Counting backwards, and loops over text
for i in range(10, 0, -1):
print(i, end=" ")
print("Go!")
for i in range(5, 0):
print("this never prints")
for ch in "CHAI":
print(ch)
Counting down needs a negative step. range(5, 0) is empty, because the default step +1 can never get from 5 down to 0. for can also walk through a string letter by letter.
A while loop that stops on 0
total = 0
price = int(input())
while price != 0:
total += price
price = int(input())
print("Bill total:", total)
Shankar bhaiya types prices until he types 0. We do not know how many items there will be, so while fits better than for. A value like this 0 that means "stop" is called a sentinel.
Use for when you know how many times to repeat (n tokens, each letter of a word). Use while when you repeat until something happens (the user types 0, the guess is right).
CBSE asks: "How many times does this loop run?" and "What is the output of range(10, 1, -3)?" (10 7 4). Trick: count the values range gives, and remember that stop is not one of them.
In one line
while repeats while a condition is True (do not forget the update); range(a, b, s) goes from a up to but not including b.