0

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
JITTU VARGHESE
  • 435
  • 1
  • 4
  • 6
  • 1
    https://www.tutorialspoint.com/global-and-local-variables-in-python – rdas Oct 20 '20 at 13:06
  • 2
    Python uses pass-by-value when passing arguments to a function. That means that `CheckHealth` gets its own private copy of `health` when called (and in fact, the caller could pass an expression rather than a variable). In any case, the caller won't see the change (basically `CheckHealth` doesn't do anything visible). You might be better off creating a class to hold your state. Then `CheckHealth` could be a method that changes the value of `health` in the instance that invokes it. – Tom Karzes Oct 20 '20 at 13:10

2 Answers2

0

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)
nadapez
  • 2,603
  • 2
  • 20
  • 26
0

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
Shreevardhan
  • 12,233
  • 3
  • 36
  • 50