What is the difference between a for loop and while loop in Python? When to use each?
I understand both can repeat code. But I am not sure when to choose one over the other. My textbook uses for loops for everything but my tutor says while loops are sometimes better.
1 Answer
For loop: use when you know exactly how many times to repeat, or when iterating over a sequence (list, range, string). Example: for i in range(10) — runs exactly 10 times. While loop: use when you repeat UNTIL a condition changes and you do NOT know in advance how many iterations. Example: while user_input != "quit" — runs until user decides to stop. For loops are safer (guaranteed to terminate if the sequence is finite). While loops can create infinite loops if the condition never becomes false. Rule of thumb: definite iteration (known count) = for loop. Indefinite iteration (condition-based) = while loop.
No comments yet — start the discussion.