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()
错误仍然存在。
我在这里做错了什么?
解决方案
您所犯的错误是在全局声明中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()
希望这对你有帮助!
推荐阅读
- python - 如何获得 SGDClassifier (LinearSVM) 的概率
- php - 使用 Laravel 和 Dropzone 图片上传数据中插入的 id
- c# - 使用字符串 C# 引用 XAML
- java - XMLDecoder >> java.lang.IllegalArgumentException:不支持的元素
- java - 如何使用 Jackson 序列化为 java.util.List 和 java.util.Map
- node.js - 无法使用 AWS SES 发送电子邮件:我没有正确配置它吗?
- prolog - 在prolog中调试一段代码
- hadoop - NameNode 的用户名必须与 DataNode 的用户名相同吗?
- python - 正则表达式查找某些模式之间的所有字符串
- python - 使用 aiohttp 的 HEAD 请求很慢