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
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.
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.
You can reset the value of the loop variable to i = 0 to restart the loop as soon as the user types in 'r' .
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.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With