Skip to content Skip to sidebar Skip to footer

Python Variable Won't Change?

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' deat

Solution 1:

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

Solution 2:

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:

Solution 3:

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

Post a Comment for "Python Variable Won't Change?"