Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you break a while loop from outside the loop?

Can you break a while loop from outside the loop? Here's a (very simple) example of what I'm trying to do: I want to ask for continuous inside a While loop, but when the input is 'exit', I want the while loop to break!

active = True

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

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

1 Answers

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.

like image 62
thefourtheye Avatar answered Dec 30 '25 19:12

thefourtheye