简体   繁体   English

为什么我不能突围?

[英]Why Can't I break out of the loop?

Python beginner here. Python初学者在这里。 Sorry if it's a basic python concept 抱歉,这是基本的python概念

over = False

def run():
    user_input = input("Over? (y/n): ")
    if(user_input == 'y'):
        over = True

while not over:
    run()

Although the input is 'y' the loop doesn't stop. 尽管输入为“ y”,循环不会停止。

You need to write global over , so function run() will change global variable 您需要编写global over ,因此函数run()将更改全局变量

over = False

def run():
    global over
    user_input = input("Over? (y/n): ")
    if(user_input == 'y'):
        over = True

while not over:
    run()

You shouldn't be using a global variable here. 您不应该在这里使用全局变量。 Return a boolean, and call run as the condition of the loop. 返回一个布尔值,并调用run作为循环的条件。 (At this point, you may want to reconsider the name run as well.) (此时,您可能还需要重新考虑run名称。)

def run():
    user_input = input("Over? (y/n)")
    return user_input == 'y'

while run():
    ...

You are setting the local variable over inside the function run() , but you aren't passing it out to the scope from which it was called. 要设置局部变量over函数内部run()但你不能传递出来,从它被调用的范围。 Instead return the value to the calling scope like this: 而是将值返回到调用范围,如下所示:

over = False

def run():
    user_input = input("Over? (y/n): ")
    if(user_input == 'y'):
        over = True
    else:
        over = False
    return over

while not over:
    over = run()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM