Why won't a global variable change when assigning to it in a function? - python

I'm making a game in python, and I have some code set up as such:
istouching = False
death = True
def checkdead():
if istouching:
print "Is touching"
death = True
while death is False:
print death
# game logic
I know the game logic is working, because "Is touching" prints, but then when I print out the value of death, it remains false.

use global to change global variables inside a function, otherwise death=True inside checkdead() will actually define a new local variable.
def checkdead():
global death
if istouching == True: #use == here for comparison
print "Is touching"
death = True

Make checkdead return a value:
def checkdead():
if istouching:
print "Is touching"
return True
death = checkdead()
You could also use global, as #AshwiniChaudhar shows, but I think it is preferable to write functions that return values instead of functions that modify globals, since such functions can be unit-tested more easily, and it makes explicit what external variables are changed.
PS. if istouching = True should have resulted in a SyntaxError since you can not make a variable assignment inside a conditional expression.
Instead, use
if istouching:

That's scope-related.
death = False
def f():
death = True # Here python doesn't now death, so it creates a new, different variable
f()
print(death) # False
death = False
def f():
global death
death = True
f()
print(death) # True

Related

Python - Change a function parameter even if it's global

I've made a function that I want to use to change a variable, this variable also happens to be global.
def CheckMarkFunc(var):
if var == True:
var= False
elif var == False:
var= True
If var is a global, it wont change. Is there a way to change the var without having to hardcode the global parameter (sound_mute, in this case) into the function itself?
The code below works, but I'd rather not have multiple if statements for each global variable that I want to change, if at all possible:
def CheckMarkFunc(var,button_id,uncheck_texture,checked_texture):
global sound_mute
if var == True:
TextureSwap(uncheck_texture,button_id)
sound_mute = False
if var == False:
sound_mute = True
TextureSwap(checked_texture,button_id)
In both of these cases, the var parameter is the sound_mute boolean.
One option is as follows:
def CheckMarkFunc(var, button_id, uncheck_texture, checked_texture):
if var:
TextureSwap(uncheck_texture, button_id)
else:
TextureSwap(checked_texture, button_id)
return not var
sound_mute = CheckMarkFunc(sound_mute, button_id, uncheck_texture, checked_texture)

How do I set a global variable via function call?

I am trying to change the value of global variable edl_loading to True in function edl_flashing ,somehow it doesn't work?can anyone help understand why does print edl_loading prints False after call to edl_flashing in which I change the value to True
def edl_flashing():
edl_loading = True
print edl_loading
def main ():
global edl_loading
edl_loading = False
print edl_loading
edl_flashing()
print edl_loading #Why this prints as False
if __name__ == '__main__':
main()
OUTPUT:-
False
True
False
You need to use the global in both of your functions - main and edl_flashing
def edl_flashing():
global edl_loading
edl_loading = True
print edl_loading
Without the global declaration in the function, the variable name is local to the function.
The above change prints out
False
True
True

Python3 defining room conditions

def isdark():
dark = True
dark = isdark()
if dark:
print('bt')
else:
print('dasd')
Im trying to make it so that it prints bt but instead is prints dasd, why isn't the dark = is dark() condition working?
def isdark():
dark = True
Here, you are not assigning to the global variable, but creating a local variable and assigning True to it. Instead, you can return the value from the function like this
def isdark():
return True
Since, you are assigning the returned value to the dark variable with this line
dark = isdark()
whatever you return from isdark will be assigned to dark.
Apart from that, if you are using that just to check that if condition, you can rewrite the code like this
if isdark():
print('bt')
else:
print('dasd')
isdark() is a function with no return statement, so it returns None by default. So dark never evaluates to true.
You're confusing yourself by using the same variable in two different ways. Here's how I would do it:
dark = True
def isdark():
return dark
if isdark():
print('bt')
else:
print('dasd')
or more simply:
isdark = True
if isdark:
print('bt')
else:
print('dasd')
or even more simply:
isdark = True
print('bt' if isdark else 'dasd')
You need to return dark, like this:
def isdark():
dark = True
return dark
dark = isdark()
if dark:
print('bt')
else:
print('dasd')

how does the compile() work in python?

I have two code which really confused me.
def get_context():
__gc = globals()
__lc = locals()
def precompiler(code):
exec code in __lc
def compiler(script, scope):
return compile(script, scope, 'eval')
def executor(expr):
return eval(expr, __gc, __lc)
return precompiler, compiler, executor
maker1, compiler1, executor1 = get_context()
maker2, compiler2, executor2 = get_context()
maker1("abc = 123")
maker2("abc = 345")
expr1 = compiler1("abc == 123", "test.py")
print "executor1(abc == 123):", executor1(expr1)
print "executor2(abc == 123):", executor2(expr1)
the result is:
executor1(abc == 123): True
executor2(abc == 123): False
Why the compile execute in the closure only once and the byte-code could run in both?
And there is another code here:
def get_context():
__gc = globals()
__lc = locals()
test_var = 123
def compiler(script, scope):
return compile(script, scope, 'eval')
def executor(expr):
return eval(expr, __gc, __lc)
return compiler, executor
compiler1, executor1 = get_context()
compiler2, executor2 = get_context()
expr1 = compiler1("test_var == 123", "test.py")
print "executor1(test_var == 123):", executor1(expr1)
print "executor2(test_var == 123):", executor2(expr1)
the result is:
NameError: name 'test_var' is not defined
And how did this happen?
Why does the compile need to check the environment(variable or some others) of the closure while it is not dependent on the closure? This is what I confused!
In your first example, you are executing 'abc=123' in your first context, and 'abc=345' in your second context. So 'test_var==123' is true in your first context and false in your second context.
In your second example, you have caught an interesting situation where the interpreter has removed test_var from the context because test_var isn't referenced.
For your first question, compile just takes the python code and produces the bytecode. It it is not dependent in any way on the closure where you compiled it. Its not different then if you had produced say, a string. That string isn't permantely tied to the function where it was created and neither is the code object.
For your second question, locals() builds a dictionary of the local variables when it is called. Since you setup test_var after calling locals it doesn't have it. If you want test_var inside locals, you need to call it afterwards.

Trouble with variable. [Python]

I have this variable on the beginning of the code:
enterActive = False
and then, in the end of it, I have this part:
def onKeyboardEvent(event):
if event.KeyID == 113: # F2
doLogin()
enterActive = True
if event.KeyID == 13: # ENTER
if enterActive == True:
m_lclick()
return True
hookManager.KeyDown = onKeyboardEvent
hookManager.HookKeyboard()
pythoncom.PumpMessages()
and I get this error when I press enter first, and when I press F2 first:
UnboundLocalError: local variable 'enterActive' referenced before assignment
I know why this happens, but I don't know how can I solve it...
anyone?
See Global variables in Python. Inside onKeyboardEvent, enterActive currently refers to a local variable, not the (global) variable you have defined outside the function. You need to put
global enterActive
at the beginning of the function to make enterActive refer to the global variable.
Approach 1: Use a local variable.
def onKeyboardEvent(event):
enterActive = false
...
Approach 2: Explicitly declare that you are using the global variable enterActive.
def onKeyboardEvent(event):
global enterActive
...
Because you have the line enterActive = True within the functiononKeyboardEvent, any reference to enterActive within the function uses the local variable by default, not the global one. In your case, the local variable is not defined at the time of its use, hence the error.
enterActive = False
def onKeyboardEvent(event):
global enterActive
...
Maybe you are trying to declare enterActive in another function and you aren't using the global statement to make it global. Anywhere in a function where you declare the variable, add:
global enterActive
That will declare it as global inside the functions.
Maybe this is the answer:
Using global variables in a function other than the one that created them
You are writing to a global variable and have to state that you know
what you're doing by adding a "global enterActive" in the beginning of
your function:
def onKeyboardEvent(event):
global enterActive
if event.KeyID == 113: # F2
doLogin()
enterActive = True
if event.KeyID == 13: # ENTER
if enterActive == True:
m_lclick()
return True

Categories