KAHIBARO Bookshelves
Discord Login Register

7.6. Loop exercises

Practice Style for These Exercises

In this chapter you will:

  • Practice both while and for loops
  • Combine loops with if statements, variables, and user input
  • Learn to recognize common loop patterns

Each exercise includes:

  1. A short task description
  2. A suggestion: try yourself first
  3. 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 start and end and sum from start to end
  • Use a while loop instead of a for loop

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 0 to 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 while instead of for

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 = 3
  • 3 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 line

Pattern: 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 break to 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:

  1. Say hello
  2. Say goodbye
  3. 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.

Views: 0

Comments

Please login to add a comment.

Don't have an account? Register now!

Where to Move

Move chapter:

  • ☰ 1. Chapter 1: What Is Programming?
    • ☰ 1.1. What is a computer program?
      • ☰ 1.2. What is Python?
        • ☰ 1.3. Where is Python used?
          • ☰ 1.4. How programming helps solve problems
            • ☰ 1.5. Your first Python program
            • ☰ 2. Chapter 2: Setting Up Python
              • ☰ 2.1. Installing Python (Windows / macOS / Linux)
                • ☰ 2.2. Using Python in the terminal
                  • ☰ 2.3. Using an IDE (IDLE / VS Code)
                    • ☰ 2.4. Running Python scripts
                      • ☰ 2.5. Python interactive mode
                      • ☰ 3. Chapter 3: Variables and Data Types
                        • ☰ 3.1. What is a variable?
                          • ☰ 3.2. Creating variables
                            • ☰ 3.3. Numbers
                              • ☰ 3.4. Test
                                • ☰ 3.5. Boolean values
                                  • ☰ 3.6. Type checking
                                  • ☰ 4. Chapter 4: Basic Operations
                                    • ☰ 4.1. Arithmetic operations
                                      • ☰ 4.2. Working with numbers
                                        • ☰ 4.3. String operations
                                          • ☰ 4.4. Combining text and variables
                                            • ☰ 4.5. Comments in Python
                                            • ☰ 5. Chapter 5: User Input and Output
                                              • ☰ 5.1. Getting input from the user
                                                • ☰ 5.2. Converting input to numbers
                                                  • ☰ 5.3. Formatting output
                                                    • ☰ 5.4. Writing interactive programs
                                                    • ☰ 6. Chapter 6: Conditions
                                                      • ☰ 6.1. Comparison operators
                                                        • ☰ 6.2. Logical operators
                                                          • ☰ 6.3. if, elif, else
                                                            • ☰ 6.4. Nested conditions
                                                              • ☰ 6.5. Common beginner mistakes
                                                              • ☰ 7. Chapter 7: Loops
                                                                • ☰ 7.1. Why loops are useful
                                                                  • ☰ 7.2. for loops
                                                                    • ☰ 7.3. while loops
                                                                      • ☰ 7.4. Loop counters
                                                                        • ☰ 7.5. break and continue
                                                                          • ☰ 7.6. Loop exercises
                                                                          • ☰ 8. Chapter 8: Data Collections
                                                                            • ☰ 8.1. Lists
                                                                              • ☰ 8.2. Tuples
                                                                                • ☰ 8.3. Dictionaries
                                                                                  • ☰ 8.4. Sets (basics)
                                                                                    • ☰ 8.5. Choosing the right data structure
                                                                                    • ☰ 9. Chapter 9: Functions
                                                                                      • ☰ 9.1. Why functions matter
                                                                                        • ☰ 9.2. Defining functions
                                                                                          • ☰ 9.3. Parameters and arguments
                                                                                            • ☰ 9.4. Return values
                                                                                              • ☰ 9.5. Scope (local vs global)
                                                                                                • ☰ 9.6. Reusing code
                                                                                                • ☰ 10. Chapter 10: Working with Files
                                                                                                  • ☰ 10.1. What is a file?
                                                                                                    • ☰ 10.2. Reading text files
                                                                                                      • ☰ 10.3. Writing and appending files
                                                                                                        • ☰ 10.4. File paths
                                                                                                          • ☰ 10.5. Simple file-based programs
                                                                                                          • ☰ 11. Chapter 11: Errors and Debugging
                                                                                                            • ☰ 11.1. Types of errors
                                                                                                              • ☰ 11.2. Reading error messages
                                                                                                                • ☰ 11.3. Common beginner errors
                                                                                                                  • ☰ 11.4. try and except
                                                                                                                    • ☰ 11.5. Debugging strategies
                                                                                                                    • ☰ 12. Chapter 12: Using Python Libraries
                                                                                                                      • ☰ 12.1. What is a library?
                                                                                                                        • ☰ 12.2. Importing modules
                                                                                                                          • ☰ 12.3. Standard libraries
                                                                                                                            • ☰ 12.3.1. math
                                                                                                                              • ☰ 12.3.2. random
                                                                                                                                • ☰ 12.3.3. datetime
                                                                                                                                • ☰ 12.4. Installing external libraries with pip
                                                                                                                                • ☰ 13. Chapter 13: Object-Oriented Programming
                                                                                                                                  • ☰ 13.1. What is object-oriented programming?
                                                                                                                                    • ☰ 13.2. Classes and objects
                                                                                                                                      • ☰ 13.3. The `__init__` method
                                                                                                                                        • ☰ 13.4. Attributes and methods
                                                                                                                                          • ☰ 13.5. Encapsulation
                                                                                                                                            • ☰ 13.6. Inheritance (basics)
                                                                                                                                              • ☰ 13.7. Simple OOP examples
                                                                                                                                              • ☰ 14. Chapter 14: Automation with Python
                                                                                                                                                • ☰ 14.1. What is automation?
                                                                                                                                                  • ☰ 14.2. Automating simple tasks
                                                                                                                                                    • ☰ 14.3. Working with files and folders
                                                                                                                                                      • ☰ 14.4. Automating text processing
                                                                                                                                                        • ☰ 14.5. Scheduling scripts
                                                                                                                                                          • ☰ 14.6. Practical automation examples
                                                                                                                                                          • ☰ 15. Chapter 15: Web Development with Python
                                                                                                                                                            • ☰ 15.1. How the web works (basic overview)
                                                                                                                                                              • ☰ 15.2. Introduction to Flask
                                                                                                                                                                • ☰ 15.3. Creating a simple web server
                                                                                                                                                                  • ☰ 15.4. Routing and templates
                                                                                                                                                                    • ☰ 15.5. Handling user input (forms)
                                                                                                                                                                      • ☰ 15.6. Very basic APIs
                                                                                                                                                                      • ☰ 16. Chapter 16: Data Science with Python
                                                                                                                                                                        • ☰ 16.1. What is data science?
                                                                                                                                                                          • ☰ 16.2. Working with data
                                                                                                                                                                            • ☰ 16.3. Introduction to NumPy
                                                                                                                                                                              • ☰ 16.4. Introduction to pandas
                                                                                                                                                                                • ☰ 16.5. Data visualization with matplotlib
                                                                                                                                                                                  • ☰ 16.6. Simple data analysis examples
                                                                                                                                                                                  • ☰ 17. Chapter 17: Mini Projects
                                                                                                                                                                                    • ☰ 17.1. Number guessing game
                                                                                                                                                                                      • ☰ 17.2. Simple calculator
                                                                                                                                                                                        • ☰ 17.3. To-do list
                                                                                                                                                                                          • ☰ 17.4. Password generator
                                                                                                                                                                                            • ☰ 17.5. Quiz application
                                                                                                                                                                                              • ☰ 17.6. Small web or data project
                                                                                                                                                                                              • ☰ 18. Chapter 18: Next Steps
                                                                                                                                                                                                • ☰ 18.1. How to practice Python
                                                                                                                                                                                                  • ☰ 18.2. Writing clean and readable code
                                                                                                                                                                                                    • ☰ 18.3. Choosing a specialization
                                                                                                                                                                                                      • ☰ 18.3.1. Web development
                                                                                                                                                                                                        • ☰ 18.3.2. Data science
                                                                                                                                                                                                          • ☰ 18.3.3. Automation
                                                                                                                                                                                                            • ☰ 18.3.4. Software development
                                                                                                                                                                                                            • ☰ 18.4. Learning resources and communities
                                                                                                                                                                                                            • ☰ 19. Appendix
                                                                                                                                                                                                              • ☰ 19.1. Python syntax cheat sheet
                                                                                                                                                                                                                • ☰ 19.2. Common errors and solutions
                                                                                                                                                                                                                  • ☰ 19.3. Glossary of terms