-1

I am writing a program where I have a value that is 0 at the start, but is used throughout the program to keep track of "changes" and I want then to print the sum of the changes, the rest of the code works fine but for some reason that variable that goes into multiple functions doesn't keep the changes and return them when I print but just returns 0 every time

var = 0

def func1(var1):
    for i in range(x):
        for j in range(y):
            if condition:
                pass
            elif condition:
                func2(var1)
    return var1

def func2(var2):
    if condition:
        pass
    elif condition:
        var2 += 1
    return var2

func1(var)
print(var)
  • 2
    You should read https://nedbatchelder.com/text/names.html – chepner Apr 21 '23 at 13:33
  • You return `var2` in `func2` but you don't catch the value in `func1`. Maybe you want `var1 = func2(var1)`? – Matthias Apr 21 '23 at 13:44
  • @chepner: thanks for this link, it's a very interesting read, very well explained, even for someone who already knows the basics! – Swifty Apr 21 '23 at 15:46
  • @Matthias i want to catch the value in func1 and ultimately return the cumulative value from inside the functions to the var variable outside – Tar-Eruntalion Apr 26 '23 at 09:57

2 Answers2

6

int values are immutable, and Python does not use call-by-reference semantics. var2 += 1 sets the local variable var2 to refer to an int object equal to var2 + 1. It neither mutates the value originally assigned to var2, not updates the variable used to pass a value to func2 in the first place.

chepner
  • 497,756
  • 71
  • 530
  • 681
1

You are passing in var to func1() as var1, manipulating the value of var1 and returning the value of var1. However, you do not assign a variable to the return of func1(). Since you are not manipulating var itself, just its value inside of func1(), when you print var at the end, you still get its original value. Try this:

output = func1(var)
print(output) # will print an updated value - I can't say what value as I don't know x and y
print(var) # will still print 0 as you are not actually modifying var itself.

If inside of func1() you did not pass in arguments and instead were operating on var instead of the argument var1, var would get changed. But in python you are simply modifying the value you pass in, not the actual value of the variable.

I recommend researching pass-by-value, pass-by-reference, and how python handles these things.