computer science

What is the difference between a for loop and while loop in Python? When to use each?

RJRahul Joshi · 12 Asked 14d ago 220 views 1 answer

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

MPMeera Pillai ✓ Accepted · 14d ago ▲ 16

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.

Log in to post your own answer or join the discussion.

Discussion (0)

No comments yet — start the discussion.

← Back to all questions