2016-12-16 52 views
-2
#Quiz answer variables go here! 
ca1 = cringe_crew[0] 
ca2 = cucks[0] 
ca3 = 5 
ca4 = cringe_crew[1] 
ca5 = 'No' 

#Questions 
q1 = "Question 1 - Who do we refer to when shouting CODE YELLOW? " 
q2 = "Question 2 - Who would you think of if I called him 'Linux Boy': " 
q3 = "Question 3 - How many people were there in the original Cringe-Crew back in the days of 2015? " 
q4 = "Question 4 - Biggest pseudo Overwatch fan? (top tip: even bought a fucking bag): " 
q5 = "Question 5 - Do we miss Luke Slater? " 

#a is the raw_input answer 
#b is the correct answer needed 
#a1-a5 will be separately stored raw_input ANSWERS 
#ca1-ca5 are already called as variables and these are the correct answers. 

#Score 

score = 0 

def compare(a, ca): 
    if a == ca: 
     score = score + 1 
     print "That's correct! The answer was %s" % ca 
     print "Your score is", score 

    else: 
     print "%s is not the correct answer - you did not get a point!" % a 
    return; 


#test 
a1 = raw_input(q1) 
compare(a1, ca1) 
a2 = raw_input(q2) 
compare(a2, ca2) 
a3 = raw_input(q3) 
compare(a3, ca3) 
a4 = raw_input(q4) 
compare(a4, ca4) 
a5 = raw_input(q5) 
compare(a5, ca5) 

嘿傢伙,我是全新的python和編碼整體,但想開始與一個小測驗與分數,雖然我覺得我去完全錯誤的結構明智,如果我刪除了'分數'的代碼運行完全正常。如果我有它,出現這種情況:Python初學者 - 我做對了嗎?測驗與分數

Traceback (most recent call last): 
    File "ex2.py", line 57, in <module> 
    compare(a1, ca1) 
    File "ex2.py", line 46, in compare 
    score = score + 1 
UnboundLocalError: local variable 'score' referenced before assignment 

你能給我特別是對如何構建在這樣的情況下,代碼任何提示?非常感謝!

+0

重複:http://stackoverflow.com/questions/423379/using-global-variables-in-a-function-other-than -THE-一個是創建的,他們 – qxz

回答

0

在您的compare()函數中,在嘗試訪問它的值之前,您尚未定義您的score變量。

您應該將它傳遞給比較函數(將其作爲參數添加到函數中),然後將結果返回(首選),或者將其聲明爲函數內的全局變量(更簡單,但不是技術上的最好的方法)。

傳遞參數&返回值的解決方案

def compare(a, ca, scr): 
    if a == ca: 
     scr = scr + 1 
     print "That's correct! The answer was %s" % ca 
     print "Your score is", scr 

    else: 
     print "%s is not the correct answer - you did not get a point!" % a 
    return scr ; 

# skipping some code here 

score = compare(a1, ca1, score) 

全局變量的解決方案

def compare(a, ca): 
    global score 
    if a == ca: 
     score = score + 1 
     print "That's correct! The answer was %s" % ca 
     print "Your score is", score 

    else: 
     print "%s is not the correct answer - you did not get a point!" % a 
    return; 

否則,在全局範圍內score是一個完全不同的變量爲t即使他們具有相同的名稱,他也可以在compare範圍內使用score

0

在比較功能添加全局語句得分:

def compare(a, ca): 
    global score 
    if ca == ca: 
     # the rest of your code