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

Смежные вопросы