0

Using this bit of code works as intended:

#!/usr/bin/python

import sys

good = sys.argv[1]
if 'good' in good:
    print good
else:
    print 'bad'
---
>>> ./script.py good
good
>>> ./script.py good123
good123
>>> ./script.py hi
bad

But when I add an or to the if statement, the script 'stops' to work the way I thought it would work.

if 'good' or 'GOOD' or 'Good' in good:

I get:

>>> ./script.py hello123
hello123

Why is that ?

soBusted
  • 197
  • 3
  • 18

1 Answers1

3

Adding some brackets should help show what's being evaluated:

if 'good' or 'GOOD' or ('Good' in good):

The in has a higher precedence than or, and doesn't act as you expected. So the or will return the first truthy argument, which will always be 'good', and the if will always succeed and run the code block.

xavc
  • 1,245
  • 1
  • 8
  • 14
  • I thought of something as well, but mine seems a bit more 'costly' and less dynamic: if 'scp' in scp or 'Scp' in scp or 'SCP' in scp: – soBusted Jul 12 '20 at 08:44
  • Yes that would be the correct solution, you could alternatively use `str.lower` (although this would also accept `GoOd`) like this: `'good' in good.lower()`, or in general you could use a loop to iterate through all the possibilities. – xavc Jul 12 '20 at 08:46