如何将一个功能集成到另一个功能中

时间:2016-11-21 01:26:37

标签: python range

作为我正在练习的类的练习我必须编写一些函数然后将它们集成到另一个函数中,到目前为止,我编写了两个函数函数,它们取一个整数y并告诉你这个整数是否是一个飞跃年和另一个将采用整数y(年)和整数n(月),并将告诉你该月有多少天。我想要做的是将第一个函数集成到第二个函数中,这样如果你在闰年输入二月,就会告诉你它有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")

非常感谢任何帮助!

3 个答案:

答案 0 :(得分:0)

您应该使用isLeapYear函数来确定是否从daysIn函数返回28或29天。

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

答案 1 :(得分: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中,函数也是一个对象。所以你可以把它作为参数传递给另一个函数。

答案 2 :(得分: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))