2016-11-21 112 views
0

作爲一個我正在學習的類的練習,我必須編寫一些函數,然後將其中一個函數集成到另一個函數中,至此我編寫了兩個函數函數,它們需要一個整數y和告訴你這個整數是閏年,另一個整數是y(年)和整數n(月),並且會告訴你該月有多少天。我想要做的是將第一個函數集成到第二個函數中,這樣如果您在閏年中輸入2月,它會告訴您它有29天。如何將一個函數集成到另一個函數中

這是我迄今寫的代碼;

def isLeapYear(y): 
    if y % 400 == 0: 
     return True 
    if y % 100 == 0: 
     return False 
    if y % 4 == 0: 
     return True 
    else: 
     return False 

def daysIn (y,n): 
    import sys 

    d = int(0) 
    months = ["Notuary", "January", "Febuary", "March", "April", "May",  "June", "July", "August", "September", 
       "October", "November", "December"] 

    if n == 0: 
     print("This is a fake month") 
     sys.exit() 

    if n == 1 or n == 3 or n == 5 or n == 7 or n == 8 or n == 10 or n == 12: 
     d = 31 

    if n == 2 and (y % 4 != 0): 
     d = 28 

    if n == 2 and (y % 4 == 0): 
     print("Febuary has 29 days this year as it is a leap year") 
     sys.exit() 

    if n == 4 or n == 6 or n == 9 or n == 11: 
     d = 30 

    print(months[n], "has", d, "days in it") 

任何幫助將不勝感激!

+0

FWIW,你的'daysIn'功能可以使用組或列出你的一個月長度測試中取得了很多更緊湊,但我猜你可能還未了解這些。但函數頂部附近的'd = int(0)'有點沒有意義:不需要將零轉換爲整數,它是_already_整數,因此您可以執行'd = 0'。另外,在函數內部放置一個'import'語句是很不尋常的。只要把它放在腳本的頂部 –

回答

0

您應該使用您的isLeapYear函數來確定是否要從daysIn函數返回28天或29天。

if n == 2: 
    if isLeapYear(y): 
     print("It's a leap year!") 
     d = 29 
    else 
     d = 28 
0

試試這個

import sys 
def isLeapYear(y): 
    if y % 400 == 0: 
     return True 
    if y % 100 == 0: 
     return False 
    if y % 4 == 0: 
     return True 
    else: 
     return False 
def daysIn (y,n, func): 
    d = int(0) 
    months = ["Notuary", "January", "Febuary", "March", "April",  "May","June", "July", "August", "September","October", "November", "December"] 
    if n == 0: 
     print("This is a fake month") 
     sys.exit() 
    if n == 1 or n == 3 or n == 5 or n == 7 or n == 8 or n == 10 or n == 12: 
     d = 31 
    if n == 2 and func(y): 
     d = 28 
    if n == 2 and func(y): 
     print("Febuary has 29 days this year as it is a leap year") 
     sys.exit() 
    if n == 4 or n == 6 or n == 9 or n == 11: 
     d = 30 
    print(months[n], "has", d, "days in it") 
daysIn(1996, 2, isLeapYear) 

在Python中,函數也是一個對象。所以你可以將它作爲參數傳遞給另一個函數。

+1

這是一個非常令人困惑的方式來寫這個。 – erip

+0

對不起,我不承認你的意思。你的意思是我的縮進錯誤? –

+1

我的意思是整個事情。 – erip

0

只需從另一個內部調用1個函數即可。

例如:

def daysIn (y,n): 
    import sys 

    isleap = isLeapYear(y) 

    # SNIP 

    print(months[n], "has", d, "days in it") 
    print("Is {} a leap year? {}".format(y, isleap)) 
相關問題