程序應提示用戶輸入月份和年份(作為整數)并顯示該月的天數以及月份名稱。例如,如果用戶輸入 2 月和 2000 年,程序應顯示:Enter a month as an integer (1-12): 2Enter a year: 2000There are 29 days in February of 2000def numberOfDays(month, year): daysInMonths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] if month > len(daysInMonths) or year < 0 or month < 0: return "Please enter a valid month/year" return daysInMonths[month-1] + int((year % 4) == 0 and month == 2)def main(): year = int(input("Enter a year: ")) month = int(input("Enter a month in terms of a number: ")) print(month, year, "has", numberOfDays(month, year) , "days")if __name__ == '__main__': main()在這個程序中,我想顯示月份的名稱并將其打印在最后。那么程序會怎樣呢?我應該怎么辦?例如,如果輸入為 1,則 1 應指定為一月并打印。
2 回答

海綿寶寶撒
TA貢獻1809條經驗 獲得超8個贊
使用字典:
dict_month = {1:"January", 2: "February"} # and so on ...
print(dict_month.get(month), year, "has", numberOfDays(month, year) , "days")

飲歌長嘯
TA貢獻1951條經驗 獲得超3個贊
您可以使用日歷模塊來完成此任務:
import calendar
months = list(calendar.month_name) #gets the list of months by name
obj = calendar.Calendar()
y, m = int(input('Enter year: ')), int(input('Enter a month as an integer (1-12): '))
days = calendar.monthrange(y, m)[1]
print(f'There are {days} days in {months[m]} of {y}')
如果您只想檢查年份是否為閏年:
import calendar
print(calendar.isleap(int(input('Enter year: '))))
添加回答
舉報
0/150
提交
取消