Skip to content Skip to sidebar Skip to footer

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 '

Solution 1:

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

definputHandler(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.

definputHandler(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 initer(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.

Solution 2:

Others have already stated why your code fails. Alternatively you break it down to some very simple logic.

whileTrue:
    userInput = input("Input here: ")
    if userInput == 'exit':
        break

Solution 3:

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

global active
active = TruedefinputHandler(value):
    global active
    if value == 'exit':
        active = Falsewhile active:
    userInput = input("Input here: ")
    inputHandler(userInput)

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

Post a Comment for "Can You Break A While Loop From Outside The Loop?"