Python Basics — Loops Practice Exercises

2 minute read

Loops Practice Exercises

Test your understanding of for loops, while loops, break/continue, range/enumerate/zip, and nested loops.


Exercise 1: FizzBuzz

Print numbers from 1 to 30. For multiples of 3, print “Fizz”. For multiples of 5, print “Buzz”. For multiples of both, print “FizzBuzz”.

Expected Output (first 15):

1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
Solution
for i in range(1, 31):
    if i % 3 == 0 and i % 5 == 0:
        print("FizzBuzz")
    elif i % 3 == 0:
        print("Fizz")
    elif i % 5 == 0:
        print("Buzz")
    else:
        print(i)

Exercise 2: Collect Valid Scores

Use a while loop to collect exactly 5 valid test scores (0–100) from the user. Skip invalid input with continue. After collecting them, print the average.

Expected Output:

Enter score 1: 85
Enter score 2: 110
  Invalid! Score must be 0-100.
Enter score 2: 92
Enter score 3: abc
  Invalid! Please enter a number.
Enter score 3: 78
Enter score 4: 95
Enter score 5: 88

Scores: [85, 92, 78, 95, 88]
Average: 87.6
Solution
scores = []

while len(scores) < 5:
    try:
        value = input(f"Enter score {len(scores) + 1}: ")
        score = int(value)
    except ValueError:
        print("  Invalid! Please enter a number.")
        continue

    if score < 0 or score > 100:
        print("  Invalid! Score must be 0-100.")
        continue

    scores.append(score)

print(f"\nScores: {scores}")
print(f"Average: {sum(scores) / len(scores):.1f}")

Exercise 3: Student Ranking

Given two lists, use enumerate() and zip() to print a ranked leaderboard.

names = ["Alice", "Bob", "Charlie", "Diana", "Eve"]
scores = [92, 88, 95, 78, 91]

Expected Output:

=== Leaderboard ===
#1  Charlie    95
#2  Alice      92
#3  Eve        91
#4  Bob        88
#5  Diana      78
Solution
names = ["Alice", "Bob", "Charlie", "Diana", "Eve"]
scores = [92, 88, 95, 78, 91]

# Create pairs and sort by score (descending)
paired = list(zip(names, scores))
paired.sort(key=lambda x: x[1], reverse=True)

print("=== Leaderboard ===")
for rank, (name, score) in enumerate(paired, start=1):
    print(f"#{rank}  {name:<10} {score}")

Exercise 4: Diamond Pattern

Print a diamond pattern using nested loops. The width should be based on user input (odd number).

Expected Output (n=5):

    *
   ***
  *****
   ***
    *
Solution
n = int(input("Enter an odd number: "))

# Ensure odd
if n % 2 == 0:
    n += 1
    print(f"Rounded up to {n}")

mid = n // 2

# Top half (including middle)
for i in range(mid + 1):
    spaces = " " * (mid - i)
    stars = "*" * (2 * i + 1)
    print(spaces + stars)

# Bottom half
for i in range(mid - 1, -1, -1):
    spaces = " " * (mid - i)
    stars = "*" * (2 * i + 1)
    print(spaces + stars)

Exercise 5: Prime Number Finder

Write a program that finds and prints all prime numbers from 2 to 100 using a nested loop with break and for-else.

Expected Output:

Prime numbers from 2 to 100:
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97

Total: 25 primes found
Solution
primes = []

for num in range(2, 101):
    for i in range(2, int(num ** 0.5) + 1):
        if num % i == 0:
            break
    else:
        primes.append(num)

print("Prime numbers from 2 to 100:")
print(", ".join(str(p) for p in primes))
print(f"\nTotal: {len(primes)} primes found")

Scoring Guide

Exercises Completed Level
5/5 Expert — Loops mastered!
4/5 Advanced — Solid loop skills
3/5 Intermediate — Good foundation
1-2/5 Beginner — Review loop concepts

Next Chapter: Strings →

Updated: