Python - Get a function to overwrite a variable
Question: So I'm testing out some mechanics for a text-based game I was going to make.
If the player has armour it would halve the damage they take and if not they
would take full damage. The problem I'm having is that whenever I try to run
the functions twice, it resets the health because it has been hardcoded. So
I'm wondering how can I get the function to overwrite the health variable
after it runs each time?

Here is the code:

    
    
    import random
    inventory = ["Armour","Sword","Healing Potion"]
    health=100
    
    def randDmg():
        dealtDamage = random.randint(1,10)
        print("You have taken "+str(dealtDamage)+" damage.")
        return dealtDamage
    
    def dmgCheck(damage, health):
        if "Armour" in inventory:
            damage = damage/2
        else:
            damage = damage
        health-=damage
        return health
    
    print("Your new health is "+str(dmgCheck(randDmg(), health)))
    


Answer: Defining a global at the top of your dmgCheck function would work well - then
you don't need to pass it in as a local. While you're at it, if you call the
randDmg function within dmgCheck you won't need to pass that in either.

    
    
    import random
    inventory = ["Armour","Sword","Healing Potion"]
    health=100
    
    def randDmg():
        dealtDamage = random.randint(1,10)
        print("You have taken "+str(dealtDamage)+" damage.")
        return dealtDamage
    
    def dmgCheck():
        global health
        damage = randDmg()
        if "Armour" in inventory:
            damage = damage/2
        else:
            damage = damage
        health-=damage
        return health
    
    print("Your new health is" + str(dmgCheck()))
    print("Your new health is" + str(dmgCheck()))
    

That last bit could also be simplified by using pythons' string formating
syntax:

    
    
    print("Your new health is %s" % dmgCheck())
    

To do something similar using a Python Class you could use:

    
    
    import random
    
    class Game(object):
    
        def __init__(self, inventory, health):
            self.inventory = inventory
            self.health = health
    
        def randDmg(self):
            dealtDamage = random.randint(1,10)
            print("You have taken "+str(dealtDamage)+" damage.")
            return dealtDamage
    
        def dmgCheck(self):
            damage = self.randDmg()
            if "Armour" in self.inventory:
                damage = damage/2
            else:
                damage = damage
            self.health -= damage
            return self.health
    
        def play(self):
            result = self.dmgCheck()
            print("Your new health is %s" % result)
    
    
    
    game = Game(["Armour","Sword","Healing Potion"], 100)
    
    game.play()
    game.play()
    

