全局变量名称和不同函数的麻烦(使用Python)

时间:2017-12-30 19:09:02

标签: python function global-variables

我正在尝试使用函数对不同困难的历史测验进行编程,但在全局名称和#34;方面遇到了一些麻烦。我试图纠正这个,但似乎没有任何工作。

代码段为:

#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!"

似乎没有什么工作,我只是继续得到同样的错误。有什么想法吗?

2 个答案:

答案 0 :(得分:2)

声明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)

答案 1 :(得分:0)

要在python中使用全局变量,我认为你应该声明变量而不是该函数的全局关键字 ,然后将其声明为 with < / strong>函数的全局关键字

x=5
def h():
   global x
   x=6

print(x)
h()
print(x)

此代码将打印

5
6

然而,全局变量通常是需要避免的。