您可以在Python中的子例程末尾更改参数的整数值吗?
对于上下文,我在Python中编写的代码的一部分是,当运行子例程时,它将通过使用附加的整数参数等于1。子例程应增加一个参数,以便下次运行子例程时,该参数将在数组中添加2个。取而代之的是,每次运行代码时,都会将整数1添加到数组中。
示例代码:
Number = int(1)
def Numberadd(Number):
array.append(Number)
Number += 1
如果有人知道这是为什么,或者如果直接不可能,请告诉我
for context a part of the code I am writing in python is that when a subroutine is run, it will add an integer, starting at 1, to an array by using append with an integer parameter that is equal to 1. at the end of the subroutine the parameter should be increased by one, so that next time the subroutine is run it will add 2 to the array. instead all that happens is it keeps adding the integer 1 to the array every time the code is run.
example code:
Number = int(1)
def Numberadd(Number):
array.append(Number)
Number += 1
if anyone knows why this is, or if its just straight up impossible, please let me know
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您不能因为
number += 1
在函数内部创建一个新变量。在全局名称空间中,号码
仍将为1,而该函数具有本地变量number
将设置为2
。您可以将其整体化:
或将其纳入可以修改的列表:
You can't because
Number += 1
creates a new variable inside the function. In the global namespace,Number
will still be 1, while the function has a local variableNumber
set to2
.You can either make it global:
Or make it into a list which can then be modified: