- Write
whileandforloops. - Generate number sequences with
range(). - Control loops with
break,continue,passand the loopelseclause. - 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: statementscount = 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)1 2 3 4 5 Sum of digits: 14
for Loop and range()
range(start, stop, step) produces numbers from start up to but not including stop. Defaults: start = 0, step = 1.
| Call | Values 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)1 4 9 16 25 P-y-t-h-o-n- 1 apple 2 mango 3 kiwi
n = 5
factorial = 1
for i in range(1, n + 1):
factorial *= i
print(f"{n}! = {factorial}")5! = 120
break, continue and pass
break | Exits the loop immediately. |
continue | Skips the rest of the current iteration and moves to the next one. |
pass | Does 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")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)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()* ** *** **** 1 2 3 2 4 6 3 6 9
Key Takeaways
whilerepeats on a condition;forrepeats over items;range()excludes its stop value.breakexits,continueskips,passdoes nothing.- A loop’s
elseruns only if the loop was not ended bybreak.
Video : Loops
Question / Answer (15 questions)
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.
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.
- Python Software Foundation. (n.d.). More Control Flow Tools. In The Python Tutorial. https://docs.python.org/3/tutorial/controlflow.html
- Python Software Foundation. (n.d.). Compound Statements. In The Python Language Reference. https://docs.python.org/3/reference/compound_stmts.html
- Python Software Foundation. (n.d.). Built-in Functions. The Python Standard Library. https://docs.python.org/3/library/functions.html
- Python Software Foundation. (n.d.). Built-in Types. The Python Standard Library. https://docs.python.org/3/library/stdtypes.html
- Downey, A. B. (2024). Think Python (3rd ed.). O’Reilly Media. (Free online edition by Green Tea Press.) https://allendowney.github.io/ThinkPython/
- Matthes, E. (2023). Python Crash Course (3rd ed.). No Starch Press.