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.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
