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

0

u/Diapolo10 I write code for a living -- https://github.com/Diapolo10 Oct 13 '24

The others already beat me to explaining what happened, but I still want to suggest some improvements.

import calendar
import locale

# You presumably want English months, this makes
# sure of that; remove if you prefer localised names
locale.setlocale(locale.LC_ALL, 'en_GB')

MONTHS = list(map(str.upper, calendar.month_name))[1:]

month = input("Enter a month: ").strip().upper()

if month not in MONTHS:
    print("That's not a month")
    raise SystemExit

month_num = MONTHS.index(month) + 1

if month_num == 2:
    print("it has 28 days, but 29 on a leap year")

elif month_num in {4, 6, 9, 11}:
    print("it has 30 days")

else:
    print("it has 31 days")

This way you don't need to spell out the months yourself, there's a lot less typing involved, and it's trivial to add support for localised month names if you wish.