Can you break a while loop from outside the loop?

我与影子孤独终老i 提交于 2020-01-04 05:35:14

问题


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:


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:


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

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



回答3:


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.)



来源:https://stackoverflow.com/questions/33906813/can-you-break-a-while-loop-from-outside-the-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!