2015-07-04 28 views
1

嘗試打印在「問題」功能中定義的「分數」變量時遇到困難。 有問題的困擾代碼:哪裏可以定義變量使用功能

def question(attempt, answer): 
    score = 0 
     #if attempt is true, add 1 to score 
     #if attempt is false, do nothing to score 
    if attempt == answer: 
     score += 1 

print("How many ducks are there?") 
question(input(), "14") 

print("Your score is %r." % score) 

雖然,當我嘗試運行它,我得到的是這樣的:

Traceback (most recent call last): 
    File "quiz.py", line 11, in <module> 
    print("Your score is %r." % score) 
NameError: name 'score' is not defined 

,首先要弄清楚任何幫助在哪裏放置變量將不勝感激。

回答

0
def question(attempt, answer): 
    score = 0 
    #if attempt is true, add 1 to score 
    #if attempt is false, do nothing to score 
    if attempt == answer: 
     score += 1 
     return score 
    print("Your score is %r." % score) 

我將打印的功能,這裏面返回:

>>> print("How many ducks are there?") 
How many ducks are there? 
>>> question(input(), "14") 

Your score is 0. 
>>> 
0

你要縮進這是在你的函數運行的代碼,你也必須從你的函數

def question(attempt, answer): 
    score = 0 
    #if attempt is true, add 1 to score 
    #if attempt is false, do nothing to score 
    if attempt == answer: 
     score = 1 
    return score 

返回一些價值你應該覺得總體得分函數即
score += question(attempt, answer)

之外