【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