3

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.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • Does this answer your question? [Python function global variables?](https://stackoverflow.com/questions/10588317/python-function-global-variables) – mkrieger1 Sep 24 '22 at 09:51

3 Answers3

4

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
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
4

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:
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
2

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
Christoph
  • 78
  • 5
  • 1
    A better solution would perhaps be to make it object-oriented and define self.death as an attribute. To avoid 'global death', you could also add a 'return death' statement to your function. – Christoph Oct 16 '12 at 00:53
  • I upvoted your comment. Why not show the object oriented approach in your answer? – John La Rooy Oct 16 '12 at 01:42