Python随机项目

2024-04-19 13:16:36 发布

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

这是一个随机代码,类似于我自己的项目代码。 当我运行它时,它显示UnboundLocalError:在赋值之前引用的局部变量“score”。谁能修好它

score = 0

def Random_Thing():
    Random_Text = input("Random Text")
    if Random_Text == "Hello":
        score = score + 1
        print(score)

def Random_Thing_2():
    Random_Text_2 = input("Random Text 2")
    if Random_Text_2 == "Hello2":
        score = score + 1
        print(score)

Random_Thing()
Random_Thing_2()
print(score)

1条回答
网友
1楼 · 发布于 2024-04-19 13:16:36

在顶部定义score = 0时,它位于文件的全局范围内。默认情况下,函数只能读取全局变量。你不能改变它们。因此print(score)将在函数内部工作。但是score=score+1不会

如果要从函数内部更改全局变量,请在函数开头执行global var1, var2...。对于您的代码,您需要执行以下操作

def Random_Thing():
    global score
    #your code

def Random_Thing_2():
    global score
    #your code

相关问题 更多 >