Techniques to Exit Nested Loops in Python
This article explains several Python techniques—using identical break conditions, flag variables, exceptions, loop‑else clauses, and function returns—to exit nested loops, demonstrated through a prime‑number game where the program stops when a non‑prime input is entered.
Python provides two loop structures, while and for . When you need to terminate loops early, the break statement works, but breaking out of multiple nested loops requires additional techniques.
We illustrate several methods using a simple prime-number game where the user repeatedly inputs numbers; the game ends when a non‑prime is entered.
Using identical break conditions in each loop
This approach places a break in both the inner and outer loops, checking for a divisor and exiting when found.
<code># 此程序仅为演示相同条件跳出循环,输入2的时候会报错
while True:
number = int(input('Please input an integer: '))
for i in range(2, number):
if number % i == 0:
break
if number % i == 0:
break
print('Game Over')</code>Using a flag variable
A flag is set to indicate whether the inner loop found a divisor; after the inner loop, the outer loop checks the flag and breaks accordingly.
<code>while True:
number = int(input('Please input an integer: '))
flag = True # 默认number是质数
for i in range(2, number):
if number % i == 0:
flag = False
break
if not flag:
break
print('Game Over')</code>Raising an exception
When break is insufficient, you can raise and catch an exception (e.g., StopIteration ) to exit multiple loops.
<code>try:
while True:
number = int(input('Please input an integer: '))
for i in range(2, number):
if number % i == 0:
raise StopIteration
except StopIteration:
print('Game Over')</code>Combining with else
Python's loop‑ else construct can be used so that the outer loop’s else runs only when the inner loop does not break, allowing controlled exit.
<code>while True:
number = int(input('Please input an integer: '))
for i in range(2, number):
if number % i == 0:
break
else:
continue
break
print('Game Over')</code>Using return inside a function
Encapsulating the nested loops in a function lets a return statement terminate the loops and exit the function.
<code>def prime_game():
while True:
number = int(input('Please input an integer: '))
for i in range(2, number):
if number % i == 0:
return
prime_game()
print('Game Over')</code>These techniques provide flexible ways to break out of nested loops in Python.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.