You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何在函数内部修改整数变量的值?

函数内修改整数变量的问题解析

你代码里的现象很典型:列表numbers的元素在函数内修改后,外部的列表确实变了,但整数i在函数里赋值为50后,外部的i还是0。这是因为Python对不可变类型和可变类型的处理规则不一样。

核心原因

  • 整数(int)属于不可变类型:当你把i传给函数时,函数拿到的是i的引用,但一旦在函数里执行i = 50,其实是在函数的局部作用域里创建了一个新的整数对象,和外部的i没有任何关系了。外部的i依然指向原来的0。
  • 列表(list)属于可变类型:函数拿到列表的引用后,修改列表的元素(比如numbers[5] = 48)是直接操作原来的列表对象,所以外部的列表会同步变化。

解决方法

这里给你几种常用的实现方式:

1. 让函数返回修改后的值(推荐)

这是最符合Python风格的做法,通过返回值把修改后的i传递出去,外部重新赋值:

i = 0
numbers = [2, 7, 8, 14, 15, 38, 27, 9, 77, 10]

print("the value of [5] before the function call is " + str(numbers[5]))

def printArray(numbers, i):
    numbers[5] = 48
    numbers[0] = 50
    
    for x in numbers:
        print(x)
    
    i = 50
    return i  # 返回修改后的i

i = printArray(numbers, i)  # 用返回值更新外部的i

print("The new value of i is " + str(i))

2. 用可变容器包装整数

把整数放到列表这类可变容器里,函数内修改容器的元素就能影响外部:

i = [0]  # 用列表包装整数
numbers = [2, 7, 8, 14, 15, 38, 27, 9, 77, 10]

print("the value of [5] before the function call is " + str(numbers[5]))

def printArray(numbers, i):
    numbers[5] = 48
    numbers[0] = 50
    
    for x in numbers:
        print(x)
    
    i[0] = 50  # 修改列表内的元素

printArray(numbers, i)

print("The new value of i is " + str(i[0]))

3. 使用global关键字(不推荐)

如果你的场景非常简单,可以用global声明使用全局变量,但这种方式会破坏函数的封装性,不建议在复杂代码里用:

i = 0
numbers = [2, 7, 8, 14, 15, 38, 27, 9, 77, 10]

print("the value of [5] before the function call is " + str(numbers[5]))

def printArray(numbers):
    global i  # 声明使用全局变量i
    numbers[5] = 48
    numbers[0] = 50
    
    for x in numbers:
        print(x)
    
    i = 50

printArray(numbers)

print("The new value of i is " + str(i))

内容的提问来源于stack exchange,提问作者ClaytonTK

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 15:57:51