Okay so I am not exactly a rookie but a beginner in python, and I have been trying to create the following program by using functions, however, I don't really know how functions work and it just seems a little tough for the moment. Here is the question:
The length of a month varies from 28 to 31 days. In this exercise you will create a program that reads the name of a month from the user as a string. Then your program should display the number of days in that month. Display “28 or 29 days” for February so that leap years are addressed.
And here is my simple solution:
name = input('What month is it? ')
thirty_days = ['April','June','September','November']
thirty_one_days = ['January','March','July','August','October','December']
feb = ['February']
if name in thirty_days:
print('Number of days: 30')
elif name in thirty_one_days:
print('Number of days: 31')
elif name in feb:
print('Number of days: 28 or 29')
Any suggestions are appreciated :) Cheers!
CodePudding user response:
You can put the code in a function that returns the length instead of printing it. Then call the function and print its result.
def month_length(name):
thirty_days = ['April','June','September','November']
thirty_one_days = ['January','March','July','August','October','December']
feb = ['February']
if name in thirty_days:
return 30
elif name in thirty_one_days:
return 31
elif name in feb:
return '28 or 29'
name = input('What month is it?')
print('Number of days:', month_length(name))
CodePudding user response:
You could leverage some date utils:
from datetime import datetime
from calendar import monthrange
def length(name):
d = datetime.strptime(name, "%B") # parse month by full name
l = monthrange(datetime.now().year, d.month)[1]
# may not be needed as you dynamically get the correct value for current year
# if l == 28:
# return "28 or 29"
return l
print('Number of days:', length(input()))
Some docs: