Search code examples
pythonparametersglobal-variables

How do I re-assign a variable in a function (python)


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!")

Solution

  • 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!")