-3

I'm brand new to Python. Why does the below always resolve true (i.e. satisfy the if statement).

I have found a solution by putting brackets around the or part (also below), but I don't know why the solution works. Grateful for your advice! Thank you in advance.

problem code:

 animals = ['dog', 'cat', 'mouse', 'shark']
    
    if 'fox' or 'fish' in animals:
      print('you found a new pet')
    else:
      print('you don\'t deserve a pet.')

solution code:

 animals = ['dog', 'cat', 'mouse', 'shark']
    
    if ('fox' or 'fish') in animals:
      print('you found a new pet')
    else:
      print('you don\'t deserve a pet.')
1
  • 1
    The "solution" works because "fox" or "fish" returns "fox" as it is truthy, and then you go on to check if fox is in animals, fish is never taken into account Commented Mar 23, 2022 at 11:54

1 Answer 1

1

Because if 'fox' or 'fish' in animals is parsed as

if 
  ('fox')
  or
  ('fish' in animals)

and 'fox', being a non-empty string, is truthy.

Then, in if ('fox' or 'fish') in animals: the expression ('fox' or 'fish') is evaluated to the first truthy value, 'fox', so the effective expression is if 'fox' in animals: (the fish is gone, presumably eaten by the cat).

You're likely looking for

if 'fox' in animals or 'fish' in animals:
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.