Python While Loops – Repeat Until You’re Done!
Last Updated: September 2025
Sometimes you want Python to keep doing something until a condition is no longer true — that’s when a while
loop becomes your best friend! It’s super helpful when you don’t know in advance how many times you need to repeat something.
What’s a While Loop?
A while
loop keeps running as long as a condition stays true. Once the condition becomes false, Python stops the loop. This makes it perfect for situations where you’re waiting for something to happen!
Example 1: Counting Up
i = 1
while i <= 5:
print(i)
i += 1
🔹Here, the loop keeps counting from 1 to 5. Don’t forget to update the value inside the loop, or it could go on forever!
Example 2: Asking for Correct Input
password = ""
while password != "python123":
password = input("Enter the password: ")
print("Access granted!")
🔹The loop keeps asking until you enter the correct password. Perfect for making programs interactive!
Example 3: Using break
to Exit Early
i = 0
while True:
print(i)
i += 1
if i == 3:
break
🔹break
lets you stop the loop even if the condition hasn’t turned false yet. This way you can exit early when needed!
Example 4: Skipping Iterations with continue
i = 0
while i < 5:
i += 1
if i == 3:
continue
print(i)
🔹This loop skips printing the number 3 and continues with the next iteration — neat for filtering unwanted cases!
Example 5: Loops with Else
i = 1
while i <= 3:
print(i)
i += 1
else:
print("Loop finished!")
🔹You can attach else
to a while
loop to run code after it completes. Great for final messages or cleanup!
Why Learn While Loops?
- They help you run code repeatedly when you don’t know how many times ahead of time.
- Useful for input validation, waiting for events, and more.
- Every interactive Python program uses loops like this!
Common Errors to Watch Out For
- Forgetting to update the condition: If the condition never changes, the loop will run forever!
- Using
=
instead of==
: One is for assigning, the other for checking equality—don’t mix them up! - Infinite loops without
break
: A loop that never ends can freeze your program. Always plan an exit!
Practice Challenge
Create a program that keeps asking for your favorite fruit until you type “stop”. Use a while
loop and print a fun message each time!