Testing Multiple values against a single variable in Python.

·

2 min read

I came upon a problem where I was getting a True value when trying to determine if it was a weekday or a weekend regardless of any of my input.

The problem looked like this

day = input("What day is it?:" )

if day == "Saturday" or "Sunday":
    print("It is the weekend")

else:
    print("It is a weekday")

The code identifies every day as a weekend, even if you mention a fruit it identifies the fruit as a weekend.

What day is it?: Sunday
It is the weekend

What day is it?: Thursday
It is the weekend.

What day is it?: Banana
It is the weekend.

After my research to solve this problem, I learned that Python has always been likened to the English Language, which makes it easy for beginners to get confused when they get logical errors while trying to solve a problem like the one I have above.

When you have a conditional statement like this, you are tempted to think that Python would interpret it just like natural English, but instead, python approaches the problem in a literal-minded manner.

When you run the code above, you will notice it identifies “Saturday” and “Sunday” as the weekend, but it also recognizes “Thursday” as a weekend. This proves that the conditional statement is not correct.

It is going to look like this when breaking down how Python approaches this problem

if (day == "Saturday") or ("Sunday"):

# which is equivlent to 

if (true) or (true):

The code above satisfies the "if" condition causing the "if" block to execute and print "It is the weekend".

Now when trying with "Thursday", this is what the problem looks like

if (day == "Thursday") or ("Sunday"):

# which is equivlent to 

if (False) or (true):

The or operator chooses the first operand that is "True", i.e. which would satisfy an if condition (or the last one, if none of them are "True"):

if "Sunday":

Since "Sunday" is true, the if block executes. That is what causes "It is the weekend" to be printed regardless of the day given.

There are two common methods to correctly construct this conditional statement and another method that is not as common

There are two common ways to properly construct this conditional.

  1. Use multiple == operators to explicitly check against each value:

     if day == "Saturday" or day == "Sunday":
    
  2. Compose a collection of valid values (a set, a list or a tuple for example), and use the in operator to test for membership:

     if day in {"Saturday", "Sunday"}: