Python / Core Python Fundamentals Interview Questions
When should you use a while loop instead of a for loop in Python?
Use a while loop when the number of iterations is not known upfront and the loop should continue as long as a condition remains true. A for loop is for iterating over a known sequence; a while loop is for repeating until something changes.
attempts = 0 max_attempts = 3 while attempts < max_attempts: password = input('Enter password: ') if password == 'secret': print('Access granted') break attempts += 1 print(f'{max_attempts - attempts} attempt(s) remaining') else: print('Account locked')
The else clause on a while loop runs only if the condition naturally became False — it does not run if the loop exited via break. This is a clean way to distinguish between 'found it and broke out' versus 'exhausted all attempts'.
Common patterns where while shines: polling a queue until it is empty, reading chunks from a socket until EOF, implementing a game loop that runs until the player quits, or processing a linked list node by node without knowing its length in advance.
The most important thing to guard against is an infinite loop. Always ensure the loop variable is modified inside the loop body or use a break as an exit. A while True: loop is fine if it has a clear break condition; without one, the program hangs.
More Related questions...