While Loop
suggest changeA while loop will cause the loop statements to be executed until the loop condition is falsey. The following code will execute the loop statements a total of 4 times.
i = 0
while i < 4:
# loop statements
i = i + 1
While the above loop can easily be translated into a more elegant for loop, while loops are useful for checking if some condition has been met. The following loop will continue to execute until myObject is ready.
myObject = anObject()
while myObject.isNotReady():
myObject.tryToGetReady()
A while loop also keeps running while its condition stays true. A nonzero number is true, including a nonzero complex value:
import cmath
complex_num = cmath.sqrt(-1)
while complex_num: # 1j is true, and this condition never changes
print(complex_num) # Prints 1j forever
If the condition is always true the while loop will run forever (infinite loop) if it is not terminated by a break or return statement or an exception.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents