Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Variable "resetting"

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
like image 765
Zooty Avatar asked Nov 09 '13 23:11

Zooty


People also ask

How do you reset variables in Python?

to clear Variables in Python just use %reset-f. You can clear variables in python by using %reset-f function. If you want to delete any specific variable then use %reset-f.

How do you reset global variables in Python?

Use del and globals to erase all declared global variables If it isn't used by Python, access the object with the variable name name using globals() [name] . Use the syntax del globals()[name] to delete the object from memory. At the end of the for loop, the loop variable will remain in memory.

How do you reset a variable in a for loop Python?

You can reset the value of the loop variable to i = 0 to restart the loop as soon as the user types in 'r' .

How do you reassign a variable in Python?

Reassigning Values to a Variable (Say that three times fast.) In Listing 4.21, the variable coffee_cup has its value changed from coffee to tea. To reassign a value, you simply enter the assignment syntax with a new value at the end of it.


1 Answers

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'

like image 133
TerryA Avatar answered Oct 05 '22 01:10

TerryA