3

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?

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

3

The line:

    heading=heading2

Creates a new local variable called heading, which is different to the other varaible called heading that you passed into the function.

You can make the function assign to external variables by adding:

global heading

before you assign to heading:

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

Comments

0

Inside function, you are creating a local variable called heading. This isn't the same heading declared outside of the function.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.