python3 之 判断闰年小实例

2022-10-17,,,

一、方法1:

 1 while true:
 2     try:
 3         year = int(input('请输入一个年份:'))
 4         if (year % 4) == 0 and (year % 100) != 0 or (year % 400) == 0:
 5             print('{0}是闰年。'.format(year))
 6         else:
 7             print('{0}不是闰年。'.format(year))
 8         break
 9     except valueerror:
10         print('您输入的年份无法识别,请输入正确的年份(整数)。')

二、方法2:

 1 while true:
 2     try:
 3         year = int(input('请输入一个年份:'))
 4         if (year % 4) == 0:
 5             if (year % 100) == 0:
 6                 if (year % 400) == 0:
 7                     print('{0}是闰年'.format(year))    #整百年能被400整除的是闰年
 8                 else:
 9                     print('{0}不是闰年'.format(year))
10             else:
11                 print('{0}是闰年'.format(year))  # 非整百年能被4整除的是闰年
12         else:
13             print('{0}不是闰年'.format(year))
14 
15     except valueerror:
16         print('您输入的年份无法识别,请输入正确的年份(整数)。')

三、方法3:调用内部函数

 1 import calendar
 2 while true:
 3     try:
 4         year = int(input('请输入一个年份:'))
 5         check_year = calendar.isleap(year)
 6         if check_year:
 7             print('{0}是闰年'.format(year))
 8         else:
 9             print('{0}不是闰年'.format(year))
10         break
11     except valueerror:
12         print('您输入的年份无法识别,请输入正确的年份(整数)。')

 

《python3 之 判断闰年小实例.doc》

下载本文的Word格式文档,以方便收藏与打印。