pythonfunctionthonny

I am trying to call a function in thonny and then printing the variable changed by the function. Why isn't it working?


i define the function "player" and inside, assign the variable "health".

def player():
   health = 100
player()
print(health)  

but when i try to run the program, i recieve this error.

i tried to make the variable health global like this

global health
def player():
    health = 100   
player()
print(health)

and it still doesn't work.


Solution

  • You need to call global inside the function in order to access the global variable.

    def player():
      global health
      health = 100   
    player()
    print(health)
    

    Output

    100