-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.')
Giz
  • 1
  • 2
  • 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 – Sayse Mar 23 '22 at 11:54

1 Answers1

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:
AKX
  • 152,115
  • 15
  • 115
  • 172