Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python and assigning variable values in if statements

Tags:

python

I'm somewhat of a beginner in python and I swear I got a very similar program to what I'm doing right now to work. But, for some reason, I can't make it work. I was able to pinpoint my problem and created a fake program to play around with it. Here is what the program:

global heading
global heading2
global a

heading=2
a=2
heading2=4

def function ():
    if a==2:
        heading=heading2
        print 'yes'
        print heading

function()       
print heading

This is what appears:

yes
4
2

Why doesn't the heading variable heading keep the value 4? I tried putting return heading all over. Didn't work. I tried putting the variables in the parentheses of the function. Didn't work either... Do you know what I'm doing wrong?

like image 279
user1020797 Avatar asked May 24 '26 17:05

user1020797


1 Answers

global statement is meaningless outside of a function. If you want to modify the global variable, instead of introducing a local one, you need to put global inside the function

def foo():
    global x
    x = x2

Also, don't use globals.

like image 133
Cat Plus Plus Avatar answered May 27 '26 05:05

Cat Plus Plus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!