0

Very, very simple question here. How would I modify a variable through a function? I feel really dumb for asking this. Here's what I have:

enemyHealth = 100

def Attack():
    enemyHealth -= 10

Apparently, enemyHealth is not defined.

I would expect that you wouldn't need to return anything. What am I doing wrong?

EvilLemons
  • 13
  • 3
  • You need to declare the variable `global` if you want to modify it within a function. See [here](http://stackoverflow.com/a/4693170/2069350). But realistically, this is rarely the best solution--you'd more likely want an instance of some `Enemy` class, with its own `health` attribute for you to modify. See [this answer](http://stackoverflow.com/a/16210362/2069350) for an explanation/example. – Henry Keiter Jun 09 '14 at 21:35

2 Answers2

2

One way is to make it global, but that's a really bad sign. It makes it difficult to develop and debug functions, as you need to know about the global state to do so.

The simple way to avoid it is to pass values around:

enemy_health = 100

def attack(health, power=10):
    return health - power

enemy_health = attack(enemy_health)

print(enemy_health)

But it looks like you could use OOP here:

class Enemy:

    def __init__(self):
        self.health = 100

def attack(character, power=10):
    character.health -= power

enemy = Enemy() # create Enemy instance

attack(enemy) # attack it

print(enemy.health) # see the result
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
0

Short answer:

enemyHealth = 100

def Attack():
    global enemyHealth
    enemyHealth -= 10
U2EF1
  • 12,907
  • 3
  • 35
  • 37
  • Dear reader of this accepted answer, please be aware that experienced programmers try very, very hard not to use `global`. Using `global` leads to inflexible and unmaintainable code. In other words: do not do what this answer suggests. – Matthias Jul 06 '23 at 19:37