Kohdee Kohdee - 1 year ago 79
Python Question

Python, not following if statements

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("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")
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("ok, select a different race")
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)

Answer Source

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"]:


if p['race'].upper() == "ELF":
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download