我正在尝试使用函数编写一个历史测验来解决不同的困难,但是在“全局名称”方面遇到了一些麻烦。我试图纠正这个,但似乎没有任何工作。
代码段是:
#Checking Answers
def checkEasyHistoryQuestions():
score = 0
if hisAnswer1E == 'B' or hisAnswer1E == 'b':
score = score + 1
print "Correct!"
else:
print "Incorrect!"
if hisAnswer2E == 'A' or hisAnswer2E == 'a':
score = score + 1
print "Correct!"
else:
print "Incorrect!"
if hisAnswer3E == 'B' or hisAnswer3E == 'b':
score = score + 1
print "Correct!"
else:
print "Incorrect!"
print score
print "\n"
#History - Easy - QUESTIONS + INPUT
def easyHistoryQuestions():
print "\n"
print "1. What date did World War II start?"
print "Is it:", "\n", "A: 20th October 1939", "\n", "B: 1st September 1939"
hisAnswer1E = raw_input("Enter your choice: ")
print "\n"
print "2. When did the Battle of Britain take place?"
print "Is it: ", "\n", "A: 10th July 1940 – 31st October 1940", "\n", "B: 3rd July 1940- 2nd August 1940"
hisAnswer2E = raw_input("Enter your choice: ")
print "\n"
print "3. Who succeeded Elizabeth I on the English throne?"
print "Is it: ", "\n", "A. Henry VIII", "\n", "B. James VI"
hisAnswer3E = raw_input("Enter your choice: ")
print "\n"
checkEasyHistoryQuestions()
我得到的错误是:
if hisAnswer1E == 'B' or hisAnswer1E == 'b':
NameError: global name 'hisAnswer1E' is not defined
我试图将hisAnswer1E声明为函数内的全局变量以及它之外的全局变量。
例如:
print "\n"
print "1. What date did World War II start?"
print "Is it:", "\n", "A: 20th October 1939", "\n", "B: 1st September 1939"
global hisAnswer1E
hisAnswer1E = raw_input("Enter your choice: ")
print "\n"
并且:
global hisAnswer1E
#Checking Answers
def checkEasyHistoryQuestions():
score = 0
if hisAnswer1E == 'B' or hisAnswer1E == 'b':
score = score + 1
print "Correct!"
else:
print "Incorrect!"
似乎没有什么工作,我只是继续得到同样的错误。有什么想法吗?
声明global hisAnswer1E
意味着“从全球范围使用hisAnswer1E
”。它实际上并没有在全球范围内创建hisAnswer1E
。
因此,要使用全局变量,首先应在全局范围内创建变量,然后在函数中声明global hisAnswer1E
然而!
一条建议:不要使用全局变量。只是不要。
函数接受参数并返回值。这是在它们之间共享数据的正确机制。
在你的情况下,最简单的解决方案(即你到目前为止所做的最少的改变)是从easyHistoryQuestions
返回答案并将它们传递给checkEasyHistoryQuestions
,例如:
def checkEasyHistoryQuestions(hisAnswer1E, hisAnswer2E, hisAnswer3E):
# <your code here>
def easyHistoryQuestions():
# <your code here>
return hisAnswer1E, hisAnswer2E, hisAnswer3E
hisAnswer1E, hisAnswer2E, hisAnswer3E = easyHistoryQuestions()
checkEasyHistoryQuestions(hisAnswer1E, hisAnswer2E, hisAnswer3E)
要在python中使用全局变量,我认为你应该在函数之外声明没有global关键字的变量,然后在函数内部使用global关键字声明它。
x=5
def h():
global x
x=6
print(x)
h()
print(x)
这段代码会打印出来
5
6
然而,全局变量通常是需要避免的。