Python 在何处定义使用函数的变量
无法打印“问题”函数中定义的“分数”变量。 令人不安的代码:Python 在何处定义使用函数的变量,python,variables,Python,Variables,无法打印“问题”函数中定义的“分数”变量。 令人不安的代码: 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?")
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
回溯(最近一次呼叫最后一次):
文件“quick.py”,第11行,在
打印(“您的分数为%r.%score)
NameError:未定义名称“分数”
如果您能帮助您找出变量的位置,我们将不胜感激。您必须缩进函数中运行的代码,还必须从函数中返回一些值
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+=问题(尝试,回答)
您必须缩进函数中运行的代码,还必须从函数中返回一些值
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+=问题(尝试、回答)
我会在函数中打印它,函数返回:
>>> print("How many ducks are there?")
How many ducks are there?
>>> question(input(), "14")
Your score is 0.
>>>
我会在函数中打印它,函数返回:
>>> print("How many ducks are there?")
How many ducks are there?
>>> question(input(), "14")
Your score is 0.
>>>