2016-01-24 53 views
-3

這是我的代碼:代碼檢查閏年和月計數無天的

def cal(month): 
    if month in ['January', 'march','may','july','august','oct','dec']: 
     print ("this month has 31 days") 
    elif month in ['april','june','sept','nov']: 
     print ("this month has 30 days") 
    elif month == 'feb' and leap(year)== True: 
     print ("this month has 29 days") 
    elif month == 'feb' and leap(year) == False: 
     print ("this month has 28 days") 
    else: 
     print ("invalid input") 


def leap(year): 
    if (year % 4== 0) or (year % 400 == 0): 
     print ("its a leap year!") 
    else: 
     print ("is not a leap year") 

year = int(input('type a year: ')) 
print ('you typed in :' , year) 
month = str(input('type a month: ')) 
print ('you typed in :', month) 



cal(month) 
leap(year) 

我收到的輸出:

type a year: 2013 
you typed in : 2013 
type a month: feb 
you typed in : feb 
is not a leap year 
is not a leap year 
invalid input 
is not a leap year 

爲什麼我沒有得到輸出如果是28天的月份還是29天,那麼在feb中的天數是多少?

爲什麼我會得到無效的輸入部分,即使它是一個其他的?

+6

'leap'的返回值是'None'。 'None == True'和'None == False'都是錯誤的。 – vaultah

+2

1900年不是閏年。你的測試會假設它是。 –

+0

謝謝隊友。解決了它。 :) – Teejay

回答

1

你不應該嘗試用你自己的功能取代基本的功能。 Python有模塊來管理日期。你應該使用它。

https://docs.python.org/2/library/calendar.html#calendar.monthrange

>>> import calendar 
>>> calendar.monthrange(2002,1) 
(1, 31) 

而對於閏年,還是在DOC:

https://docs.python.org/2/library/calendar.html#calendar.isleap 

關於你的代碼,你的函數leap應該返回一個布爾值,因爲你在一個條件語句中使用它,否則leap(whatever) == true將始終返回false。

+0

問題是,作者試圖做一些他不應該這樣做的方式。 – JesusTheHun

+3

的確如此,但是如果是這樣的話,你的回答應該解釋一下,並且通常仍然解釋代碼的錯誤。 –

+0

你是對的。我編輯了我的答案,使其更加友好和教育。 – JesusTheHun

1

您只需在閏年(年)函數中返回True或False即可正常工作。

這是與維基百科的閏年算法。

def leap(year): 
    if year % 400 == 0: 
     return True 
    if year % 100 == 0: 
     return False 
    if year % 4 == 0: 
     return True 
    else: 
     return False 
+1

查看此評論[Jon Leffler](http://stackoverflow.com/questions/34978182/code-for-checking-leap-year-and-counting-no-of-days-in-a-month#comment57685751_34978182 ) –

+0

更改了算法:) – MetalloyD

+0

看起來更好。 :) –