Mahdi_J
Mahdi_J

Reputation: 428

Problem with getting while loop to repeat in python

Whenever I run this program, I can't get the while loop to repeat. It's a simple exercise with classes and I don't know what I am doing wrong.

class Enemy():
    def attack(self):
        enemy_health = 50
        while enemy_health > 0:
            action = input("attack enemy?")
            if action.lower() == "yes":
                print("enemy health dropped by 5")
                enemy_health =- 5
            else:
                print("enemy escaped!")




jaguar = Enemy()
jaguar.attack()

I want the input to repeat until the enemy health is 0. Also, should I include any return statements in here instead of simply subtracting from enemy health? Thank you

Upvotes: 0

Views: 68

Answers (4)

bigwillydos
bigwillydos

Reputation: 1371

You have a typo here:

enemy_health =- 5

This sets enemy_health to -5. What you want to do is take whatever enemy_health is and subtract 5 from it and then store that value back in enemy_health.

You could do that like this: enemy_health -= 5

Or like this: enemy_health = enemy_health - 5

Upvotes: 0

juncaks
juncaks

Reputation: 96

It's because you have to inverse the operator to -=

Upvotes: 0

ruohola
ruohola

Reputation: 24038

You have a small mistake, this line:

enemy_health =- 5

Should actually be:

enemy_health -= 5

Your original line just sets the health to -5. Easier to see the mistake when you change the spacing:

enemy_health = -5  # same as the first line

Upvotes: 1

Jacob
Jacob

Reputation: 225

When you used enemy_health =- 5, you're not decreasing the enemy health by 5, you're setting it to - 5. Use enemy_health -= 5.

Upvotes: 0

Related Questions