Module 5 Practice Problems
15 problems to master loops in Python
Problem 1: Print 1 to 20
EasyUse a for loop to print the numbers 1 through 20, each on its own line.
Use range(1, 21) since range does not include the stop value.
for i in range(1, 21): print(i)
Problem 2: Sum of Numbers
EasyAsk the user for a number n. Calculate and print the sum of all integers from 1 to n.
Use an accumulator variable. Start with total = 0 and add each number in the range.
n = int(input("Enter a number: ")) total = 0 for i in range(1, n + 1): total += i print(f"Sum of 1 to {n}: {total}")
Problem 3: Countdown
EasyAsk the user for a starting number. Count down from that number to 1, then print "Liftoff!"
Use range(start, 0, -1) or a while loop that decrements.
start = int(input("Start countdown from: ")) for i in range(start, 0, -1): print(f"{i}...") print("Liftoff!")
Problem 4: Even Numbers Only
EasyPrint all even numbers from 2 to 50 (inclusive) on a single line separated by spaces.
Use range(2, 51, 2) to step by 2.
for i in range(2, 51, 2): print(i, end=" ")
Problem 5: Character Counter
EasyAsk the user for a string and a character. Count how many times that character appears in the string.
Loop through each character in the string. Use a counter variable.
text = input("Enter a string: ") char = input("Enter a character to count: ") count = 0 for letter in text: if letter == char: count += 1 print(f"'{char}' appears {count} time(s)")
Problem 6: Factorial
MediumAsk for a number and calculate its factorial. For example, 5! = 5 × 4 × 3 × 2 × 1 = 120.
Start with result = 1 and multiply by each number from 1 to n.
n = int(input("Enter a number: ")) result = 1 for i in range(1, n + 1): result *= i print(f"{n}! = {result}")
Problem 7: Guessing Game
MediumPick a secret number (hardcode it). Let the user guess repeatedly. After each guess, say "too high", "too low", or "correct!" Count the number of attempts.
Use a while loop that continues until the guess matches. Increment an attempts counter each loop.
secret = 42 attempts = 0 while True: guess = int(input("Guess the number (1-100): ")) attempts += 1 if guess < secret: print("Too low!") elif guess > secret: print("Too high!") else: print(f"Correct! You got it in {attempts} attempts.") break
Problem 8: Reverse a String
MediumAsk the user for a string. Use a loop to build and print the reversed string (do not use slicing).
Start with an empty string reversed_str = "". Add each character to the front: reversed_str = char + reversed_str.
text = input("Enter a string: ") reversed_str = "" for char in text: reversed_str = char + reversed_str print(f"Reversed: {reversed_str}")
Problem 9: FizzBuzz
MediumPrint numbers from 1 to 30. For multiples of 3, print "Fizz". For multiples of 5, print "Buzz". For multiples of both, print "FizzBuzz".
Check divisibility by both 3 and 5 first (using and), then by 3 alone, then by 5 alone.
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)
Problem 10: Input Validation
MediumKeep asking the user for a test score (0-100) until they enter a valid number. Then print the score.
Use a while loop. Keep looping as long as the input is outside the valid range.
while True: score = int(input("Enter a score (0-100): ")) if 0 <= score <= 100: break print("Invalid! Score must be between 0 and 100.") print(f"Valid score entered: {score}")
Problem 11: Fibonacci Sequence
HardPrint the first 15 Fibonacci numbers. The sequence starts with 0, 1, and each subsequent number is the sum of the previous two: 0, 1, 1, 2, 3, 5, 8, ...
Use two variables a = 0 and b = 1. Each iteration: print a, then update: a, b = b, a + b.
a = 0 b = 1 for i in range(15): print(a, end=" ") a, b = b, a + b
Problem 12: Star Rectangle
HardAsk the user for the number of rows and columns. Print a rectangle of stars using nested loops.
Outer loop for rows, inner loop for columns. Use print("*", end=" ") inside and print() after each row.
rows = int(input("Rows: ")) cols = int(input("Columns: ")) for i in range(rows): for j in range(cols): print("* ", end="") print()
Problem 13: Prime Numbers
HardPrint all prime numbers between 2 and 50. A prime number is only divisible by 1 and itself.
For each number, check if it is divisible by any number from 2 to that number-1. If none divide evenly, it is prime. Use a flag variable or the for-else pattern.
for num in range(2, 51): is_prime = True for i in range(2, num): if num % i == 0: is_prime = False break if is_prime: print(num, end=" ")
Problem 14: Multiplication Table
HardPrint a formatted multiplication table from 1 to 10. Align the numbers neatly in columns.
Use nested for loops. Format each number with f"{value:4}" for right-aligned 4-character width.
# Header row print(" |", end="") for i in range(1, 11): print(f"{i:4}", end="") print() print("---+" + "----" * 10) # Table body for i in range(1, 11): print(f"{i:2} |", end="") for j in range(1, 11): print(f"{i*j:4}", end="") print()
Problem 15: Diamond Pattern
HardAsk the user for a size n. Print a diamond pattern with 2n-1 rows. For example, n=3:
* *** ***** *** *
Split it into two halves: top (including middle) and bottom. For the top: row i has (n-i-1) spaces and (2*i+1) stars. For the bottom: reverse the pattern.
n = int(input("Enter size: ")) # Top half (including middle) for i in range(n): spaces = " " * (n - i - 1) stars = "*" * (2 * i + 1) print(spaces + stars) # Bottom half for i in range(n - 2, -1, -1): spaces = " " * (n - i - 1) stars = "*" * (2 * i + 1) print(spaces + stars)