0

I'm trying to make a list of the number of days corresponding to months and I need to account for leap years and I want to be able to access either 28 days or 29 days depending on if it's a leap year. This is what I have:

def code(x)
    monthdays = [31, lambda x: 28 if leapyear(x) == False else 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    return months[1]

leapyear() is just a function with 1 parameter that returns True if it is a leapyear and False otherwise. For some reason that won't return the number I want. How else can I do this?

2
  • 3
    Just delete lambda x:. And where is months coming from? Commented Apr 15, 2015 at 1:41
  • Perhaps, it set's x to 28 when there is no leap year (from what I am getting). Commented Apr 15, 2015 at 1:41

2 Answers 2

3

You don't need a lambda here (and anyway you're not calling it), a simple conditional expression will do the trick. Try this:

monthdays = [31, 29 if leapyear(x) else 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

Also, I believe that in the last line you meant this:

return monthdays[1]

…Otherwise what's the point of creating monthdays if we're not going to use it? Even more, why create a whole list if we're interested in a single position?

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! and sorry, I was in kind of a rush when I asked my question and didn't pay attention to my variable name. Thanks!
0

If you want to be precise about what is a leap year and calendar events it is recommended to use calendar.monthrange. You can use it like this:

from calendar import monthrange

year = 2015
days = []
for month in range(1,13):
    days.append(monthrange(year, month)[1])

print(days)

which returns a list containing the number of days for each month of a given year:

[31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

and if you just want Feb's number of days you can just calculate that:

from calendar import monthrange

year = 2015
feb_days = monthrange(year, 2)[1]
print(feb_days)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.