问题
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