Python for vs while Loops: When to Use Each, With Simple Examples

Loops let a program repeat a block of code instead of duplicating it, and Python offers two main types. A for loop iterates once per item in a collection, such as list elements, string characters, or numbers from range(), and it ends automatically when the items run out. A while loop repeats as long as a given condition remains true, making it suitable when the number of repetitions is unknown in advance. A common beginner error is the infinite loop, which occurs when the condition never becomes false because the variable it depends on is not updated inside the loop. The article illustrates this with a countdown example and a password-prompt example, where a while loop is the natural fit.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.

Discussion (0)
Log in to join the discussion and vote.
Log in