Exercises: Repetition: Loops and Iteration
These exercises progress from concept checks through increasingly challenging loop problems. Type every solution yourself — don't copy-paste.
Difficulty Guide: - ⭐ Foundational (5-10 min each) - ⭐⭐ Intermediate (10-20 min each) - ⭐⭐⭐ Challenging (20-40 min each) - ⭐⭐⭐⭐ Advanced/Research (40+ min each)
Part A: for Loops and range() ⭐
A.1. Write a program that prints the numbers 1 through 20, one per line.
A.2. Write a program that prints the even numbers from 2 to 30 on a single line, separated by spaces. (Hint: use the end parameter in print() and range() with a step.)
A.3. Write a program that uses a for loop to print a countdown from 10 to 1, followed by "Blastoff!" on the final line.
A.4. Predict the output of each code snippet without running it. Then run it to verify.
a)
for i in range(4):
print(i * 3)
b)
for i in range(2, 10, 3):
print(i, end=" ")
c)
for i in range(5, 0, -2):
print(i)
A.5. Write a program that asks the user for a positive integer n and prints all multiples of 5 from 5 to 5n.
Example: if the user enters 4, print 5 10 15 20.
A.6. Write a program that iterates over the string "Mississippi" and prints each character on its own line, along with its position (starting from 0).
Expected output (first few lines):
Position 0: M
Position 1: i
Position 2: s
Position 3: s
...
Part B: while Loops ⭐-⭐⭐
B.1. Write a program that uses a while loop to print the numbers 1 through 10. (Yes, a for loop is better for this — the point is practicing while syntax.)
B.2. Write an input validation loop that asks the user to enter a number between 1 and 100 (inclusive). If they enter a number outside that range, print an error message and ask again. Once they enter a valid number, print "Thank you! You entered: {number}".
B.3. Write a program that repeatedly asks the user for words (one at a time) until they type "quit". After they quit, print how many words they entered (not counting "quit").
Example session:
Enter a word (or 'quit' to stop): hello
Enter a word (or 'quit' to stop): world
Enter a word (or 'quit' to stop): python
Enter a word (or 'quit' to stop): quit
You entered 3 words.
B.4. Write a "guess the number" game. The secret number is 42. The user guesses repeatedly until they get it right. After each wrong guess, tell them whether the secret number is higher or lower. When they get it, tell them how many guesses it took.
Example session:
Guess the secret number (1-100): 50
Too high! Try again.
Guess the secret number (1-100): 25
Too low! Try again.
Guess the secret number (1-100): 42
Correct! You got it in 3 guesses.
B.5. Write a program that computes the sum of all digits in a positive integer entered by the user. Use a while loop with integer division (//) and modulo (%) to extract digits.
Example: Input 12345 → Output Sum of digits: 15 (because 1+2+3+4+5 = 15).
Hint: 12345 % 10 gives 5 (the last digit). 12345 // 10 gives 1234 (removes the last digit).
Part C: Accumulator Pattern ⭐⭐
C.1. Write a program that asks the user for 5 test scores and computes: - The total - The average - The highest score - The lowest score
Use the accumulator pattern for each.
C.2. Write a program that computes the factorial of a number entered by the user. The factorial of n (written n!) is the product of all positive integers from 1 to n. For example, 5! = 5 × 4 × 3 × 2 × 1 = 120.
Hint: Initialize your accumulator to 1 (not 0 — why?).
C.3. Write a program that asks the user for a sentence and counts how many words it contains. (Hint: count the spaces and add 1. For now, assume words are separated by single spaces. In Chapter 7, you'll learn a much better way with .split().)
C.4. Write a program that takes a string from the user and builds a new string that contains only the consonants (non-vowel letters). Use the accumulator pattern with string concatenation.
Example: Input "Hello World" → Output "Hll Wrld".
C.5. Elena needs to compute a running total of donations. Write a program that asks the user to enter donation amounts one at a time (enter 0 to stop). After each donation, print the running total. At the end, print the total, the number of donations, and the average donation.
Example session:
Enter donation amount (0 to stop): 150
Running total: $150.00
Enter donation amount (0 to stop): 75.50
Running total: $225.50
Enter donation amount (0 to stop): 200
Running total: $425.50
Enter donation amount (0 to stop): 0
Summary:
Total donations: $425.50
Number of donations: 3
Average donation: $141.83
Part D: Nested Loops and Patterns ⭐⭐-⭐⭐⭐
D.1. Write a program that prints this rectangle of stars:
*****
*****
*****
*****
Use a nested loop (outer loop for rows, inner loop for columns). The rectangle should be 5 wide and 4 tall.
D.2. Write a program that prints this right triangle pattern for a size entered by the user:
For size 5:
*
**
***
****
*****
D.3. Write a program that prints an inverted right triangle:
For size 5:
*****
****
***
**
*
D.4. Write a program that prints a multiplication table from 1×1 to 10×10, neatly formatted with row and column headers. Each cell should be right-aligned to 4 characters wide.
D.5. Write a program that prints a hollow square. For size 5:
*****
* *
* *
* *
*****
Hint: a star is printed when the row is the first or last, OR the column is the first or last. Otherwise, print a space.
Part E: Loop Control (break, continue, else) ⭐⭐
E.1. Write a program that searches for the first number between 100 and 200 that is divisible by both 7 and 3. Use break to stop searching once found.
E.2. Write a program that prints all numbers from 1 to 30, except those divisible by 4. Use continue to skip the divisible-by-4 numbers.
E.3. Write a password checker. The correct password is "python123". The user gets 3 attempts. Use a for loop with range(3) and break when they enter the correct password. Use the loop's else clause to print "Account locked" if all 3 attempts fail.
Part F: Choosing the Right Loop ⭐⭐
F.1. For each scenario below, state whether you'd use a for loop or a while loop, and explain why in one sentence:
a) Printing every character in a user's name b) Asking the user to re-enter input until it's valid c) Computing the average of exactly 30 test scores d) Running a cash register until the cashier presses 'Q' e) Counting down from a number to zero f) Reading lines from a file until you find a specific keyword
Part M: Mixed Practice (Interleaved) ⭐⭐-⭐⭐⭐
These problems mix concepts from Chapters 3-5.
M.1. Write a temperature converter that asks the user how many temperatures they want to convert (Chapter 3: variables), then for each one asks for a Fahrenheit temperature (Chapter 5: loop), converts it to Celsius (Chapter 3: expressions), and classifies it as "Freezing" (below 0°C), "Cold" (0-15°C), "Comfortable" (15-25°C), or "Hot" (above 25°C) using conditionals (Chapter 4).
Formula: C = (F - 32) × 5/9
M.2. Write a program that generates the first n terms of the Fibonacci sequence, where n is entered by the user. The Fibonacci sequence starts with 0, 1, and each subsequent number is the sum of the two before it: 0, 1, 1, 2, 3, 5, 8, 13, 21, ...
Hint: You need two variables to track the "previous two" values. Update them each iteration.
M.3. The Collatz conjecture says that if you start with any positive integer and repeatedly apply the following rules, you'll eventually reach 1: - If the number is even, divide it by 2 - If the number is odd, multiply by 3 and add 1
Write a program that takes a starting number from the user and prints the entire Collatz sequence until it reaches 1, along with how many steps it took.
Example: Starting with 6: 6 → 3 → 10 → 5 → 16 → 8 → 4 → 2 → 1 (8 steps)
Part G: Synthesis & Critical Thinking ⭐⭐⭐-⭐⭐⭐⭐
G.1. Write a program that checks whether a number entered by the user is prime. A prime number is divisible only by 1 and itself. Your program should handle edge cases: 1 is not prime, 2 is prime, negative numbers are not prime.
Optimization hint: You only need to check divisors up to the square root of the number (think about why — if you find a factor larger than the square root, the corresponding smaller factor would have already been found).
G.2. Write a program that plays a simplified version of the card game "21" (Blackjack). The computer deals random "cards" (numbers 1-10) one at a time. After each card, the player sees their total and chooses to "hit" (get another card) or "stand" (stop). If the total exceeds 21, the player busts and loses. If they stand at 21 or below, they win if their total is 17 or higher (simplified rule).
Hint: Use import random and random.randint(1, 10) to generate random card values.
Solutions
Selected solutions in appendices/answers-to-selected.md.