1
command = input("what is harder to catch the faster you run? ")
ans = command.split(" ")

if "breath" or "air" in ans:
     print("you're smart")
else:
     print("sorry, you're wrong")

I'm not getting the expected result. The output is always:

print("you're smart")
shmsr
  • 3,802
  • 2
  • 18
  • 29
Thangesh
  • 13
  • 4
  • 2
    This should answer your question: [How to test multiple variables against a value?](https://stackoverflow.com/questions/15112125/how-to-test-multiple-variables-against-a-value) – mkrieger1 Jul 31 '20 at 15:49

2 Answers2

1

The reason why this doesn't work is because or is checking the truthiness of the two statements, it doesn't work to compare multiple values, only to OR multiple booleans. So what you really have is

if ("breath") or (("air" in ans) == True): 

Specifically, this is not checking if "breath" is in ans, but instead checking if breath:. More on that at the bottom of the answer.

You can check if both values are in ans by writing out the in ans part twice, like this:

if "breath" in ans or "air" in ans:

or if you think you will wind up checking a ton of values, you can do a list like the other answer mentioned:

wordlist = ["breath", "air", ...]
contains_word = False
for word in wordlist:
  if word in ans:
    contains_word = True
    break
if contains_word:
  #do stuff

Note: "breath" is being evaluated for truthiness by the or. In python, non-empty strings are "truthy", and empty strings are "falsy". If you do "breath"==True then you would get False, but if you do if "breath": , then the if statement would evaluate as True. Whereas if "": would evaluate as False.

Cz_
  • 371
  • 2
  • 8
0

You could use a set.intersection() shorthand.

#if ans is a list - ex ["your", "breath"]
if {"breath", "air"} & {*ans}:
    #do something

You could tie it together so all of your questions and answer sets are in lists that you zip and loop over.

qn = ["What is harder to catch the faster you run? ", ...]
an = [{"breath", "air"}, ...]

for q, a in zip(qn, an):
    ans = input(q).lower().split(" ")
    if a & {*ans}:
        print("You're smart!")
    else:
        print("Sorry, you're wrong.")

You could even do input, check and print on one line.

qn = ["What is harder to catch the faster you run? ", ...]
an = [{"breath", "air"}, ...]

for q, a in zip(qn, an):
    print("You're smart!" if {*input(q).lower().split(" ")} & a else "Sorry, you're wrong.")
OneMadGypsy
  • 4,640
  • 3
  • 10
  • 26