1

I'm writing a simple text-based game in Python 2.7. In the code below, even if the user answers something completely different than "run" or "nothing," the arrested() function still kicks in. I'm pretty sure the problem is in this line of code:

if "run" or "nothing" in answer:

because if I only provide one string, as follows:

if "run" in answer:

the program runs beautifully, calling remote_spot() if the answer does not contain "run". The whole code is the following:

def facing_cops():
    print "There are several cars that might serve as stake-outs for the cops. What do you do?"
    answer = raw_input("> ")
    if "run" or "nothing" in answer:
        arrested("Cops got suspicious. You are arrested, along with the drug dealer.")
    else:
        remote_spot()

What do you think is the matter?

Thanks,

Chris

Chris
  • 1,173
  • 11
  • 19

2 Answers2

3

The or does not do what you want it to do. What you wrote is the same as:

if "run" or ("nothing" in answer):

"run" is a string and in a boolean context it is understood as True. So you want:

if "run" in answer or "nothing" in answer:
syntonym
  • 7,134
  • 2
  • 32
  • 45
2

The operator 'in' has priority over 'or' so that you're effectively testing if "run" or ("nothing" in answer). If you only have two, you can well write:

if "run" in answer or "nothing" in answer:

If ever you have more keywords to test than 2, things get a bit long to write and you could go for this option:

keywords = ["run","nothing","otherkeyword"]
if any(keyword in answer for keyword in keywords):
vermillon
  • 543
  • 2
  • 8
  • 19