无法尝试打印“问题”功能中定义的“得分”变量。 令人不安的代码:
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 :(得分: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)
答案 1 :(得分: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.
>>>