Can a while loop run infinitely in Python?
a) No, while loops always terminate
b) Yes, if the loop condition never becomes false
c) Yes, if the loop contains a break statement
d) No, while loops have a built-in time limit
Answer:
b) Yes, if the loop condition never becomes false
Explanation:
A while
loop in Python can run infinitely if the loop condition never becomes false. This happens if the condition always evaluates to True
and there is no mechanism (like a break
statement) to exit the loop.
while True:
print("This loop runs forever") # Infinite loop
Infinite loops are typically undesirable, but they can be useful in certain scenarios, such as continuously running programs like servers or event listeners, where the program needs to keep running until an external condition occurs.
To avoid accidentally creating an infinite loop, it’s important to ensure that the loop condition will eventually become false or that there is a break
statement or other exit mechanism within the loop.