Keyboard Shortcuts N Next post
P Previous post
S Save / unsave
R Read aloud
T Toggle theme
/ Focus search
Esc Close panels
🔥
Ready to read...
Loops Module 2 - Control Flow Python Python Basics Python Programming: From Zero to Real-World Applications

while Loops in Python - Repeating Until a Condition

Reviewed & accurate
AI Summary

What You Will Learn

Beginner

  • How to use while loops
  • Avoiding infinite loops
  • When to use while vs for
Terminalpython
# Basic while loop
count = 0
while count < 5:
    print(count)
    count += 1   # IMPORTANT: increment to avoid infinite loop!
# 0 1 2 3 4
Infinite loops
If you forget to update the condition inside the loop, it runs forever. Always ensure the loop variable changes. Use Ctrl+C to stop a runaway loop.

while with User Input

Terminalpython
# Keep asking until valid input
while True:
    response = input("Enter 'quit' to stop: ")
    if response == "quit":
        break
    print(f"You said: {response}")

while vs for

forwhile
Known number of iterationsUnknown number of iterations
Iterate over a sequenceRepeat until a condition changes
for item in list:while condition:
Cannot easily infinite loopCan easily infinite loop

Practical Exercise

Write a while loop that counts from 1 to 10
Write a while loop that asks for input until user types 'stop'
Print all even numbers from 0 to 20 with a while loop
Add 1 to a total until total reaches 100

Key Takeaways

  • while repeats while condition is True.
  • ALWAYS update the loop variable to avoid infinite loops.
  • while True + break for user input loops.
  • for = known iterations. while = unknown iterations.
  • Ctrl+C stops an infinite loop.
Previously: Lesson 11 covered for loops.
Today: You learned: Repeat code until a condition becomes False.
Next: Lesson 13 covers break and continue.
Test Your Knowledge
How did you find this?

Comments

Join the discussion! Sign in with your Google or Blogger account, or comment as Anonymous - no account needed. For quick questions, also reach me on Telegram @cytestch.

Comments