簡體   English   中英

全局變量名稱和不同函數的問題(使用Python)

[英]Trouble with global variable names and different functions (using Python)

我正在嘗試使用功能編寫一個具有不同困難的歷史測驗,但是在“全局名稱”方面遇到了一些麻煩。 我已嘗試糾正此問題,但似乎無濟於事。

片段代碼為:

#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

但是,通常應避免使用全局變量。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM