Ian*_*Ian 2 python boolean-expression while-loop python-3.x
你能从循环外部打破一个循环吗?这是一个(非常简单)我正在尝试做的例子:我想在While循环中要求连续,但是当输入是'exit'时,我希望while循环中断!
active = True
def inputHandler(value):
if value == 'exit':
active = False
while active is True:
userInput = input("Input here: ")
inputHandler(userInput)
Run Code Online (Sandbox Code Playgroud)
在您的情况下,inputHandler您正在创建一个名为active并存储False在其中的新变量.这不会影响模块级别 active.
要解决这个问题,你需要明确地说这active不是一个新变量,而是在模块顶部声明的变量,带有global关键字,就像这样
def inputHandler(value):
global active
if value == 'exit':
active = False
Run Code Online (Sandbox Code Playgroud)
但是,请注意,执行此操作的正确方法是返回结果inputHandler并将其存储回来active.
def inputHandler(value):
return value != 'exit'
while active:
userInput = input("Input here: ")
active = inputHandler(userInput)
Run Code Online (Sandbox Code Playgroud)
如果你看一下while循环,我们就用了while active:.在Python中,您必须使用==比较值,或者仅仅依赖于值的真实性.is只有在需要检查值是否相同时才应使用运算符.
但是,如果你完全想避免这种情况,你可以简单地使用iter在满足标记值时自动突破的功能.
for value in iter(lambda: input("Input here: "), 'exit'):
inputHandler(value)
Run Code Online (Sandbox Code Playgroud)
现在,iter将继续执行传递给它的函数,直到函数返回传递给它的sentinel值(第二个参数).