-1
month = int(input())
day = int(input())

if (month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 10) and day == 31:
  print(month+1)
  print(1)
elif month == 12 and day == 31:
  print(1)
  print(1)
elif (month == 4 or month == 6 or month == 9 or month == 11) and day == 30:
  print(month+1)
  print(1)
elif month == 2 and day == 28:
  print(month+1)
  print(1)
else:
  print(month)
  print(day+1)

I have this code that just gives the next day of the inputted day (e.g. inputting 3 [March] 4 will give 3 5). However, if I remove the parentheses in the if statements I get wrong answers. If I inputted something like 3 4, it would give the the first day of the next month (4 1). This happens no matter which day I choose. I know this has something to do with the or and and statements. I was wondering if someone could clear up why the output changes when the parentheses are removed.

  • 2
    Does this answer your question? [Priority of the logical statements NOT AND & OR in python](https://stackoverflow.com/questions/16679272/priority-of-the-logical-statements-not-and-or-in-python) – buran Feb 08 '21 at 18:27
  • Thanks! It said there that or takes priority over and. Wouldn't that mean that I don't need the parentheses? – opaque_dragon Feb 08 '21 at 18:31
  • 1
    Quite the opposite - `or` has lower priority than `and`. that is why without parenthesis is equivalent to `month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or (month == 10 and day == 31)`. There is also link to relevant python docs. – buran Feb 08 '21 at 18:35
  • That page says "It's NOT, AND, OR, from highest to lowest" -- I'm not sure how you would think that OR has higher priority... – John Gordon Feb 08 '21 at 18:36
  • While it doesn't answer the question as asked, a solution that avoids the whole precedence issue (and with less to type) would be `if month in [1,3,5,7,8,10] and ...` – G. Anderson Feb 08 '21 at 18:38

1 Answers1

0

Because operators have a priority. A table of the order the operators are evaluated can be found here.

TheEagle
  • 5,808
  • 3
  • 11
  • 39