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?

2

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

1 Comment

I can use that if I experience trouble in the future. For now, global variables can work.
0

Short answer:

enemyHealth = 100

def Attack():
    global enemyHealth
    enemyHealth -= 10

2 Comments

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.