0

I'm trying to create a text bases dungeon game. Just for fun and practice but I'm having a problem with Python not following my if blocks. The weird thing is that it worked when I first typed it out, but a day later it's not. It's treating as if all conditions are true.

choosing_race = True
while choosing_race == True:
    print("options: Human, Elf, Dwarf")
    p['race'] = input("Choose Race: ",)
    print(p['race'], choosing_race)

    if p['race'] == "Elf" or "elf":
        print()
        print("Elves are nimble, both in body and mind, but their form is frail. They gain Bonuses to Intelligence and Dexterity and a Penalty to Constitution")
        print()
        confirm_race = input("Are you an Elf? ",)
        if confirm_race == "yes" or "Yes":
            p['int_mod_r'] = 2
            p['dex_mod_r'] = 2
            p['con_mod_r'] = -2
            choosing_race = False
        elif confirm_race == "no" or "No":
            print()
            print("ok, select a different race")
        else:
            print()
            print("Could not confirm, try again")

The p[race] input shows fine, but I can type anything (example duck) and it acts as if I typed elf. When I ask to confirm_race it's always returning yes. I assume I must have put a typo in there, but I can't find it. I redid all my indenting but still no luck. I'm going to try to restructure with functions and maybe that will help. In the mean time I'd love to know what went wrong here so I can prevent it in the future. Thanks. (I'm using Python 3, on my Nexus 5 phone is case that matters)

Kohdee
  • 3
  • 3
  • You might also want to check that the input is valid with something along the lines of: `is_a_valid_choice = p['race'].lower() in ['human', 'elf', 'dwarf']` – Alexander Sep 12 '16 at 14:08

1 Answers1

4

You are not getting the behavior you expect from lines like

if p['race'] == "Elf" or "elf":

In this case, "elf" evaluates to true every time. You want to instead write

if p['race'] == "Elf" or p['race'] == "elf":

or more concisely

if p['race'] in ["Elf", "elf"]:

or

if p['race'].upper() == "ELF":
jeff carey
  • 2,313
  • 3
  • 13
  • 17
  • The reason for both "Elf" or "elf" in so the user doesn't have to worry about case sensitivity. Is there a better way to change that? – Kohdee Sep 12 '16 at 14:01
  • Yes, the last line I wrote will take any variant, including things like elf, Elf, and even things like ELf and eLf – jeff carey Sep 12 '16 at 14:02
  • Thanks, I'll use . upper. This might seem basic but I'm not understanding why Elf or elf always returns true. – Kohdee Sep 12 '16 at 14:20
  • Any non-blank string in Python will evaluate to True. So when you write if x == "Elf" or "elf", the second part is not checking if x == "elf", it's just evaluating "elf", which is always True. – jeff carey Sep 12 '16 at 14:23