名称错误:未定义名称“<name>”

2024-10-04 01:24:36 发布

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

全部

我正在尝试创建一个脚本,在文本中播放名称游戏。我的第一节课被卡住了

def AskName():
    print("\n\nLet's play the Name Game!\n  Based on the song written by Shirly Ellis and Lincoln Case.\n")
    GivenName = input("What is your first name? --> ")
    print("\n")
    global GivenName

稍后再打电话(这是第一堂课),我一直收到这个。。。 (假设我输入了“大卫”。)

./namegame.py:27: SyntaxWarning: name 'GivenName' is assigned to
before global declaration   global GivenName


Let's play the Name Game!   Based on the song written by Shirly Ellis
and Lincoln Case.

What is your first name? --> David
Traceback (most recent call last): 
File "./namegame.py", line 78, in <module>
    AskName()   File "./namegame.py", line 25, in AskName
    GivenName = input("What is your first name? --> ")
File "<string>", line 1, in <module>
NameError: name 'David' is not defined

我将GivenName视为非全球性,并根据类似问题的建议添加了以下内容:

if __name__== "__main__":
  AskName()

错误仍然存在

我做错了什么


Tags: thenameinpyyourislineglobal
1条回答
网友
1楼 · 发布于 2024-10-04 01:24:36

您所犯的错误是在GivenName的全局声明中,如果您使用任何变量作为全局变量,那么global GivenName行在任何函数中都应该始终是第一行,尽管它不是强制性的。您的代码应该如下所示

#if the variable is global it should be defined in global scope first and then you can use it
GivenName=""
def AskName():

    global GivenName
    print("\n\nLet's play the Name Game!\n  Based on the song written by Shirly Ellis and Lincoln Case.\n")
    GivenName = input("What is your first name?  > ")
    print("\n")

if __name__== "__main__":
  AskName()

希望这对你有帮助

相关问题 更多 >