-1

I tried using global but it doesn't seem to re-assign the variable. Sorry if this has already been answered, I couldn't find an answer. Whenever I run the code, It outputs the health by the calculation, but it doesn't calculate again e.g. if the health is 10, and I run the function, I would get 7. If I re-run, I would get another 7; it wouldn't go down anymore

def mon_attack(health, monDamage, defense):
    print("The monster attacked!")
    health = health - ((monDamage // defense) + 1)
    print("You have " + str(health) + " health left!")
Z0X
  • 1
  • 2
  • 1
    Although in this particular case, it would probably be easiest to `return` the new `health` value from the function and reassign it at the call site. – Carcigenicate Dec 20 '20 at 18:57
  • 1
    Related: [What is the purpose of the return statement?](https://stackoverflow.com/questions/7129285/what-is-the-purpose-of-the-return-statement) | [Why can a function modify some arguments as perceived by the caller, but not others?](https://stackoverflow.com/questions/575196/why-can-a-function-modify-some-arguments-as-perceived-by-the-caller-but-not-oth) – wwii Dec 20 '20 at 19:01
  • You should return `health` and assign the return value. `health = mon_attack(health, monDamage, defense)` – wwii Dec 20 '20 at 19:05

2 Answers2

1

Health is a local variable, it exists only for the duration of the function. Though you probably call the function and may pass in another variable named health, that variable is in a different scope and is just a different variable with the same name, so when you modify health in your function you only modify the local version, not the version that you called the function with. What you can do instead is have the function return the new value of health after the attack and move the print statements outside the function.

mCoding
  • 4,059
  • 1
  • 5
  • 11
0

With global variable - remove the "health" function parameter:

health = 100
def mon_attack(monDamage, defense):
    global health
    print("The monster attacked!")
    health = health - ((monDamage // defense) + 1)
    print("You have " + str(health) + " health left!")