SyntaxError:在全局声明之前将名称“retry”分配给

SyntaxError: name 'retry' is assigned to before global declaration

提问人:omardabookwyrm 提问时间:5/25/2023 更新时间:5/25/2023 访问量:138

问:

它一直这样说:SyntaxError:在全局声明之前将名称“retry”分配给

关于如何解决这个问题的任何提示?

代码如下:

import time

global retry 
retry = 1

def message(pausetime, text):
        print(text)
        time.sleep(pausetime)

def investigate(var):
        print("You find" +" "+ var)

def death():
    lose = input(" You lost, would you like to try again? n\ press y to try again or n to stop playing ")
    if lose == "y":
        global retry 
        retry = 1
    elif lose == "n":
        print("Thanks for playing! Hope you enjoyed")
        global retry 
        retry = 0

def win():
    print("Congratulations! You defeated the Orc King and stopped the Orc raids, you are now the hero of Everwood!")
    global retry 
    retry = 0

while retry >= 1:
#some code

它说问题出在第 20 行,它只是说:

global retry
python-3.x 语法错误 全局变量

评论

1赞 Robert Bradley 5/26/2023
这回答了你的问题吗?语法警告:在全局声明全局项之前将名称“item”分配给

答:

0赞 JRiggles 5/25/2023 #1

在全局范围内声明之前不需要(已经在全局范围内)。只需将其删除即可。global retryretryretry

import time

# global retry <= not necessary
retry = 1

...

此外,只需要在 的定义中使用一次,如下所示global retrydeath()

def death():
    global retry
    lose = input(" You lost, would you like to try again? n\ press y to try again or n to stop playing ")
    if lose == "y":
        retry = 1
    elif lose == "n":
        print("Thanks for playing! Hope you enjoyed")
        retry = 0

更多信息:该关键字在函数内部使用,以允许它们修改全局范围内存在的变量(例如,)。当然,不需要修改此值的函数不需要设置globalretryglobal retry