Sanatan Chaudhary Sanatan Chaudhary - 4 months ago 10
Python Question

Why is function not changing global variable even after specifying global

I have recently started programming. Everything is working fine but this piece of code intriguing me from a long time.

Here is my code.

addon = 20
startup = 50 + addon

def click():
global addon, startup
addon *= 2
print addon, startup

click()
click()
click()
click()
click()
click()
click()
click()
click()
click()


This is my output:-

40 70
80 70
160 70
320 70
640 70
1280 70
2560 70
5120 70
10240 70
20480 70


This is what I expected:-

40 90
80 170
160 330
320 650
640 1290
1280 2570
2560 5130
5120 10250
10240 20490
20480 40970


I am just not getting. if every call of
click
is updating global variable
addon
than it should also update
startup
variable. But don't know why it is not working.

Answer

startup does not store an expression, it stores the result of an expression, once.

In other words, the variable startup references the result of 50 + addon, which at the time is the integer 70.

That addon later changes does not make a difference here, because startup does not reference addon.

You'd have to make startup a function instead, and call that function each time if you wanted to re-calculate the expression:

startup = lambda: 50 + addon

I used a lambda expression to create the function here; a lambda creates a function from a single expression.

You then call startup each time you need to see the latest result:

def click():
    global addon
    addon *= 2
    print addon, startup()