In your case, in inputHandler, you are creating a new variable called active and storing False in it. This will not affect the module level active.

To fix this, you need to explicitly say that active is not a new variable, but the one declared at the top of the module, with the global keyword, like this

def inputHandler(value):
    global active

    if value == 'exit':
        active = False

But, please note that the proper way to do this would be to return the result of inputHandler and store it back in active.

def inputHandler(value):
    return value != 'exit'

while active:
    userInput = input("Input here: ")
    active = inputHandler(userInput)

If you look at the while loop, we used while active:. In Python you either have to use == to compare the values, or simply rely on the truthiness of the value. is operator should be used only when you need to check if the values are one and the same.


But, if you totally want to avoid this, you can simply use iter function which breaks out automatically when the sentinel value is met.

for value in iter(lambda: input("Input here: "), 'exit'):
    inputHandler(value)

Now, iter will keep executing the function passed to it, till the function returns the sentinel value (second parameter) passed to it.

Answer from thefourtheye on Stack Overflow
🌐
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.
Top answer
1 of 3
6

In your case, in inputHandler, you are creating a new variable called active and storing False in it. This will not affect the module level active.

To fix this, you need to explicitly say that active is not a new variable, but the one declared at the top of the module, with the global keyword, like this

def inputHandler(value):
    global active

    if value == 'exit':
        active = False

But, please note that the proper way to do this would be to return the result of inputHandler and store it back in active.

def inputHandler(value):
    return value != 'exit'

while active:
    userInput = input("Input here: ")
    active = inputHandler(userInput)

If you look at the while loop, we used while active:. In Python you either have to use == to compare the values, or simply rely on the truthiness of the value. is operator should be used only when you need to check if the values are one and the same.


But, if you totally want to avoid this, you can simply use iter function which breaks out automatically when the sentinel value is met.

for value in iter(lambda: input("Input here: "), 'exit'):
    inputHandler(value)

Now, iter will keep executing the function passed to it, till the function returns the sentinel value (second parameter) passed to it.

2 of 3
1

Yes, you can indeed do it that way, with a tweak: make active global.

global active
active = True

def inputHandler(value):
    global active
    if value == 'exit':
        active = False

while active:
    userInput = input("Input here: ")
    inputHandler(userInput)

(I also changed while active is True to just while active because the former is redundant.)

Discussions

Python: 'break' outside loop - Stack Overflow
In the following python code: narg=len(sys.argv) print "@length arg= ", narg if narg == 1: print "@Usage: input_filename nelements nintervals" break I get: More on stackoverflow.com
🌐 stackoverflow.com
How to break out of while loop in Python? - Stack Overflow
I have to make this game for my comp class, and I can't figure out how how break out of this loop. I have to play against the "computer," by rolling bigger numbers, and seeing who has the More on stackoverflow.com
🌐 stackoverflow.com
break outside of loop?
You cannot break outside a loop… and, really, the idea of doing so doesn’t make any sense. What you probably want to do is define a function that does what you want to do, and then inside a loop call that function again as many times as needed. More on reddit.com
🌐 r/learnpython
13
2
September 4, 2022
python - How to break while loop while outside of the terminal - Stack Overflow
I'm trying to program a macro for BTD6 using Python with pydirectinput and pyautogui. I'm having problems when trying to implement a way to break out of a while loop while outside the terminal. If ... More on stackoverflow.com
🌐 stackoverflow.com
September 29, 2024
🌐
Reddit
reddit.com › r/learnpython › how can i break out of a while loop immediately and at any point during the while loop.
r/learnpython on Reddit: How can I break out of a while loop immediately and at any point during the while loop.
June 23, 2023 -

I have a long while loop, it has a lot of code in it and a lot of delays.

I want to break out of the loop when a condition is met but I need to break out of it instantly. The only thing I can think of, is to print if statements constantly through the loop, checking if the condition is true, but this seems a little silly because it would have literally 100s of break statements.

Is there any better way to do this without typing break statements after every single line of code, that seems impractical because there's 100s of lines of code in the while loop, it takes around 10 minutes to finish and I need it to break instantly

🌐
DigitalOcean
digitalocean.com › community › tutorials › how-to-use-break-continue-and-pass-statements-when-working-with-loops-in-python-3
How To Use break, continue, and pass Statements in Python | DigitalOcean
April 24, 2026 - Within the loop is also a print() statement that will execute with each iteration of the for loop until the loop breaks, since it is after the break statement. Let’s place a final print() statement outside of the for loop to know when you are out of the loop.
Top answer
1 of 6
102

Because break cannot be used to break out of an if statement -it can only break out of loops. That's the way Python (and most other languages) are specified to behave.

What are you trying to do? Perhaps you should use sys.exit() or return instead?

2 of 6
6

Some other common ways this error may show up:

1. Incorrect indentation

Indentation is extremely important in Python. It helps determine the grouping of statements, so if you don't group statements correctly, your code will not work as expected.

Suppose you perform some computation inside a loop and depending on its result, either continue on in the loop or break out of the loop. If you inadvertently put the if-else block outside the loop because you missed the indentation, you will get the error in the title. To solve the error in that case, use indentation correctly.

For example the following will raise the error in the title.

for i in range(10):
    print(i)        # <--- do something
if i % 3:           # <--- break out of loop on some condition
    break

The following solves this error:

for i in range(10):
    print(i)
    if i % 3:       # <--- use indentation correctly
        break       # <--- to break out of loop

Of course your program will probably have much more code than this but the general structure might be the same in which case, see if the proposed solution applies.

I think this issue is exacerbated by some IDEs that use 2 spaces (not the 4 recommended by PEP8) per indentation level by default, which sometimes makes it difficult to see where indentation ends.

2. Include a break statement inside a function

The break statement must be explicitly inside the loop definition; it cannot be nested in a function that will be executed inside a loop.

For example, the following raises the error in the title:

def func(x):
    x *= 10
    if x > 20:     # <--- break out of loop on condition
        break

for i in range(10):
    func(i)        # <--- call function

To solve it, move the conditional check out of the function and put it in the loop.

def func(x):
    x *= 10
    return x       # <--- return the value

for i in range(10):
    x = func(i)    # <--- call function
    if x > 20:     # <--- check condition
        break
🌐
LearnDataSci
learndatasci.com › solutions › python-break
Python break statement: break for loops and while loops – LearnDataSci
Can you see why? while True: res = input("Enter the number 5: ") try: res = int(res) except: pass if res == 5: print("Thanks!") break ... It can be hard to spot when one of your background processes gets caught in an infinite loop. You're not breaking any of Python's rules by getting stuck in a loop, so there are often not any helpful error messages to let you know what you've done wrong.
🌐
Tutorialspoint
tutorialspoint.com › python › python_loop_control.htm
Python Break, Continue and Pass Statements
The break statement in Python terminates the current loop and resumes execution at the next statement, just like the traditional break found in C. The most common use for break is when some external condition is triggered requiring a hasty exit ...
Find elsewhere
🌐
Reddit
reddit.com › r/learnpython › break outside of loop?
r/learnpython on Reddit: break outside of loop?
September 4, 2022 -

So I am making a Point of sale system code in python with my group and I am wondering how do I make the code run again so you can make multiple order?

Please check the bottom of the code:

https://pastebin.com/f39GpLwT

edit: also i forgot to mention but pls help me in improving the code. I am begginer in python so i only know if else elif

edit: problem solved! I just forgot to indent and put "while True:" on top

🌐
Learn Python
learnpython.dev › 02-introduction-to-python › 110-control-statements-looping › 40-break-continue
break, continue, and return :: Learn Python by Nina Zakharenko
break and continue allow you to control the flow of your loops. They’re a concept that beginners to Python tend to misunderstand, so pay careful attention. Using break The break statement will completely break out of the current loop, meaning it won’t run any more of the statements contained ...
🌐
Python Morsels
pythonmorsels.com › breaking-out-of-a-loop
Breaking out of a loop - Python Morsels
June 26, 2025 - This code works just like before, but it can even work from outside a function. Even if our code was inside a function, it is sometimes useful to break out of a loop without also returning from our function. ... from random import randint number = randint(1, 99) print("I'm thinking of a number from 1 to 99. Guess the number!") while True: guess = input("What's your guess?
🌐
Real Python
realpython.com › python-break
How to Exit Loops Early With the Python break Keyword – Real Python
February 25, 2025 - This tutorial guides you through using break in both for and while loops. You’ll also briefly explore the continue keyword, which complements break by skipping the current loop iteration. By the end of this tutorial, you’ll understand that: A break in Python is a keyword that lets you exit a loop immediately, stopping further iterations. Using break outside of loops doesn’t make sense because it’s specifically designed to exit loops early.
Top answer
1 of 3
2

Because you are new to programming, I will get a few basic tips in my answer too.

INFINITE LOOP

You are trying to start an infinite loop by first settingagain = 'y' and afterwards you are using this variable to evaluate a while loop. Because you are not changing the value of y, it is better to not use a variable to create this infinite loop. Instead, try this:

while True:
    (some code)

DEFINE FUNCTION IN LOOP

You're defining the function main() inside of the while loop. As far as I can tell, there is no use for that. Just leave out the first while loop. If you define a function, it is permanent (much like a variable), so no need to redefine it everytime. Using your code, you won't even get to call the function, because you never end the first loop.

CONTINUE/BREAK NOT IN LOOP

The error is quite self-explanaitory, but here we go. If you would ever end the first loop (which in this case, you won't), the next thing you do is call your function main(). This will generate a number and make the user guess it until he got it right. When that happens, you get out of that function (and loop).

Next, you ask if the user would like to play again. This is just an input statement. You store the answer in the variable 'again'. You check, with an if statement (note that this is not a loop!) what the answer is. You want the user to play again if he typed 'y', so instead of using again != 'y', you could use the following:

if again == 'y':
    main()  # you call the function to play again

If 'n' was typed in, you want to exit the script, which you do not by typing break, because you are not in a loop, just in an if-statement. You can either type nothing, which will just go out of the if-statement. Because there is nothing after the if, you will exit the script. You could also useexit(), which will immediately exit the script.

Lastly, you want to repeat the question if neither of these two things were answered. You can put the if-statement inside of a loop. You can (if you want) use your break and continue when doing this, but you mostly want to avoid those two. Here is an example:

while True:
    again = raw_imput('y for again or n to stop')
    if again == 'y':
        main()
        exit()  # use this if you don't want to ask to play again after the 2nd game
    elif again == 'n':
        print('bye!')
        exit()
    # no need for an 'else' this way
    # every exit() can be replaced by a 'break' if you really want to

BASIC BREAK/CONTINUE USAGE

Finally, here is some basic usage of break and continue. People generally tend to avoid them, but it's nice to know what they do.

Using break will exit the most inner loop you are currently in, but you can only use it inside of a loop, obviously (for-loops or while-loops).

Using continue will immediately restart the most inner loop you are currently in, regardless of what code comes next. Also, only usable inside of a loop.

EVERYTHING TOGETHER

import random
again = 'y'


def main():
    print ("gues a number between 0 - 10.")
    nummer = random.randint(1,10)
    found = False
    while not found:
        usergues = input("your gues?")
        if usergues == nummer:
            print ('Your the man')
            found = True
    else:
        print ('to bad dude try again')

main()
while True:
    again = input('would you like to play again press y to play again   press n yo exit')
    if again == 'n':
        print ('bye!')
        exit()  # you could use break here too
    elif again == 'y':
        main()
        exit()  # you can remove this if you want to keep asking after every game
    else:
        print ('oeps i don\'t know what you mean plz enter y to play again or n to exit')

I hope I helped you!

2 of 3
0

You loops and def are all muddled, you want something more like:

import random

again = 'y'

while again == "y" :
    print "gues a number between 0 - 10."
    nummer = random.randint(1,10)
    found = False

    while not found:
        usergues = input("your gues?")
        if usergues == nummer:
            print 'Your the man'
            found = True
        else:
            print 'to bad dude try again'

    while True:
        again = raw_input('would you like to play again press y to play again   press n to exit')
        if again == 'n':
            break
        elif again != 'y':
            print 'oeps i don\'t know what you mean plz enter y to play again or n to exit'
        else:
            break
🌐
Programiz
programiz.com › python-programming › break-continue
Python break and continue (With Examples)
We can skip the current iteration of the while loop using the continue statement. For example, # Program to print odd numbers from 1 to 10 num = 0 while num < 10: num += 1 if (num % 2) == 0: continue print(num)
🌐
freeCodeCamp
freecodecamp.org › news › python-break-and-python-continue-how-to-skip-to-the-next-function
Python Break and Python Continue – How to Skip to the Next Function
March 14, 2022 - As you can see, the number 50 is not printed to the console because of the continue statement inside the if statement. The break and continue statements in Python are used to skip parts of the current loop or break out of the loop completely.
🌐
Problem Solving with Python
problemsolvingwithpython.com › 09-Loops › 09.03-Break-and-Continue
Break and Continue - Problem Solving with Python
Break and continue are two ways to modify the behavior of for loops and while loops. In Python, the keyword break causes the program to exit a loop early.
🌐
EyeHunts
tutorial.eyehunts.com › home › break outside loop python | example code
Break Outside loop Python | Example code - EyeHunts
March 29, 2022 - It stops a loop from executing for any further iterations. The break statement can be used in any type of loop – while loop and for-loop. The break keyword is only be used inside a loop. But if we try to break outside of a loop, then you will get the “SyntaxError: ‘break’ outside loop” error.
🌐
Bobby Hadz
bobbyhadz.com › blog › python-syntaxerror-break-outside-loop
SyntaxError: 'break' outside loop in Python [Solved] | bobbyhadz
April 8, 2024 - The Python "SyntaxError: 'break' outside loop" occurs when we use the break statement outside of a loop. To solve the error, use a return statement to return a value from a function, or use the sys.exit() method to exit the interpreter.