2015-07-04 25 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)

之外