【发布时间】: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