【python】判断年份是否为闰年


1、计算今年是闰年嘛?判断闰年条件, 满足年份模400为0, 或者模4为0但模100不为0.

 

代码如下:

1 x = int(raw_input('please enter a year:'))
2 if x % 4 == 0 and x % 100 != 0:
3   print 'yes'
4 elif x % 400 == 0:
5   print u"yes"
6 else:
7   print u"no"

关键点:

1、sublime text 2中需要加载sublimeREPL包才能进行交互,否则会出现:

EOFError: EOF when reading a line

2、int!int!int!重要的事情说三遍!!!如果不用int()进行强制类型转换,会出现:

TypeError: not all arguments converted during string formatting(并非所有的参数在列表中进行了字符串格式转换)

!!!

以下为http://wiki.woodpecker.org.cn/moin/ObpLovelyPython/LpyAttAnswerCdays上给出的参考答案。

 1 #coding:utf-8
 2 '''cdays-5-exercise-1.py 判断今年是否是闰年
 3     @note: 使用了import, time模块, 逻辑分支, 字串格式化等
 4 '''
 5 
 6 import time                             #导入time模块
 7 thisyear = time.localtime()[0]             #获取当前年份
 8 if thisyear % 400 == 0 or thisyear % 4 ==0 and thisyear % 100 <> 0: #判断闰年条件, 满足模400为0, 或者模4为0但模100不为0
 9     print 'this year %s is a leap year' % thisyear
10 else:
11     print 'this year %s is not a leap year' % thisyear

(在自己机器上跑会有问题,注释部分用了中文,无法显示。。。需要把2-4行删掉。。。)


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM