Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/294.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在何处定义使用函数的变量_Python_Variables - Fatal编程技术网

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.
>>>