Learning Objectives – after this chapter you will be able to:
  • Write while and for loops.
  • Generate number sequences with range().
  • Control loops with break, continue, pass and the loop else clause.
  • Write nested loops and common patterns such as sums, counters and enumerate().
Loops

A loop repeats a block of code. Python has two loop statements:

  • while – repeats as long as a condition is true (used when the number of repetitions is not known in advance).
  • for – repeats once for each item of a sequence or other iterable (string, list, tuple, range, dictionary …).
while Loop
while condition: statements
count = 1
while count <= 5:
    print(count, end=" ")
    count += 1              # update, otherwise the loop never ends
print()

# Sum of digits of a number
n, total = 4721, 0
while n > 0:
    total += n % 10
    n //= 10
print("Sum of digits:", total)
Output
1 2 3 4 5
Sum of digits: 14
If the condition never becomes false, the loop runs forever (an infinite loop). In Colab, stop it with the ■ (interrupt) button.
for Loop and range()

range(start, stop, step) produces numbers from start up to but not including stop. Defaults: start = 0, step = 1.

CallValues produced
range(5)0, 1, 2, 3, 4
range(2, 8)2, 3, 4, 5, 6, 7
range(1, 10, 3)1, 4, 7
range(10, 0, -2)10, 8, 6, 4, 2
for i in range(1, 6):
    print(i * i, end=" ")
print()

for ch in "Python":
    print(ch, end="-")
print()

fruits = ["apple", "mango", "kiwi"]
for index, fruit in enumerate(fruits, start=1):
    print(index, fruit)
Output
1 4 9 16 25
P-y-t-h-o-n-
1 apple
2 mango
3 kiwi
Factorial using a for loop
n = 5
factorial = 1
for i in range(1, n + 1):
    factorial *= i
print(f"{n}! = {factorial}")
Output
5! = 120
break, continue and pass
breakExits the loop immediately.
continueSkips the rest of the current iteration and moves to the next one.
passDoes nothing – a placeholder where a statement is required.
for n in range(1, 10):
    if n == 6:
        break           # stop the loop at 6
    if n % 2 == 0:
        continue        # skip even numbers
    print(n, end=" ")
print()

for n in range(3):
    pass                # loop body to be written later
print("done")
Output
1 3 5
done
Loop else Clause

A loop can have an else block. It runs when the loop finishes normally, and is skipped if the loop ends with break. It is useful for search loops.

def check_prime(n):
    for d in range(2, int(n ** 0.5) + 1):
        if n % d == 0:
            print(n, "is not prime; divisible by", d)
            break
    else:
        print(n, "is prime")

check_prime(29)
check_prime(91)
Output
29 is prime
91 is not prime; divisible by 7
Nested Loops

A loop inside another loop. The inner loop completes all its iterations for each iteration of the outer loop.

for row in range(1, 5):
    print("*" * row)

for i in range(1, 4):
    for j in range(1, 4):
        print(i * j, end="\t")
    print()
Output
*
**
***
****
1	2	3
2	4	6
3	6	9
Key Takeaways
  • while repeats on a condition; for repeats over items; range() excludes its stop value.
  • break exits, continue skips, pass does nothing.
  • A loop’s else runs only if the loop was not ended by break.
Video : Loops
Question / Answer (15 questions)

Answer : A loop repeats a block of code. Python provides the while loop, which repeats as long as a condition is True, and the for loop, which repeats once for each item of an iterable.

Answer : Use while when the number of repetitions is not known in advance and depends on a condition, for example reading input until the user types "quit". Use for when iterating over a known sequence or range.

Answer : An infinite loop never ends because its condition never becomes False. It is avoided by updating the loop variable inside the loop so the condition eventually fails, or by using break when a goal is reached.

Answer : range() produces integers from start up to but not including stop, increasing by step. range(5) gives 0–4, range(2, 8) gives 2–7, and range(10, 0, -2) gives 10, 8, 6, 4, 2.

Answer : 1, 4 and 7. The next value, 10, is not included because stop is exclusive.

Answer : break terminates the whole loop immediately. continue skips only the rest of the current iteration and moves on to the next iteration.

Answer : pass does nothing. It is used as a placeholder when a statement is syntactically required, such as an empty loop or function body to be completed later.

Answer : The else block runs after the loop completes normally (the condition becomes False or the items run out). It does not run if the loop is terminated by break.

Answer : The loop tries divisors and breaks when one divides the number. If no divisor is found, the loop finishes normally and else runs, reporting that the number is prime – no extra flag variable is needed.

Answer : enumerate() returns pairs of (index, item), so a loop can access both the position and the value. enumerate(items, start=1) starts counting from 1.

Answer : A nested loop is a loop inside another loop. The inner loop runs completely for each outer iteration, so the inner body runs 3 × 4 = 12 times.

Answer : total = 0; while n > 0: total += n % 10; n //= 10. n % 10 extracts the last digit and n //= 10 removes it. For 4721 the result is 14.

Answer : factorial = 1; for i in range(1, n + 1): factorial *= i. For n = 5 the result is 120.

Answer : Yes. A string is a sequence, so for ch in "Python" gives one character per iteration: P, y, t, h, o, n.

Answer : A range object does not store all its numbers in memory; it calculates each value when needed. range(1_000_000) uses the same small amount of memory as range(10).
MCQ Test : Check Your Understanding (5 questions)

Select an option and press Check Answer, or answer all questions and press Submit Test to see your score. Each answer comes with an explanation.

Q1. How many times does for i in range(2, 10, 2): execute its body?

Show Answer

Correct Answer : B. 4
The values are 2, 4, 6 and 8 – four iterations.

Q2. Which statement skips the rest of the current iteration only?

Show Answer

Correct Answer : A. continue
continue moves to the next iteration.

Q3. When is the else block of a for loop SKIPPED?

Show Answer

Correct Answer : D. When the loop ends with break
break bypasses the loop’s else clause.

Q4. What is the last value produced by range(10, 0, -3)?

Show Answer

Correct Answer : B. 1
The values are 10, 7, 4, 1; 0 is the excluded stop value.

Q5. What does the following print? i = 0; while i < 3: i += 1 – then print(i)

Show Answer

Correct Answer : C. 3
The loop stops when i becomes 3.

Bibliography/References

The notes, questions and MCQs on this page are original explanations written for this course. The works listed below were consulted and are cited for attribution and further reading. Product names, logos and trademarks belong to their respective owners. Short quotations, where used, are marked and attributed.

  1. Python Software Foundation. (n.d.). More Control Flow Tools. In The Python Tutorial. https://docs.python.org/3/tutorial/controlflow.html
  2. Python Software Foundation. (n.d.). Compound Statements. In The Python Language Reference. https://docs.python.org/3/reference/compound_stmts.html
  3. Python Software Foundation. (n.d.). Built-in Functions. The Python Standard Library. https://docs.python.org/3/library/functions.html
  4. Python Software Foundation. (n.d.). Built-in Types. The Python Standard Library. https://docs.python.org/3/library/stdtypes.html
  5. Downey, A. B. (2024). Think Python (3rd ed.). O’Reilly Media. (Free online edition by Green Tea Press.) https://allendowney.github.io/ThinkPython/
  6. Matthes, E. (2023). Python Crash Course (3rd ed.). No Starch Press.