Skip to main content
 首页 » 编程设计

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

2025年05月04日26leader

我不明白为什么它一直重复该函数,即使满足将 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() 

请您参考如下方法:

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

检查一下

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

使用全局是编写代码的一个坏标志。 相反,您删除了代码中的大量代码,使其行数更少。 引用这个

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