Table of Contents
Practice Style for These Exercises
In this chapter you will:
- Practice both
whileandforloops - Combine loops with
ifstatements, variables, and user input - Learn to recognize common loop patterns
Each exercise includes:
- A short task description
- A suggestion: try yourself first
- A sample solution you can compare with your own
Run these examples, then change numbers, texts, and conditions to see what happens.
Warm-Up Exercises
Exercise 1: Count from 1 to 10 (for loop)
Task:
Use a for loop to print the numbers from 1 to 10, one per line.
Try it yourself first, then compare:
for i in range(1, 11):
print(i)Variations to try:
- Count from 5 to 15
- Count by 2s (2, 4, 6, …, 20)
- Print
"Number:"before each number
Exercise 2: Count down (while loop)
Task:
Use a while loop to count down from 5 to 1, then print "Liftoff!".
count = 5
while count >= 1:
print(count)
count = count - 1
print("Liftoff!")Variations:
- Start from 10
- Change the final message
- Count down by 2 (10, 8, 6, …)
Exercise 3: Sum of first N numbers
Task:
Ask the user for a positive integer n.
Use a loop to calculate the sum:
$1 + 2 + 3 + \dots + n$
Example: if the user enters 5, the sum is $1 + 2 + 3 + 4 + 5 = 15$.
n = int(input("Enter a positive integer: "))
total = 0
for i in range(1, n + 1):
total = total + i
print("The sum of numbers from 1 to", n, "is", total)Variations:
- Ask for two numbers
startandendand sum fromstarttoend - Use a
whileloop instead of aforloop
Pattern: Repeating Until a Condition Is Met
These exercises use loops to keep asking until the user gives a valid answer.
Exercise 4: Ask for a number between 1 and 10
Task:
Keep asking the user for a number between 1 and 10 (inclusive).
If the user enters a number outside this range, ask again.
Only stop when the user enters a valid number.
number = int(input("Enter a number between 1 and 10: "))
while number < 1 or number > 10:
print("That is not between 1 and 10. Try again.")
number = int(input("Enter a number between 1 and 10: "))
print("Thanks! You entered:", number)Variations:
- Accept only even numbers between 1 and 10
- Accept only odd numbers between 1 and 20
- Allow the user to type
0to give up
Exercise 5: Password attempt (simple)
Task:
Set a secret password in your code (for example "python123").
Keep asking the user to type the password until they get it right.
Then print "Access granted".
secret_password = "python123"
guess = input("Enter the password: ")
while guess != secret_password:
print("Wrong password, try again.")
guess = input("Enter the password: ")
print("Access granted")Variations:
- Limit the user to 3 attempts (use a counter)
- After 3 wrong attempts, print
"Too many tries"and stop
Pattern: Loops with Counters and Totals
Exercise 6: Average of test scores
Task:
Ask the user how many test scores they want to enter.
Use a loop to read that many scores and calculate the average.
Example:
- User enters
3 - Scores:
80,90,100 - Average = $(80 + 90 + 100) / 3 = 90$
count = int(input("How many scores will you enter? "))
total = 0
for i in range(count):
score = float(input("Enter score #" + str(i + 1) + ": "))
total = total + score
average = total / count
print("Average score:", average)Variations:
- Track the highest score entered
- Track the lowest score entered
- Use
whileinstead offor
Exercise 7: Multiplication table
Task:
Ask the user for a number, then print its multiplication table from 1 to 10.
Example if user enters 3:
3 x 1 = 33 x 2 = 6- …
3 x 10 = 30
number = int(input("Enter a number: "))
for i in range(1, 11):
result = number * i
print(number, "x", i, "=", result)Variations:
- Print up to 12 instead of 10
- Create tables for numbers 1 to 5 (nested loops)
Example nested version for 1 to 5:
for n in range(1, 6):
print("Table for", n)
for i in range(1, 11):
print(n, "x", i, "=", n * i)
print() # blank linePattern: Loops with break and continue
Exercise 8: Guess the secret number (simple version)
Task:
Choose a secret number in your code (for example 7).
Use a loop to keep asking the user to guess the number.
- If the guess is correct, print
"Correct!"and stop the loop - Use
breakto exit the loop
secret = 7
while True:
guess = int(input("Guess the number: "))
if guess == secret:
print("Correct!")
break
else:
print("Wrong, try again.")Variations:
- Tell the user
"Too high"or"Too low" - Limit to a certain number of guesses and stop after that
Exercise 9: Skip negative numbers with continue
Task:
Ask the user to enter 5 numbers.
Ignore (skip) negative numbers using continue.
Print the sum of only the non-negative numbers.
total = 0
for i in range(5):
num = float(input("Enter number #" + str(i + 1) + ": "))
if num < 0:
print("Negative number ignored.")
continue
total = total + num
print("Sum of non-negative numbers:", total)Variations:
- Count how many negative numbers were entered
- Ask until the user enters
0, then stop (while loop)
Pattern: Working with Strings in Loops
Exercise 10: Count vowels in a word
Task:
Ask the user for a word.
Use a loop to count how many vowels it contains (a e i o u, both lowercase and uppercase).
text = input("Enter a word: ")
vowels = "aeiouAEIOU"
count = 0
for ch in text:
if ch in vowels:
count = count + 1
print("Number of vowels:", count)Variations:
- Count consonants as well
- Ask for a sentence instead of a single word
Exercise 11: Reverse a string (manual way)
Task:
Ask the user for some text.
Use a loop to build a new string that is the reverse of the original.
Example:
"hello" → "olleh"
text = input("Enter text: ")
reversed_text = ""
for ch in text:
reversed_text = ch + reversed_text
print("Reversed:", reversed_text)Variations:
- Check if the text is a palindrome (reads the same forwards and backwards)
- Ignore spaces when checking for palindrome
Pattern: Nested Loops
Exercise 12: Simple square of stars
Task:
Ask the user for a size n.
Print an n x n square of * characters using nested loops.
Example if n = 3:
***
***
***
n = int(input("Enter size: "))
for row in range(n):
line = ""
for col in range(n):
line = line + "*"
print(line)Variations:
- Print a rectangle with different width and height
- Print a right-angled triangle instead of a square
Triangle example:
n = int(input("Enter height: "))
for row in range(1, n + 1):
line = ""
for col in range(row):
line = line + "*"
print(line)Mixed Practice: Small Loop-Based Programs
Exercise 13: Menu until exit
Task:
Create a simple text menu that keeps showing until the user chooses to exit.
Example menu:
- Say hello
- Say goodbye
- Exit
Use a while loop. When the user chooses 3, exit the loop.
choice = 0
while choice != 3:
print("Menu:")
print("1. Say hello")
print("2. Say goodbye")
print("3. Exit")
choice = int(input("Enter your choice: "))
if choice == 1:
print("Hello!")
elif choice == 2:
print("Goodbye!")
elif choice == 3:
print("Exiting...")
else:
print("Invalid choice, try again.")
print("Program ended.")Variations:
- Add more menu options
- Use a string choice (
"h"for hello,"g"for goodbye,"q"for quit)
Exercise 14: Simple number statistics
Task:
Keep asking the user for numbers until they enter 0.
Then print:
- How many numbers were entered (excluding the final
0) - The sum of the numbers
- The average of the numbers
Only do the calculations if at least one non-zero number was entered.
count = 0
total = 0.0
while True:
num = float(input("Enter a number (0 to stop): "))
if num == 0:
break
total = total + num
count = count + 1
if count > 0:
average = total / count
print("Count:", count)
print("Sum:", total)
print("Average:", average)
else:
print("No numbers were entered.")Variations:
- Track the minimum and maximum numbers
- Ignore negative numbers
Exercise 15: FizzBuzz (classic loop challenge)
Task:
Use a loop to print the numbers from 1 to 30. For each number:
- If it is divisible by 3, print
"Fizz"instead of the number - If it is divisible by 5, print
"Buzz"instead of the number - If it is divisible by both 3 and 5, print
"FizzBuzz" - Otherwise, just print the number
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)Variations:
- Ask the user for the maximum number instead of always using 30
- Use different words, like
"Foo"and"Bar"
How to Practice Further
To get comfortable with loops:
- Take any exercise here and:
- Rewrite it using the other loop type (
for↔while) - Change the conditions or range
- Add input checks (for example, no negative numbers)
- Invent your own tasks, such as:
- Repeatedly asking quiz questions until the user types
"quit" - Simulating a simple counter that goes up or down based on user input
- Printing simple patterns with characters (triangles, stairs, borders)
The more small loop-based problems you solve, the more natural loops will feel in your programs.