Requirement: Enter a certain month of a certain year to determine how many days there are in this month
Analysis:
1, 3, 5, 7, 8, 10, 12: 31 days 4, 6, 9, 11
: 30 days
2: leap year: 29 days, normal year: 28 days Core: determine whether
the input year is a leap year or a normal year
1: Year %400 == 0 leap year 2000
Case 2: Year %4 == 0 and year %100 != 0 1900 is not a leap year
code:
'''方法一'''
if __name__ == '__main__':
year = int(input('请输入年份:'))
month = int(input('请输入月份:'))
# 判断
if month in [1, 3, 5, 7, 8, 10, 12]:
days = 31
elif month in [4, 6, 9, 11]:
days = 30
else:
# 处理2月份
if year % 400 == 0 or (year % 4 == 0 and year % 100 != 0):
days = 29
else:
days = 28
# 输出
print('%d年%d月:%d天' % (year, month, days))
'''方法二'''
year = int(input('请输入年份:'))
month = int(input('请输入月份:'))
# 定义一个list
days_list = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
# 判断是否是闰年
if (month == 2) and (year % 400 == 0 or (year % 4 == 0 and year % 100 != 0)):
print('%d年%d月:%d天' % (year, month, days_list[month - 1] + 1))
else:
print('%d年%d月:%d天' % (year, month, days_list[month - 1]))