我正在尝试使用函数编写不同困难的历史测验,但在"全局名称"方面遇到了一些麻烦。我试图纠正这一点,但似乎没有任何效果。
代码片段代码为:
#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
我试图将他的 Answer1E 声明为函数内外的全局变量。
例如:
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关键字声明它。
x=5
def h():
global x
x=6
print(x)
h()
print(x)
此代码将打印
5
6
但是,全局变量通常是要避免的。