【发布时间】:2020-08-01 06:20:34
【问题描述】:
points = 0
def testfunction():
points = 2
return points
testfunction()
print (points)
为什么点数现在不等于 2?
【问题讨论】:
标签: python string function return
points = 0
def testfunction():
points = 2
return points
testfunction()
print (points)
为什么点数现在不等于 2?
【问题讨论】:
标签: python string function return
在这里,testFunction 在其本地范围内创建另一个 points 变量。这就是为什么全局points 变量的值没有改变的原因。您需要告诉您的函数您要使用全局 points 变量,
points = 0
def test_function():
global points
points = 2
return points
test_function()
print(points)
或者你可以将返回值赋给points变量,比如:
def test_function():
points = 2
return points
points = test_function()
print(points)
而且大多数 Pythonistas 更喜欢使用蛇形大小写来命名函数和变量。
【讨论】:
你必须将变量分配给函数,写:
points = testfunction()
打印线上方。
【讨论】:
函数中的return 必须分配给变量。您可以像这样编辑全局变量:
points = 0
def test_function():
global points
points = 2
pass
test_function()
print(points)
或者不调用点作为全局变量:
points = 0
def testfunction():
points = 2
return points
points = testfunction()
print (points)
显然这确实使points 的初始声明相当过时......
【讨论】:
在函数内部创建的变量属于该函数的局部作用域,只能在该函数内部使用。
因此,即使它们具有相同的名称,您也无法从函数中修改外部变量。
你可以使用:
points = testfunction()
【讨论】:
您有两个不同的变量,名称为 points。一个在外部作用域中声明,另一个是本地函数testfunction()。
外部范围points 变量设置为 0 并且永不更新。本地范围points 设置为2,从函数返回,然后蒸发到遗忘。函数返回的值本质上是向左“吐出”,可用于赋值到另一个变量。
因此:
points = 0
def testfunction():
points = 2
return points
points = testfunction()
print (points)
会完成你想要的。
这样写可能更清楚:
calc_result = 0
def testfunction():
points = 2
return points
calc_result = testfunction()
print (calc_result )
另外,因为 Python 不需要任何类型的变量声明,所以不需要第一行。
【讨论】: