为什么它重复,即使WHILE循环更改为False

时间:2017-05-08 10:32:40

标签: python python-3.x while-loop

我无法理解为什么它会不断重复该函数,即使满足将while循环更改为false的条件。这是我想要做的一个例子:

confirm=True

def program():
    name=input("What is your name? ")
    country=input("What is your country? ")

    runagain=input("Would you like to run again? Enter no or yes: ")
    if runagain=="no":
        print("Thank You")
        confirm=False
    else:
        print("Rerun")
        confirm=True

while confirm==True:
    program()

1 个答案:

答案 0 :(得分:3)

您必须在方法程序中使用全局确认。

检查出来

confirm=True

def program():
    global confirm
    name=input("What is your name? ")
    country=input("What is your country? ")

    runagain=input("Would you like to run again? Enter no or yes: ")
    if runagain=="no":
        print("Thank You")
        confirm=False
    else:
        print("Rerun")
        confirm=True

while confirm:
    program()

使用global是编写代码的一个坏兆头。 相反,您删除了代码中的大量代码,从而减少了行数。 请参阅此

def program():
    name=input("What is your name? ")
    country=input("What is your country? ")
    runagain=input("Would you like to run again? Enter no or yes: ")
    if runagain=="no":
        print("Thank You")
        exit()
    else:
        print("Rerun")

while 1:
    program()