【问题标题】:NameError: name '<name>' is not definedNameError:名称“<名称>”未定义
【发布时间】:2020-06-14 05:49:51
【问题描述】:

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

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

错误仍然存​​在。

我在这里做错了什么?

【问题讨论】:

  • 您认为您使用的是 Python 3,但事实并非如此。获取 Python 3。
  • 在 python 2 中,python 将尝试编译并执行为input 输入的内容。 Python 2 将raw_input 用于字符串。 Python 3 放弃了input 功能,并将raw_input 重命名为input。看起来你真的在运行 python 2。
  • 另一个错误正是它所说的。您必须将global GivenName 放在函数中GivenName 的任何使用之上。
  • 你不应该使用全局变量(这个“规则”有例外)。而是从函数中返回 GivenName。
  • 感谢您的建议。我曾尝试不将 GivenName 作为全局变量,但我又试了一次。同名错误。使用 input 与 raw_input 并没有什么不同。同名错误。我会看看我的 Python 版本是否是最新的。可能就是这样。

标签: python python-3.x nameerror


【解决方案1】:

您犯的错误是在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()

希望对你有帮助!

【讨论】:

  • 感谢您的建议,但是当我尝试这样做时,出现了相同的 NameError。
猜你喜欢
  • 2018-01-24
  • 1970-01-01
  • 2020-04-20
  • 2021-04-15
  • 2019-01-26
  • 2021-10-05
  • 2017-08-16
  • 2019-08-18
相关资源
最近更新 更多