1

I know this is very rudimentary, but I am new to programming and this is driving me NUTS.

Can someone tell me why I am getting "30" and not "28" as the answer to this?

def days_in_month(month):
    if month == 4 or 6 or 9 or 11:
        return 30
    else:
        if month == 2:
            return 28
    else:
        return 31

print(days_in_month(2))
Efie
  • 1,430
  • 2
  • 14
  • 34
  • Sorry for the possible duplicate, like I said I am new to coding (and this site) and therefore also new to searching for answers here. I'm not sure I would have thought to word it that way. – Efie Sep 14 '14 at 20:19
  • Your computation will not be correct for leap years. And, as many times, there is a module to get you what you want; see: http://stackoverflow.com/questions/9481136/how-to-find-number-of-days-in-the-current-month – ngulam Sep 14 '14 at 20:26
  • I understand that there is a module for leap year. I am just doing it myself as part of a free online course to learn python. What specifically would be wrong about the is_leap_year function? Edit: I'm an idiot -- I created a function for leap years but didn't put it in the code as I felt it wasn't relevant to the question. Thank you for pointing that out, though. – Efie Sep 14 '14 at 20:30

1 Answers1

2

The following is not quite correct (it's syntactically valid but doesn't do what you expect it to do):

if month == 4 or 6 or 9 or 11:

Change it to:

if month in {4, 6, 9, 11}:

Also, your top if statement has two else clauses. This is not valid syntax. I'd suggest taking a look at the tutorial to learn about the if statement.

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