0

Why does using the 'or' operator give different results in this case? Why must I write the day.weekday() twice rather than just == 5 or 6


This is the option that works

if day.weekday() == 5 or day.weekday() == 6: 

This is the option that gives a different result

if day.weekday() == 5 or 6:
furas
  • 134,197
  • 12
  • 106
  • 148
Haython
  • 7
  • 5

2 Answers2

1

Or statements work as such:

if (condition) or (condition):

By saying:

if day.weekday() == 5 or 6:

The code thinks that you are implying that 6 is a condition, which if you are trying to print something if it's a Saturday (since saturday is the 6th day of the week), you won't get anything printed. Hope this helps, leave a comment if it doesn't, or you need additional help.

1BL1ZZARD
  • 225
  • 2
  • 14
1

It gives a different result because "day.weekday() == 5" and "6" are being evaluated separately. It doesn't give you an error because any number that is not 0 evaluates to "True".

The better way to write this would be:

if day.weekday() in (5, 6):
JWCompDev
  • 455
  • 1
  • 5
  • 19
  • what is the 6 being evaluated as? – Haython Mar 16 '22 at 00:58
  • basically the 6 is just being converted to a boolean. Any number that is 0 will be False. Any number that is not 0 will be True. So that's why if you want to check multiple values you have to use in. Putting the 5 and 6 in parentheses puts it in a tuple so calling in checks if the value of day.weekday() is in the tuple. – JWCompDev Mar 16 '22 at 01:04
  • No problem, glad to help – JWCompDev Mar 17 '22 at 02:21