Python While Loops – Repeat Until You’re Done!

⏱ 5 min read · Skill: Beginner

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

Python

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

Python

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

Python

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

Python

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

Python

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?




Common Errors to Watch Out For




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!



Ready to go deeper? Explore more Python essentials: Lists, List Comprehensions, For Loops, and String Functions.