Python loops exercises FizzBuzz primes solutions cheat sheet

Python loops exercises — put them to the test

Python loops exercises are where everything clicks. You’ve seen the theory and practised with real programs. Now it’s time to solve on your own. In this article you’ll find four exercises across three levels, from FizzBuzz (a classic that appears in real job interviews) to compound interest and prime numbers.

As always: try to solve it, use the hint if you’ve been stuck for more than 10 minutes, and compare with the commented solution at the end. Use pythontutor.com to step through your solution and check what’s happening.

How to use this article

Read the exercise → try to solve it in VS Code → if stuck for more than 10 minutes read the hint → compare with the solution. Don’t jump to the solutions — you learn twice as much by solving it yourself first.


Python loops exercises — Basic Level

Exercise 1 — FizzBuzz

FizzBuzz is the most famous programming exercise in the world. It appears in job interviews at all levels, if you can solve it confidently you’ve mastered the basic loop + conditional combination.

Write a program that prints the numbers from 1 to 100 with these rules:

  • If the number is divisible by 3, print Fizz
  • If the number is divisible by 5, print Buzz
  • If it’s divisible by both 3 and 5, print FizzBuzz
  • Otherwise print the number

The output should start like this:

1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
...

💡 Hint: Use for i in range(1, 101) and if/elif/else with %. The classic mistake is checking i % 3 == 0 and i % 5 == 0 last — if you check i % 3 == 0 first it will print Fizz for 15 and never reach FizzBuzz. Always check the most specific condition first.


Exercise 2 — Multiplication table generator

Write a program that asks for a number and prints its complete multiplication table from 1 to 10, but with a formatted layout and marking the even and odd results:

Multiplication table for 7:
─────────────────────────────
 7 x  1 =   7  (odd)
 7 x  2 =  14  (even)
 7 x  3 =  21  (odd)
 7 x  4 =  28  (even)
 7 x  5 =  35  (odd)
 7 x  6 =  42  (even)
 7 x  7 =  49  (odd)
 7 x  8 =  56  (even)
 7 x  9 =  63  (odd)
 7 x 10 =  70  (even)
─────────────────────────────
Sum of results: 385
Even results: 5 | Odd results: 5

💡 Hint: Use for i in range(1, 11) and f"{n} x {i:2d} = {result:3d}" for the aligned format. The accumulator for the sum starts at 0 before the loop and adds each result inside. Count even and odd with two separate counters.


Python loops exercises — Intermediate Level

Exercise 3 — Compound interest calculator

Write a program that calculates how an investment grows with compound interest year by year. Ask for the initial capital, annual interest rate and number of years, and show a complete table of the growth.

The compound interest formula is: capital × (1 + rate/100)

Initial capital (€): 1000
Annual interest rate (%): 5
Number of years: 10

--- Investment evolution ---
Year  0: 1000.00 €  (+ 0.00 €)
Year  1: 1050.00 €  (+ 50.00 €)
Year  2: 1102.50 €  (+ 52.50 €)
Year  3: 1157.63 €  (+ 55.13 €)
Year  4: 1215.51 €  (+ 57.88 €)
Year  5: 1276.28 €  (+ 60.77 €)
Year  6: 1340.10 €  (+ 63.81 €)
Year  7: 1407.10 €  (+ 67.00 €)
Year  8: 1477.46 €  (+ 70.36 €)
Year  9: 1551.33 €  (+ 73.87 €)
Year 10: 1628.89 €  (+ 77.57 €)

Summary:
  Initial capital:   1000.00 €
  Final capital:     1628.89 €
  Total profit:       628.89 €
  Profitability:       62.89%

💡 Hint: Use for year in range(years + 1), include year 0 to show the initial capital. Inside the loop: new_capital = round(capital * (1 + rate/100), 2). The gain for each year is new_capital - capital. After the loop the final capital and total profit are already calculated.


Python loops exercises — Final Challenge

Exercise 4 — Prime number finder

A prime number is one that is only divisible by 1 and itself. Write a program that asks for a number n and finds all primes up to n. Then show some statistics about the primes found.

Find all primes up to: 50

Primes up to 50:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47

--- Statistics ---
Primes found: 15
Largest prime: 47
Average gap between primes: 3.21
Twin primes (differ by 2): (3,5) (5,7) (11,13) (17,19) (29,31) (41,43)

💡 Hints:

  • A number is prime if no number from 2 to √n divides it exactly. You don’t need to check up to n, just up to int(n**0.5) + 1
  • Use nested loops: the outer for goes through each candidate number, the inner checks if it’s divisible by any smaller number
  • Use a flag variable is_prime = True and set it to False if you find a divisor
  • Twin primes: iterate through the list of primes found and check if primes[i+1] - primes[i] == 2

Commented solutions

Solution Exercise 1:

# FizzBuzz
for i in range(1, 101):
    if i % 3 == 0 and i % 5 == 0:    # most specific first
        print("FizzBuzz")
    elif i % 3 == 0:
        print("Fizz")
    elif i % 5 == 0:
        print("Buzz")
    else:
        print(i)

Solution Exercise 2:

# Multiplication table generator
n = int(input("Number: "))

print(f"\nMultiplication table for {n}:")
print("─" * 29)

total = 0
even_count = 0
odd_count = 0

for i in range(1, 11):
    result = n * i
    parity = "even" if result % 2 == 0 else "odd"
    print(f"{n:2d} x {i:2d} = {result:3d}  ({parity})")
    total += result
    if result % 2 == 0:
        even_count += 1
    else:
        odd_count += 1

print("─" * 29)
print(f"Sum of results: {total}")
print(f"Even results: {even_count} | Odd results: {odd_count}")

Solution Exercise 3:

# Compound interest calculator
capital = float(input("Initial capital (€): "))
rate = float(input("Annual interest rate (%): "))
years = int(input("Number of years: "))

print(f"\n--- Investment evolution ---")
print(f"Year  0: {capital:.2f} €  (+ 0.00 €)")

initial = capital

for year in range(1, years + 1):
    new_capital = round(capital * (1 + rate / 100), 2)
    gain = round(new_capital - capital, 2)
    print(f"Year {year:2d}: {new_capital:.2f} €  (+ {gain:.2f} €)")
    capital = new_capital

total_profit = round(capital - initial, 2)
profitability = round((total_profit / initial) * 100, 2)

print(f"\nSummary:")
print(f"  Initial capital:   {initial:.2f} €")
print(f"  Final capital:     {capital:.2f} €")
print(f"  Total profit:      {total_profit:.2f} €")
print(f"  Profitability:     {profitability:.2f}%")

Solution Exercise 4:

# Prime number finder
n = int(input("Find all primes up to: "))

primes = []

for candidate in range(2, n + 1):
    is_prime = True
    limit = int(candidate ** 0.5) + 1

    for divisor in range(2, limit):
        if candidate % divisor == 0:
            is_prime = False
            break

    if is_prime:
        primes.append(candidate)

print(f"\nPrimes up to {n}:")
print(" ".join(map(str, primes)))

# Statistics
if primes:
    print(f"\n--- Statistics ---")
    print(f"Primes found: {len(primes)}")
    print(f"Largest prime: {primes[-1]}")

    if len(primes) > 1:
        gaps = [primes[i+1] - primes[i] for i in range(len(primes)-1)]
        avg_gap = round(sum(gaps) / len(gaps), 2)
        print(f"Average gap between primes: {avg_gap}")

        twins = [(primes[i], primes[i+1])
                 for i in range(len(primes)-1)
                 if primes[i+1] - primes[i] == 2]

        if twins:
            twins_str = " ".join([f"({a},{b})" for a, b in twins])
            print(f"Twin primes (differ by 2): {twins_str}")
        else:
            print("No twin primes found in this range")

Cheat sheet — Python loops

# ============================================
# CHEAT SHEET — Python Loops
# Sergio Learns · sergiolearns.com
# ============================================

# FOR LOOP — known repetitions
for element in sequence:
    code_block

for i in range(n):              # 0 to n-1
for i in range(start, end):     # start to end-1
for i in range(start, end, step): # with jumps
for i in range(n, 0, -1):      # reverse (n down to 1)

# WHILE LOOP — condition-based
while condition:
    code_block
    # ALWAYS update the condition inside

# FOR vs WHILE
# for  → know how many times → lists, range, strings
# while → don't know → validation, games, search

# BREAK — exit loop immediately
for i in range(10):
    if i == 5:
        break        # → 0, 1, 2, 3, 4

# CONTINUE — skip current iteration
for i in range(10):
    if i == 5:
        continue     # → 0, 1, 2, 3, 4, 6, 7, 8, 9

# NESTED LOOPS
for i in range(rows):
    for j in range(cols):     # runs completely for each i
        code_block

# ACCUMULATOR PATTERN
total = 0                     # 1. initialise BEFORE loop
for value in sequence:
    total += value            # 2. update INSIDE loop
average = total / len(sequence)  # 3. use AFTER loop

# COUNTER PATTERN
count = 0
for value in sequence:
    if condition(value):
        count += 1

# PRIME CHECK PATTERN
is_prime = True
for divisor in range(2, int(n**0.5) + 1):
    if n % divisor == 0:
        is_prime = False
        break

# INPUT VALIDATION WITH WHILE
value = int(input("Enter value: "))
while value < 0 or value > 100:
    print("Invalid — try again")
    value = int(input("Enter value: "))

# FIZZBUZZ PATTERN — check most specific condition first
if n % 3 == 0 and n % 5 == 0:    # 1. both — most specific
    print("FizzBuzz")
elif n % 3 == 0:                   # 2. just 3
    print("Fizz")
elif n % 5 == 0:                   # 3. just 5
    print("Buzz")
else:                              # 4. neither
    print(n)

# RANGE COMMON MISTAKE
range(10)      # → 0, 1, 2, ..., 9   (NOT 10)
range(1, 11)   # → 1, 2, ..., 10    (to get 1 to 10)
range(5, 0, -1) # → 5, 4, 3, 2, 1  (reverse)

# COMMON ERRORS
# 1. Infinite loop — forgetting to update condition → Ctrl+C to stop
# 2. range(n) goes to n-1, not n
# 3. Missing : after for/while → SyntaxError
# 4. Wrong indentation → IndentationError
# 5. Accumulator not initialised before loop → NameError
# 6. FizzBuzz — most specific condition must come first

Similar Posts

One Comment

Leave a Reply

Your email address will not be published. Required fields are marked *