Python while Loop (Infinite Loop, break, continue)
This article explains a while
loop in Python.
Unlike a for
loop, which sequentially processes iterable elements such as a list
, a while
loop repeats as long as its condition evaluates to True
.
See the following article for information on a for
loop. A for
loop is better suited when you need to process elements from iterables, such as a list
, or when you want to execute a loop a specific number of times.
An infinite loop can be implemented using a for
loop and the functions of the itertools
module instead of using a while
loop. Infinite loops with counters and similar use cases can often be written more easily using these functions.
Basic syntax of while
loops in Python
A while
loop in Python is written as follows:
while condition:
... <do something>
i = 0
while i < 3:
print(i)
i += 1
# 0
# 1
# 2
You can specify multiple conditions for the condition
part with and
or or
.
Break a while
loop: break
Use break
to break a while
loop.
i = 0
while i < 3:
print(i)
if i == 1:
print('!!BREAK!!')
break
i += 1
# 0
# 1
# !!BREAK!!
Continue to the next iteration: continue
You can skip the current iteration and move to the next one using the continue
statement. break
terminates the entire while
loop, whereas continue
only skips the remaining code in the current iteration.
while i < 3:
if i == 1:
print('!!CONTINUE!!')
i += 1
continue
print(i)
i += 1
# 0
# !!CONTINUE!!
# 2
Note that if you write code that updates a variable used in the condition, such as i += 1
, after the continue
statement, the variable will not be updated. As a result, the loop may not terminate as expected.
Details on forced termination are described at the end.
Execute code after normal termination: else
Use else
to execute something after the while
loop has been completed successfully.
i = 0
while i < 3:
print(i)
i += 1
else:
print('!!FINISH!!')
# 0
# 1
# 2
# !!FINISH!!
If the loop is terminated by break
, the code block in the else
clause will not be executed.
i = 0
while i < 3:
print(i)
if i == 1:
print('!!BREAK!!')
break
i += 1
else:
print('!!FINISH!!')
# 0
# 1
# !!BREAK!!
When the loop completes normally, even if continue
has been used within the loop, the code block in the else
clause will still be executed.
i = 0
while i < 3:
if i == 1:
print('!!SKIP!!')
i += 1
continue
print(i)
i += 1
else:
print('!!FINISH!!')
# 0
# !!SKIP!!
# 2
# !!FINISH!!
Infinite loop with while
statement: while True:
If the condition in the while
statement is always True
, the loop will never end, and execution will repeat infinitely.
In the following example, the Unix time is acquired using time.time()
. The elapsed time is then measured and used to set the condition for when to break out of the loop.
import time
start = time.time()
while True:
time.sleep(1)
print('processing...')
if time.time() - start > 5:
print('!!BREAK!!')
break
# processing...
# processing...
# processing...
# processing...
# processing...
# !!BREAK!!
For example, since non-zero numbers and non-empty strings are considered True
, a statement like while 1:
will create an infinite loop.
start = time.time()
while 1:
time.sleep(1)
print('processing...')
if time.time() - start > 5:
print('!!BREAK!!')
break
# processing...
# processing...
# processing...
# processing...
# processing...
# !!BREAK!!
In the sample code above, an infinite loop is used for explanation; however, the same operation can be performed without an infinite loop, as shown below.
start = time.time()
while time.time() - start <= 5:
time.sleep(1)
print('processing...')
else:
print('!!FINISH!!')
# processing...
# processing...
# processing...
# processing...
# processing...
# !!FINISH!!
Stop the infinite loop using keyboard interrupt (ctrl + c
)
To stop the infinite loop using keyboard interrupt instead of setting break
, you can catch the KeyboardInterrupt
.
try:
while True:
time.sleep(1)
print('processing...')
except KeyboardInterrupt:
print('!!FINISH!!')
If you press ctrl + c
in the running terminal (Mac) or command prompt (Windows cmd.exe
), the while
loop will be terminated, and the except
clause will be executed.
See the following article for exception handling.
Forced termination
If you make a mistake in setting the condition, the process may fall into an infinite loop and never end.
It can be forcibly terminated in the following ways.
- Press
ctrl + c
in the running terminal - End the process in Activity Monitor or Task Manager
- Find the process name
Python
and kill it
- Find the process name