为什么即使WHILE循环更改为Fals,它仍在重复

2024-10-02 00:26:57 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Tags: 函数nonamefalsetrueinputyouris
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()

如果可能的话,应该避免使用global。尽管使用global可以解决这个问题,但最好避免使用它。你知道吗

如果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")
        return False
    else:
        print("Rerun")
        return True

while program():
    pass

Python是静态范围的

http://python-textbok.readthedocs.io/en/1.0/Variables_and_Scope.html

# This is a global variable
a = 0

if a == 0:
    # This is still a global variable
    b = 1

def my_function(c):
    # this is a local variable
    d = 3
    print(c)
    print(d)

# Now we call the function, passing the value 7 as the first and only parameter
my_function(7)

# a and b still exist
print(a)
print(b)

# c and d don't exist anymore   these statements will give us name errors!
print(c)
print(d)

全局关键字起作用,但可能适得其反。。。你知道吗

Note that it is usually very bad practice to access global variables from inside functions, and even worse practice to modify them. This makes it difficult to arrange our program into logically encapsulated parts which do not affect each other in unexpected ways. If a function needs to access some external value, we should pass the value into the function as a parameter. If the function is a method of an object, it is sometimes appropriate to make the value an attribute of the same object

相关问题 更多 >

    热门问题