Python: 有没有什么办法可以通过定义一个或多个函数来编写这段代码?

Python: Is there any way this code can be written by defining one or more functions?

好吧,我不完全是菜鸟,而是 python 的初学者,我一直在尝试使用函数创建以下程序,但是,我真的不知道函数是如何工作的目前似乎有点困难。这是问题:

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.

这是我的简单解决方案:

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')

欢迎任何建议:)干杯!

您可以将代码放在 returns 长度的函数中,而不是打印它。然后调用该函数并打印其结果。

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))

您可以利用一些日期实用程序:

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()))

一些文档: