Why loops?
A loop repeats a block of code. Without a loop, printing the 5 times table needs ten lines; with a loop it needs two:
for i in range(1, 11):
print(5, "x", i, "=", 5 * i)
Python has two loops: for (repeat for each item) and while (repeat while a condition is true).
range(): a ready-made sequence of numbers
| Call | Numbers | Note |
|---|---|---|
range(5) | 0, 1, 2, 3, 4 | starts at 0 |
range(1, 6) | 1, 2, 3, 4, 5 | stop is not included |
range(2, 11, 2) | 2, 4, 6, 8, 10 | step of 2 |
range(10, 0, -1) | 10, 9, ... 1 | counts down |
for loops
total = 0
for month in range(1, 13):
total += 500
print("Saved in a year:", total) # 6000
Each time round, month takes the next value, and the indented block runs once.
for works on anything you can go through one item at a time: strings, lists, tuples, dictionaries and files.
for letter in "Ranchi":
print(letter)
for name in ["Asha", "Ravi", "Meena"]:
print("Hello", name)
while: repeat as long as a condition is true
n = 5
while n > 0:
print(n)
n -= 1 # without this line the loop never ends
print("Lift-off!")
Use while when you do not know in advance how many times to repeat, for example "keep asking until the PIN is right".
Infinite loop: if the condition never becomes false, the loop runs forever. Press Ctrl + C to stop it.
break and continue
breakstops the loop immediately.continueskips the rest of this turn and goes to the next one.
for n in range(1, 11):
if n == 7:
break # stops at 7: prints 1 to 6
print(n)
for n in range(1, 11):
if n % 2 == 0:
continue # skips even numbers: prints 1 3 5 7 9
print(n)
The while True menu pattern
Real programs often loop until the user chooses to quit:
while True:
print("1. Balance 2. Deposit 3. Exit")
choice = input("Choose: ")
if choice == "1":
print("Balance: Rs 5000")
elif choice == "2":
print("Deposit accepted")
elif choice == "3":
print("Goodbye")
break
else:
print("Invalid choice")
Nested loops: tables and patterns
A loop inside a loop. The inner loop runs completely for each turn of the outer loop.
for row in range(1, 4): # 3 rows
for seat in range(1, 3): # 2 seats in each row
print(f"R{row}S{seat}", end=" ")
print() # new line after each row
Output:
R1S1 R1S2
R2S1 R2S2
R3S1 R3S2
Star pyramid
n = 4
for i in range(1, n + 1):
print(" " * (n - i) + "*" * (2 * i - 1))
*
***
*****
*******
Example: ATM PIN with 3 attempts
correct = "4321"
attempts = 0
while attempts < 3:
pin = input("Enter PIN: ")
if pin == correct:
print("Access granted")
break
attempts += 1
print("Wrong PIN,", 3 - attempts, "tries left")
else:
print("Card blocked")
The else on a loop runs only when the loop ends without a break. Here it means all three tries were wrong.
Common mistakes
- Expecting
range(1, 10)to include 10. - Forgetting to change the variable in a
whileloop, so it never ends. - Wrong indentation: a line meant to run once after the loop is indented inside it.
- Changing a list while looping over it; loop over a copy instead:
for x in items[:].
Key points
forrepeats for each item;whilerepeats while a condition is true.range(start, stop, step)stops beforestop.breakends the loop;continuejumps to the next turn.- In nested loops, the inner loop finishes completely for every turn of the outer loop.
Practice questions
1. What numbers does range(3, 15, 4) give?
3, 7, 11. The next would be 15, which is the stop value and is not included.
2. Print the sum of all even numbers from 1 to 100.
total = 0
for n in range(2, 101, 2):
total += n
print(total) # 25503. Write a loop that reverses the digits of a number, for example 1234 to 4321.
n = 1234
rev = 0
while n > 0:
rev = rev * 10 + n % 10
n //= 10
print(rev)4. How many times does print("Hi") run?
for i in range(3):
for j in range(4):
print("Hi")
12 times: 4 for each of the 3 outer turns.
5. Print this pattern using nested loops: 1 / 1 2 / 1 2 3 / 1 2 3 4 (one group per line).
for i in range(1, 5):
for j in range(1, i + 1):
print(j, end=" ")
print()