r/learnpython • • Oct 13 '24

My if statement doesnt work

Can anyone find any errors here? Im new to python so I dont know what I did wrong as every answer is responded with “it has 30 days”

month = input("Enter a month: ") month = month.upper() print(month) if month == "SEPTEMBER"or"APRIL"or"JUNE"or"NOVEMBER": print("it has 30 days") elif month == "JANUARY"or"MARCH"or"MAY"or"JULY"or"DECEMBER"or"AUGUST": print("it has 31 days") elif month == "FEBRUARY": print("it has 28 days, but 29 on a leap year") else: print("That's not a month")

This is what the output is like Enter a month: a A It has 30 days

1 Upvotes

18 comments sorted by

View all comments

2

u/nekokattt Oct 13 '24 edited Oct 13 '24

I reserve the point that the way Python's conditional operators work is overly confusing.

I personally think that or-ing a bool on the left hand side with a non bool on the right hand side for builtin types should raise a warning at runtime. In the tiny number of cases where you would want to say bool.__or__(str) or bool.__or__(list) or similar, it should be cast explicitly to bool to make it clear that it is the intention.

While it leads to more verbose code, I honestly think the way languages like Java restrict the use of conditions to only be boolean values is far more sensible in terms of reducing the number of ways to write confusing expressions.

if ("APRIL".equals(month) || "JUNE".equals(month) || ...) {
  ...
}

In OPs case, a match statement would be a better way of dealing with this:

match month:
  case "APRIL" | "JUNE" | "SEPTEMBER" | "NOVEMBER":
    ...
  case "FEBRUARY":
    ...
  case _:
    ...

You could also use a dict, but I'd argue that this is logic rather than data, so using logic to represent it is more appropriate.