10

I am setting a string to something in a function, then trying to print it in another to find that the string never changed. Am I doing something wrong?

Defining the variable at the top of my script

CHARNAME = "Unnamed"

Function setting the variable

def setName(name):
        CHARNAME = name
        print CHARNAME

Use of function

print CHARNAME
setName("1234")
print CHARNAME

Output

Unnamed
1234
Unnamed

2 Answers 2

13

When you do CHARNAME = name in the setName function, you are defining it only for that scope. i.e, it can not be accessed outside of the function. Hence, the global vriable CHARNAME (the one with the value "Unnamed"), is untouched, and you proceed to print its contents after calling the function

You aren't actually overwriting the global variable CHARNAME. If you want to, you must globalise the variable CHARNAME in the function setName by putting global CHARNAME before you define it:

def setName(name):
    global CHARNAME
    CHARNAME = name
    print CHARNAME

Alternatively, you can return the value of CHARNAME from the function:

def setName(name):
    return name

CHARNAME = setName('1234')

Of course this is rather useless and you might as well do CHARNAME = '1234'

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

Comments

3

You need

def setName(name):
    global CHARNAME
    CHARNAME = name
    print CHARNAME

http://effbot.org/pyfaq/how-do-you-set-a-global-variable-in-a-function.htm

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.