Use break and continue to do this. Breaking nested loops can be done in Python using the following:

for a in range(...):
   for b in range(..):
      if some condition:
         # break the inner loop
         break
   else:
      # will be called if the previous loop did not end with a `break` 
      continue
   # but here we end up right after breaking the inner loop, so we can
   # simply break the outer loop as well
   break

Another way is to wrap everything in a function and use return to escape from the loop.

Answer from Alexander Gessler on Stack Overflow
Top answer
1 of 7
129

Use break and continue to do this. Breaking nested loops can be done in Python using the following:

for a in range(...):
   for b in range(..):
      if some condition:
         # break the inner loop
         break
   else:
      # will be called if the previous loop did not end with a `break` 
      continue
   # but here we end up right after breaking the inner loop, so we can
   # simply break the outer loop as well
   break

Another way is to wrap everything in a function and use return to escape from the loop.

2 of 7
72

There are several ways to do it:

The simple Way: a sentinel variable

n = L[0][0]
m = len(A)
found = False
for i in range(m):
   if found:
      break
   for j in range(m):
     if L[i][j] != n: 
       found = True
       break

Pros: easy to understand Cons: additional conditional statement for every loop

The hacky Way: raising an exception

n = L[0][0]
m = len(A)

try:
  for x in range(3):
    for z in range(3):
     if L[i][j] != n: 
       raise StopIteration
except StopIteration:
   pass

Pros: very straightforward Cons: you use Exception outside of their semantic

The clean Way: make a function

def is_different_value(l, elem, size):
  for x in range(size):
    for z in range(size):
     if l[i][j] != elem: 
       return True
  return False
   
if is_different_value(L, L[0][0], len(A)):
  print "Doh"

pros: much cleaner and still efficient cons: yet feels like C

The pythonic way: use iteration as it should be

def is_different_value(iterable):
  first = iterable[0][0]
  for l in iterable:
    for elem in l:
       if elem != first: 
          return True
  return False
   
if is_different_value(L):
  print "Doh"

pros: still clean and efficient cons: you reinvdent the wheel

The guru way: use any():

def is_different_value(iterable):
  first = iterable[0][0]
  return any(cell != first for col in iterable for cell in col)

if is_different_value(L):
  print "Doh"

pros: you'll feel empowered with dark powers cons: people that will read you code may start to dislike you

๐ŸŒ
DigitalOcean
digitalocean.com โ€บ community โ€บ tutorials โ€บ how-to-use-break-continue-and-pass-statements-when-working-with-loops-in-python-3
How to Break Out of Multiple Loops in Python | DigitalOcean
August 7, 2025 - For instance, you might encounter ... placeholder for future code. Python provides three powerful statements to handle these cases: break, continue, and pass. The break statement allows you to exit a loop entirely when a specific condition is met, effectively stopping the loop ...
Discussions

How to Break out of a loop without waiting for the current iteration to complete?
Use multiprocessing.Process(), it works like Thread but it has a terminate() method. from multiprocessing import Process import keyboard def main(): while True: func() if __name__ == '__main__': process = Process(target=main) process.start() while process.is_alive(): if keyboard.is_pressed('q'): process.terminate() break More on reddit.com
๐ŸŒ r/learnpython
4
1
March 4, 2023
How to stop an infinite while loop?
while True: print("test") break I assume this is what you're looking for. The break keyword will end any loop (even for loops) and skip to the first command after the loop (as if the loop had ended normally) More on reddit.com
๐ŸŒ r/learnpython
4
0
November 25, 2022
How can I break out of a while loop immediately and at any point during the while loop.
Literally, this is what the break statement does. More on reddit.com
๐ŸŒ r/learnpython
32
0
June 23, 2023
How do i loop my code and stop it with one key press?
You can use pythons internal KeyboardInterupt exception with a try try: while True: do_something() except KeyboardInterrupt: pass For this the exit keystroke would be ctrl+c Or if you want to use a module you can take a look at the Keyboard module and use the keyboard.on_press() while True: # Do your stuff if keyboard.is_pressed("q"): # Key was pressed break For more info you can check out this post on other methods as well. Edit: Adding additional link info, also forgot to put the ctrl+c as the exit for KeyboardInterupt More on reddit.com
๐ŸŒ r/learnpython
4
10
December 21, 2021
๐ŸŒ
LearnPython.com
learnpython.com โ€บ blog โ€บ end-loop-python
How to End Loops in Python | LearnPython.com
December 16, 2021 - If you want to see some concrete examples of how to apply these two functions for efficient looping, check out this article. The break statement is the first of three loop control statements in Python.
๐ŸŒ
Enki
enki.com โ€บ post โ€บ how-to-exit-a-loop-in-python
Enki | Blog - How to Exit a Loop in Python
The break statement helps us terminate or exit a loop before its natural end. It stops the loop immediately, bypassing any remaining iterations. This loop would normally run forever because while True sets an infinite loop. Here, break halts it once i reaches 5.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-break-statement
Python break statement - GeeksforGeeks
The break statement can be used within a for loop to exit the loop before it has iterated over all items, based on a specified condition. ... A while loop in Python repeatedly executes a block of code as long as a specified condition is True.
Published ย  2 weeks ago
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ python_for_loops.asp
Python For Loops
Note: The else block will NOT be executed if the loop is stopped by a break statement. Break the loop when x is 3, and see what happens with the else block: for x in range(6): if x == 3: break print(x) else: print("Finally finished!") Try it ...
Find elsewhere
๐ŸŒ
Python Morsels
pythonmorsels.com โ€บ breaking-out-of-a-loop
Breaking out of a loop - Python Morsels
June 26, 2025 - In addition to the break statement, Python also has a continue statement: with open("numbers.txt") as number_file: total = 0 for line in number_file: for number in line.split(): n = float(number) if n < 0: print("Skipping negative", n) continue ...
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ break-in-python-nested-for-loop-break-if-condition-met-example
Break in Python โ€“ Nested For Loop Break if Condition Met Example
May 17, 2022 - The code above prints a range of ... terminated instead of printing all the way to 9. In this section, we'll see how to use the break statement in nested loops....
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ python-break-statement-tutorial
Python Break Statement โ€“ How to Break Out of a For Loop in Python
April 16, 2024 - usernames = ["Jade", "John", "Jane", ... value of i is "John": if i == "John". In the body of the if statement, we used the break statement. So the loop will stop when it finds an element in the list with the value of ...
๐ŸŒ
Real Python
realpython.com โ€บ python-break
How to Exit Loops Early With the Python break Keyword โ€“ Real Python
April 16, 2025 - Hereโ€™s how your adjusted code might look in this case, using a break statement: ... >>> scores = [90, 30, 50, 70, 85, 35] >>> num_failed_scores = 0 >>> pass_score = 60 >>> needs_tutoring = "No" >>> for score in scores: ...
๐ŸŒ
Finxter
blog.finxter.com โ€บ home โ€บ learn python blog โ€บ how to stop a for loop in python
How to Stop a For Loop in Python - Be on the Right Side of Change
September 28, 2022 - The most natural way to end a Python for loop is to deplete the iterator defined in the loop expression for <var> in <iterator>. If the iteratorโ€™s next() method doesnโ€™t return a value anymore, the program proceeds with the next statement ...
๐ŸŒ
LearnDataSci
learndatasci.com โ€บ solutions โ€บ python-break
Python break statement: break for loops and while loops โ€“ LearnDataSci
The flowchart below shows the process that Python is following in our example: ... break will terminate the nearest encompassing loop, but this can get a little confusing when working with nested loops. It's important to remember that break only ends the inner-most loop when used in a script with multiple active loops. ... strings = ['This ', 'is ', 'a ', 'list '] # iterate through each string in the list for string in strings: # iterate through each character in the string for char in string: print(char) if char == 'i': # if the character is equal to 'i', terminate the nested for loop print('break\n') break
๐ŸŒ
Tutorialspoint
tutorialspoint.com โ€บ python โ€บ python_break_statement.htm
Python - break Statement
In this example, we will see the working of break statement in for loop. for letter in 'Python': if letter == 'h': break print ("Current Letter :", letter) print ("Good bye!")
๐ŸŒ
Programiz
programiz.com โ€บ python-programming โ€บ break-continue
Python break and continue (With Examples)
We can use the break statement with the for loop to terminate the loop when a certain condition is met. For example, ... Note: We can also terminate the while loop using a break statement.
๐ŸŒ
Pierian Training
pieriantraining.com โ€บ home โ€บ python tutorial: how to stop an infinite loop in python
Python Tutorial: How to stop an infinite loop in Python - Pierian Training
April 12, 2023 - To avoid infinite loops in your Python programs, itโ€™s important to carefully check your loop conditions and make sure they are correct. Additionally, you can use tools like break statements or timeouts to stop a loop that has been running for too long.
๐ŸŒ
Python Tutorial
pythontutorial.net โ€บ home โ€บ python basics โ€บ python break
Python break
March 26, 2025 - Once you enter quit, the condition ... in lowercase so that you can enter Quit, QUIT or quit to exit the program. Use the Python break statement to terminate a for loop or a while loop prematurely....
๐ŸŒ
Problem Solving with Python
problemsolvingwithpython.com โ€บ 09-Loops โ€บ 09.03-Break-and-Continue
Break and Continue - Problem Solving with Python
An example using break in a for loop is below. ... When the loop hits i=3, break is encountered and the program exits the loop. An example using break in a while loop is below. ... In Python, the keyword continue causes the program to stop running code in a loop and start back at the top of ...
๐ŸŒ
Real Python
realpython.com โ€บ python-while-loop
Python while Loops: Repeating Tasks Conditionally โ€“ Real Python
March 3, 2025 - Stopping monitoring.") break time.sleep(1) In this loop, you use True as the loop condition, which generates a continually running loop. Then, you read the temperature sensor and print the current temperature value. If the temperature is equal to or greater than 25 degrees, you break out of the loop. Otherwise, you wait for a second and read the sensor again.
๐ŸŒ
Coursera
coursera.org โ€บ tutorials โ€บ python-break
How to Use Python Break | Coursera
When working with loops, remember that indentation tells Python which statements are inside the loop and which are outside the loop. Your break statement should follow your if statement and be indented.