1

I have a code that will allow the user to input a name, and based off of the name that is input, the script will perform different actions. For simplicity I've placed the snippet that is working incorrectly below.

print system
if "KH" or "Oberon" or "Bearcat" in system:
    print"Type 2"
elif "Sentry" in system:
    print"Type 1"

The user inputs Sentry but the script keeps falling in the "Type 2" statement. The print System command is outputting Sentry so i don't quite understand why its not doing the right thing here.

bladexeon
  • 696
  • 3
  • 10
  • 31
  • 1
    This is a hard to find dupe ... Basically, your `or` statements aren't doing what you think they are. you want something like `if any(substr in system for substr in ('KH', 'Oberon', 'Bearcat'))` – mgilson Dec 14 '15 at 17:02

2 Answers2

2

You need to change your code to this:

if "KH" in system or "Oberon" in system or "Bearcat" in system:

Currently your code does this

if ("KH") or ("Oberon") or ("Bearcat" in system):

which always evaluates to true as both "KH" and "Oberon" are non-empty strings.

Alex
  • 21,273
  • 10
  • 61
  • 73
  • Little nitpick: Using an tuple instead of a list for the in check would be enough and IMHO also the logical choice for this, as the values aren't going to change. – SleepProgger Dec 14 '15 at 17:14
  • Thanks @mgilson, I removed it. Didn't have time to test it as something urgent popped up. – Alex Dec 14 '15 at 17:18
1

Your or expressions aren't doing what you think they are. Python reads this as:

if "KH" or ("Oberon" or ("Bearcat" in system)):

which is equivalent to:

if "KH":

since "KH" is truthy and the or operator short circuits. One fix is something like:

if any(substr in system for substr in ('KH', 'Oberon', 'Bearcat')):
mgilson
  • 300,191
  • 65
  • 633
  • 696
  • Your solution and explanation here works. I question however how this is possible to pass as true, as system does not hold the string KH, would it not produce False for that first if statement? – bladexeon Dec 14 '15 at 17:16
  • 1
    @bladexeon -- Sorry, I had my [operator precedence](https://docs.python.org/2/reference/expressions.html#operator-precedence) mixed up. – mgilson Dec 14 '15 at 17:22