I try to update the health value but it returns to 100. Can anyone explain?
def CheckHealth(health):
health-=1
health = 100
while True:
print(health)
CheckHealth(health)
if health==0:
break
I try to update the health value but it returns to 100. Can anyone explain?
def CheckHealth(health):
health-=1
health = 100
while True:
print(health)
CheckHealth(health)
if health==0:
break
Numerical values cannot actually be changed in python. They are inmutables. The equal sign does not change values, but assign objects to variable names.
When you assign to health in function, you assign a different int object to the variable health which is local to the function and inaccesible from outside. |Meanwhile, the global health variable is untouched and inaccesible from the function unless you declare it as global with:
global health
inside the function and before using it.
So if you want to change the value from the function you have to declare it as global and then assign it a new value.
If you want instead to use only the argument passed to change the value, you have to pass a list with a single argument to the function and in the function change the content of the list:
def func(health):
health[0] += 1
health = [5]
func(health)
You could return the updated value from the function and re-assign it to the global variable. For example:
def CheckHealth(x):
return x - 1
health = 100
while True:
print(health)
health = CheckHealth(health) # The new value will be updated here
if health == 0:
break