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



问题

我的代码遇到了另一个问题。我正在制作一个程序,根据需要操纵全局变量的值。我正在研究如何在函数内部随时使用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()

使用全局变量:

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

main中的"字母"将始终为["A","B","C","D","E","F","G","H","I"]。如果您想修复代码,请参阅我的示例。CCD_ 5只执行了一次。如果不重新启动文件,您将无法重新扫描。

在大多数情况下,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)

相关内容

  • 没有找到相关文章

最新更新