1

I'm trying to write a small program that takes the month number and convert it into the days that month has. If someone can please point our some of the wrong coding i have that would be great. And please i am not trying to import calendar as i am trying to have it very simple. Thanks -Joel

try:
month = int(input("Enter a month Number from 1 - 12: "))
#February
if month == 2:
    print("28 or 29 Days")
else:
    #31 day months
    if month in(1 , 3 , 5 , 7 , 8 , 10 , 12):
        print("31 Days")
        #Rest of the months 
        if month in(2 , 4 , 6 , 9 , 11):
            print("30 Days")
    #Invalid input

except ValueError:
    print("Invalid Input")

EDIT: I have updated the code a bit but i am still getting a logic error whenever a number larger than 12 is entered. Looking to get an "invalid answer" print statement when a number other than 1-12 are typed.

 #Enter a month Number from 1 - 12: 100
 #>>> 

1 Answers1

4

The

if month == (1 or 3 or 5 or 7 or 8 or 10 or 12):

should be

if month in {1, 3, 5, 7, 8, 10, 12}:

In your current code, the expression 1 or 3 or 5 or 7 or 8 or 10 or 12 is first evaluated and then month is compared to the result (which happens to be 1).

This means that the program only works correctly for 1 (printing 31) and 2 (printing 28 or 29); for everything else it falls through to the final else clause and prints 30.

NPE
  • 486,780
  • 108
  • 951
  • 1,012