0

I'm trying to write a simple code that will tell me if the date that I need to do something falls on a weekend. When I run this code I get the "change day" regardless of the day of the week, there is obviously something wrong with the code but I can't see it

if week_Days[movePlates.weekday()] == "Saturday" or "Sunday":
    print("change day " + str(week_Days[movePlates.weekday()]))
else: 
     print("move plates on: " + str(movePlates))


if week_Days[readPlates.weekday()] == "Saturday" or "Sunday":
    print("change day " + str(week_Days[readPlates.weekday()]))
else: 
    print("read plates on: " + str(readPlates))

Change day Sunday Change day Thursday

Sabrina
  • 21
  • 8
  • 2
    Does this answer your question? [Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?](https://stackoverflow.com/questions/20002503/why-does-a-x-or-y-or-z-always-evaluate-to-true-how-can-i-compare-a-to-al) – jasonharper Jun 08 '23 at 22:59

2 Answers2

0

This is a result of implicit booleans. To add parentheses to your if statement (without changing it):

if (week_Days[movePlates.weekday()] == "Saturday") or "Sunday":
    print("change day " + str(week_Days[movePlates.weekday()]))
else: 
     print("move plates on: " + str(movePlates))

The problem is that you're treating the string "Sunday" in an or statement, where any nonempty string is True, so the or statement evaluates to True. Here's one solution:

if week_Days[movePlates.weekday()] == "Saturday" or week_Days[movePlates.weekday()] == "Sunday":
    print("change day " + str(week_Days[movePlates.weekday()]))
else: 
     print("move plates on: " + str(movePlates))

Or if you wanted to make it a little simpler with different syntax, you could do

if week_Days[movePlates.weekday()] in ("Saturday", "Sunday"):
    print("change day " + str(week_Days[movePlates.weekday()]))
else: 
     print("move plates on: " + str(movePlates))
Jacob Stuligross
  • 1,434
  • 5
  • 18
0

You need to test the variable against both days in your if-clause (or use the in() operator). I'd suggest wrapping the test in a function (and using lower() if the casing is not fixed):

def IsWeekend(a):
    return (a.lower() == "saturday" or a.lower() == "sunday")
wp78de
  • 18,207
  • 7
  • 43
  • 71