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 4Infinite 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
| for | while |
|---|---|
| Known number of iterations | Unknown number of iterations |
| Iterate over a sequence | Repeat until a condition changes |
| for item in list: | while condition: |
| Cannot easily infinite loop | Can 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.
Comments
Comments
Post a Comment