您可以在Python中的子例程末尾更改参数的整数值吗?

发布于 2025-02-06 13:01:28 字数 274 浏览 0 评论 0原文

对于上下文,我在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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

八巷 2025-02-13 13:01:28

您不能因为number += 1在函数内部创建一个新变量。在全局名称空间中,号码仍将为1,而该函数具有本地变量number将设置为2

您可以将其整体化:

Number = int(1)

def Numberadd(Number):
    global Number
    array.append(Number)
    Number += 1

或将其纳入可以修改的列表:

Number = [int(1)]

def Numberadd(Number):
    array.append(Number)
    Number[0] += 1

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 variable Number set to 2.

You can either make it global:

Number = int(1)

def Numberadd(Number):
    global Number
    array.append(Number)
    Number += 1

Or make it into a list which can then be modified:

Number = [int(1)]

def Numberadd(Number):
    array.append(Number)
    Number[0] += 1
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文