全部。
我正在尝试创建一个脚本,以文字形式播放名称游戏。上了我的第一堂课。
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
稍后调用它(这是第一个类),我一直在得到它... (假设我输入了“ David”。)
./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()
错误仍然存在。
我在做什么错了?
答案 0 :(得分:0)
您犯的错误是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()
希望这对您有帮助!