Kahibaro
Discord Login Register

Loop exercises

Practice Style for These Exercises

In this chapter you will:

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:

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:

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:

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:

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:

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:

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:

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:

number = int(input("Enter a number: "))
for i in range(1, 11):
    result = number * i
    print(number, "x", i, "=", result)

Variations:

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.

secret = 7
while True:
    guess = int(input("Guess the number: "))
    if guess == secret:
        print("Correct!")
        break
    else:
        print("Wrong, try again.")

Variations:

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:

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:

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:

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:

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:

Exercise 14: Simple number statistics

Task:
Keep asking the user for numbers until they enter 0.
Then print:

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:

Exercise 15: FizzBuzz (classic loop challenge)

Task:
Use a loop to print the numbers from 1 to 30. For each 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:

How to Practice Further

To get comfortable with loops:

The more small loop-based problems you solve, the more natural loops will feel in your programs.

Views: 19

Comments

Please login to add a comment.

Don't have an account? Register now!