首页 > 解决方案 > 名称错误:名称'' 没有定义

问题描述

我正在尝试创建一个以文本形式播放名称游戏的脚本。在使用我的第一堂课时被卡住了。

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

错误仍然存​​在。

我在这里做错了什么?

标签: pythonpython-3.xnameerror

解决方案


您所犯的错误是在全局声明中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()

希望这对你有帮助!


推荐阅读