定义和调用函数

时间:2019-03-29 10:14:21

标签: python-3.x

我想使用def创建函数,稍后可以在代码中调用

  • is_leap_year(year)给定年份(4位数字),如果是a年则返回true,否则返回false。 
  • month_name(number)给定一个月数,返回相应的名称。 1是一月,...,12是十二月。 
  • days_in_month(month_number,year)给定一个月(以数字的形式)和(4位数字)年,返回当月的天数(以2月为例,是否为年。
  • first_day_of_year(year)给定一个四位数的年份,请返回1月1日所在的日期。 0是星期日,…,6是星期六。 (请参阅作业2的问题2。)
  • first_day_of_month(month_number,year)给定一个月(以数字的形式)和(4位数字)年,返回该月的第一天所在的天数。 0是星期日,…,6是星期六。

我该怎么做?

代码:

def print_welcome():
    print('Test harness for calutils');

def get_selection():
    print('\nChoose from the following options:')
    print('0. quit')
    print('1. Test is_leap_year().')
    print('2. Test month_name().')
    print('3. Test days_in_month().')
    print('4. Test first_day_of_year().')
    print('5. Test first_day_of_month().')
    return int(input())


def test_leap_year():
    from calutils import is_leap_year

    year = int(input('Enter the year (4 digits):\n'))
    if is_leap_year(year):
        print('The year '+str(year)+' is a leap year.')
    else:
        print('The year '+str(year)+' is not leap year.')

def test_month_name():
    from calutils import month_name

    for month_number in range(1, 13):
        print('Month number '+str(month_number)+ ' is '+month_name(month_number)+'.')


def test_days_in_month():
    from calutils import days_in_month

    year = int(input('Enter the year (4 digits):\n'))
    for month_number in range(1, 13):
        print('The days in the month with number '+str(month_number)+ ' in year '+str(year)+' is '+str(days_in_month(month_number, year))+'.')

def test_first_day_year():
    from calutils import first_day_of_year

    year = int(input('Enter the year (4 digits):\n'))
    print('The first day of '+str(year)+' is '+str(first_day_of_year(year))+'.')

def test_first_day_month():
    from calutils import first_day_of_month

    month = int(input('Enter the month (1 for January, ..., 12 for December):\n'))
    year = int(input('Enter the year (4 digits):\n'))
    print('The first day of month '+str(month)+' in '+str(year)+' is '+str(first_day_of_month(month, year))+'.')

def main():
    print_welcome()

    selection = get_selection()
    while not selection==0:

        if selection==1:
            test_leap_year()
        elif selection==2:
            test_month_name()
        elif selection==3:

            test_days_in_month()
        elif selection==4:
            test_first_day_year()
        elif selection==5:
            test_first_day_month()
        else:
            print('That selection was not recognised.')

        selection = get_selection()


main()

0 个答案:

没有答案