Test1234
Test1234

Reputation: 113

Why doesn't this function update the variable properly?

Basically, once this code is ran, the program prints 20, 20; whereas, what I would like for it to do is to add a further 20 to the previous gold. So the program should print 20, 40.

gold = 0

def display():
    calculate(gold)
    calculate(gold)

def calculate(gold):
    gold += 10
    gold = gold + 10
    print(gold)

display()

Upvotes: 1

Views: 52

Answers (3)

DNA
DNA

Reputation: 42597

The problem is that when you call calculate(), you are passing in the current value of the variable gold, not the variable itself.

So when you add 10 to gold within calculate, the original gold variable is unaffected. The two variables have the same name, but point to different values. Below, I have named one of them gold2 to clarify this point.

If you return the new value from calculate, you can update the outer gold variable (i.e. rebind the name gold to a new int object):

gold = 0

def calculate(gold2):
    gold2 = gold2 + 10
    return gold2

gold = calculate(gold)  # 10
gold = calculate(gold)  # 20

Upvotes: 4

wim
wim

Reputation: 362607

It looks like you were aiming for this:

gold = 0

def display():
    calculate()
    calculate()

def calculate():
    global gold
    gold += 10
    gold = gold + 10
    print(gold)

display()

Since gold is a global variable here, you don't need to explicitly pass it in as a parameter to calculate.

Upvotes: 2

Denis
Denis

Reputation: 1229

gold = 0

def display():
    global gold
    gold = calculate(gold)
    calculate(gold)

def calculate(gold):
    gold += 10
    gold = gold + 10
    print(gold)
    return gold

display()

Upvotes: 1

Related Questions