Python3从另一个函数更改函数中的变量

2024-10-03 17:19:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从testadder访问main中的测试变量,这样在main中调用testadder之后,它将向testing添加1。在

出于某种原因,我可以用这种方式将1添加到列表中,但不能添加变量。非本地声明不起作用,因为函数没有嵌套。在

有办法解决这个问题吗?在

def testadder(test, testing):
    test.append(1)
    testing += 1

def main():
    test = []
    testing = 1
    testadder(test, testing)
    print(test, testing)

main()

Tags: 函数test声明列表maindef方式testing
1条回答
网友
1楼 · 发布于 2024-10-03 17:19:46

列表是可变的,但整数不是。返回修改后的变量并重新赋值。在

def testadder(test, testing):
    test.append(1)
    return testing + 1

def main():
    test = []
    testing = 1
    testing = testadder(test, testing)
    print(test, testing)

main()

相关问题 更多 >