为什么你的函数不改变 X 和 Y 的最终值?
在Python中当调用带有参数的函数时,
参数值的副本存储在局部变量中。
确实当你写的时候
def incdec(x,y,d):
x += d
y -= d
唯一改变的是函数 indec 中的 x 和 y。
但在函数结束时,局部变量会丢失。
为了获得你想要的东西,你应该记住这个函数做了什么。
要记住函数之后的这些值,您应该像这样重新分配 x 和 y:
def incdec(x,y,d):
x += d
y -= d
return (x,y)
# and then
X = 5; Y = 7; d = 2
X,Y = incdec(X,Y,d)
这是有效的,因为 X,Y 是 int 类型。
您还可以做的是使用列表直接访问您想要更改的变量。
def incdec(list_1,d):
list_1[0] += d
list_1[1] -= d
#no return needed
# and then
X = 5; Y = 7; d = 2
new_list = [X, Y]
incdec(new_list,d) #the list has changed but not X and Y
不要误会我的意思,正如我之前所说,传递的参数仍然是副本,但是当您复制列表时,仅复制引用,但它们仍然查看同一个对象。这是一个演示:
number = 5
list_a = [number] #we copy the value of number
print (list_a[0]) # output is 5
list_b = list_a # we copy all references os list_a into list_b
print(list_b[0]) # output is 5
list_a[0]=99
print(list_b[0]) # output is 99
print(number) # output is 5
如你看到的list_a[0] and list_b[0]
是同一个对象,但数字不同
那是因为我们复制了值number
而不是参考。
我建议您使用第一种解决方案。
我希望这有帮助。