Python 3 changing variable in function from another function

醉酒当歌 提交于 2021-02-08 06:58:48

问题


I would like to access the testing variable in main from testadder, such that it will add 1 to testing after testadder has been called in main.

For some reason I can add 1 to a list this way, but not variables. The nonlocal declaration doesn't work since the functions aren't nestled.

Is there a way to work around this?

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

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

main()

回答1:


Lists are mutable, but integers are not. Return the modified variable and reassign it.

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

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

main()


来源:https://stackoverflow.com/questions/39532350/python-3-changing-variable-in-function-from-another-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!