beginner

While Loops

Learn to use while loops for condition-based iteration in Python.

While loops provide a different approach to iteration, continuing as long as a condition remains true. They are perfect for situations where you don't know in advance how many iterations you'll need, such as user input validation, game loops, or processing data until a certain condition is met. This exercise teaches you to write safe, effective while loops.

📚 Concepts & Theory

Basic While Loop:

count = 0
while count < 5:
print(count)
count += 1 # Don't forget to update!

Input Validation Example:

password = ""
while password != "secret":
password = input("Enter password: ")
print("Access granted!")

Infinite Loop (Careful!):

while True:
user_input = input("Enter 'quit' to exit: ")
if user_input == "quit":
break

Common Pattern - Counter:

i = 10
while i > 0:
print(f"Countdown: {i}")
i -= 1
print("Liftoff!")

While with Else:

n = 0
while n < 3:
print(n)
n += 1
else:
print("Loop completed normally")

The else block runs if the loop completes without a break.

🎯 Your Challenge

Create a countdown from 5 to 1 using a while loop. Start with a variable `countdown` set to 5. Decrease it by 1 in each iteration. After the loop, set a variable called `message` to "Blastoff!".

📝 Starter Code

Python
# Countdown from 5 to 1
countdown = 5

# Your while loop here
while countdown > 0:
    print(countdown)
    # Decrease countdown
    

# After the loop
message = 
  • Initialize countdown to 5
  • Loop while countdown is greater than 0
  • Print before decreasing the counter
  • Use countdown -= 1 to decrease

Solution

Python
countdown = 5

while countdown > 0:
    print(countdown)
    countdown -= 1

message = "Blastoff!"

Explanation

We start with countdown = 5 and loop while it's greater than 0. Each iteration prints the current value and decreases countdown by 1 using the -= operator. When countdown reaches 0, the condition becomes false and the loop exits. Finally, we set the message variable after the loop.

⚠️ Common Mistakes to Avoid

  • Forgetting to decrease the counter (infinite loop!)
  • Using wrong comparison operator
  • Decreasing before printing (missing 5)
  • Not understanding when the condition is checked

❓ Frequently Asked Questions

The condition will always be true, creating an infinite loop. Your program will run forever until you manually stop it. Always ensure your loop has a way to terminate.
Use while when you don't know how many iterations you need, or when the loop should continue until a specific condition changes.

🔗 Related Concepts