Python: 改变函数内的全局变量和全局列表元素

Python: changing global variable and global list elements inside a function

问题

我的代码遇到了另一个问题。我正在制作一个程序,根据需要操纵全局变量的值。我正在研究如何在函数内部需要时使用 global 更改全局变量的值。任何帮助将非常感激。如果你愿意,你可以修改整个代码。再次感谢。

代码

verifier = 0
letters = ["A","B","C","D","E","F","G","H","I"]

if verifier == 0:
    letters = ["A","B","C","D","E","F","G","H","I"]
if verifier == 1:
    letters = newlist()

def newlist():
     numbers = ["0","1","2","3","4","5","6","7","8"]
     return animals

def main():
    global verifier
    # this should print ["A","B","C","D","E","F","G","H","I"]
    print(letters) 
    # global variable should be changed to 1
    verifier = 1 
    # this should print ["0","1","2","3","4","5","6","7","8"] now
    print(letters) 
main()

使用global变量:

verifier = 0

def newlist():
    if verifier == 0:
        return ["A","B","C","D","E","F","G","H","I"]
    elif verifier == 1:
        return ["0","1","2","3","4","5","6","7","8"]

print newlist()

def main():
    global verifier
    verifier = 1
main()

print newlist()

你的代码结构有误。你不会通过改变变量来实现任何目标。

是变量声明:

verifier = 0
letters = ["A","B","C","D","E","F","G","H","I"]

在调用 main 之前,将只检查一次 if 代码和第二个 if 代码。另外 - 阅读 elif.

if verifier == 0:
    letters = ["A","B","C","D","E","F","G","H","I"]
elif verifier == 1:
    letters = newlist()

"letters" 在 main 函数中总是 ["A","B","C","D","E","F","G","H","I"]。如果您想修复代码,请参阅我的示例。 if只执行了一次。如果不重新启动文件,您将无法重新扫描。

在大多数情况下 global 不必使用 - 您只需将变量传递给函数参数:

def newlist(verifier):
    if verifier == 0:
        return ["A","B","C","D","E","F","G","H","I"]
    elif verifier == 1:
        return ["0","1","2","3","4","5","6","7","8"]

def main():
    print newlist(0)
    print newlist(1)
main()

专门针对此任务-甚至不需要使用以下功能:

letters = {
    0: ["A","B","C","D","E","F","G","H","I"],
    1: ["0","1","2","3","4","5","6","7","8"]
}

print letters.get(0, None)