-1
import random

hp = 100
eh = 100



while hp > 0 and eh > 0:

    print("Action? (attack, heal, nothing):")

    act = input(">")

    attack = random.randint(1, 30)

    heal = random.randint(1, 15)




if act == "attack" or "Attack":
    eh = eh  - attack
    print(attack)
    print("eh = %s" % eh)

elif act == "heal" or "Heal":
    hp = hp + heal
    print("You have healed %s points" % heal)
    print(hp)

Why is it that when I type heal, it runs the attack part as well? Even when I type neither attack nor heal it still runs the attack section.

user3352353
  • 265
  • 2
  • 3
  • 4
  • 1
    Meet a useful [method](http://docs.python.org/2/library/stdtypes.html#str.lower): `if act.lower() == "attack":` – dawg Mar 03 '14 at 00:53

4 Answers4

1

Your use of or is incorrect. It's acting as if you had:

if (act == "attack") or ("Attack"):

Any non-empty string evaluates as True.

Instead use:

if act == "attack" or act == "Attack":

Or even:

if act in ("attack", "Attack"):
Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
0

In this conditional:

if act == "attack" or "Attack":

The part after the or always evaluates to true.

>>> if "Attack":
...     print "Yup."
...
Yup.

What you probably meant is

if act == "attack" or act == "Attack":
    eh = eh  - attack
    print(attack)
    print("eh = %s" % eh)

elif act == "heal" or act == "Heal":
    hp = hp + heal
    print("You have healed %s points" % heal)
    print(hp)

Though a better way is

if act.lower() == "attack":
Wes Modes
  • 2,024
  • 2
  • 22
  • 40
0

First of all, I assume that the if and elif part is indented to fit into while loop.

The reason behind it firing Attack part all the time, is your condition:

if act == "attack" or "Attack":

It basically equals to

if (act == "attack") or ("Attack"):

Which means the same as

if (act == "attack") or (True):

So its actually always true.

To make it work you should repeat "act == " part before "Attack too" so it s

if act == "attack" or act == "Attack":
  eh = eh  - attack
  print(attack)
  print("eh = %s" % eh)

elif act == "heal" or act == "Heal":
  hp = hp + heal
  print("You have healed %s points" % heal)
  print(hp)
0

Unless I'm mistaken, I think your if statement should be

if act == "attack" or act=="Attack":

As it is,

if "Attack" 

will always evaluate as true, so the attack portion will always run.

I might also recommend doing

act.toLower() == "attack"

This way you can do a single comparison and ignore case sensitivity. Just a thought.