While attempting to create a simple message encrypting code in Python (3.6.3), I encountered a problem, which can be observed in the following code (separate test file):
import sys
def test(integ):
integ += 1
return
def main():
x = 0
y = 2
test(x)
test(y)
print("{}\n{}".format(x, y))
test(x)
print(x)
if __name__ == "__main__":
main()
Now, my goal is for it to give me 1, 3 and 2 in that order as an output, but it gives me 0, 2 and 0, meaning that the variables x and y aren't modified at all. So, after looking up possible solutions to my issue, I found the statement nonlocal and attempted to alter my code in the following way:
def test(integ):
nonlocal integ
integ += 1
return
However, this time I obtain the following error: SyntaxError: name 'integ' is parameter and nonlocal, which leads me to the conclusion that I can not alter the variables x and y using a parameter within the function test().
Would there be some sort of workaround for this issue while avoiding the use of global variables?
test(smth), why not return the new value and simply reassignsmth = test(smth)?nonlocalisn't what you want here. Python integers are immutable, you can't change them. Yourtestfunction needs to create a new integer object with the value you want and then return that new object to the calling code, by using thereturnstatement.