Questions or a demo for your school?Student? Sit a test
BrainBit Infotech TeachingStart free

Python notes · Topic 6 of 22 · 4 min read

Python loops: for, while and range()

Python loops notes with examples: for loops, range(), while loops, break and continue, the while True menu pattern, nested loops and star patterns.

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

CallNumbersNote
range(5)0, 1, 2, 3, 4starts at 0
range(1, 6)1, 2, 3, 4, 5stop is not included
range(2, 11, 2)2, 4, 6, 8, 10step of 2
range(10, 0, -1)10, 9, ... 1counts 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

  • break stops the loop immediately.
  • continue skips 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 while loop, 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

  • for repeats for each item; while repeats while a condition is true.
  • range(start, stop, step) stops before stop.
  • break ends the loop; continue jumps 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)     # 2550
3. 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()