Lesson 17 of 21 · 2 min
while vs for — When to Use Which
| Feature | while Loop | for Loop |
|---|---|---|
| Use when | You don't know how many times you will repeat | You know what you are iterating over |
| Controlled by | A condition | A sequence (list, string, range) |
| Risk | Can run forever if condition never becomes False | Always terminates |
| Analogy | Keep pressing snooze while tired | Read every page of a book |
| Example | Wait for correct password | Process every student in a class |
# Use WHILE when you don't know how many times you will repeat:
user_input = "" # start with empty input
while user_input != "quit": # keep asking until user types "quit"
user_input = input("Enter command (or 'quit' to exit): ")
print(f"You entered: {user_input}")
# Use FOR when you know what you are iterating over:
student_names = ["Priya", "Ahmed", "Ravi"] # known list of students
for name in student_names: # go through each student once
print(f"Processing: {name}") # do something for each student