Python 函数def 编程题

题目一:您的任务是编写和测试一个函数,该函数接受一个参数(year),如果年份是闰年,则返回true,否则返回false。

def IsYearLeap(year):
    #year = int(input('年份:'))
    if year % 4 == 0 and year % 100 != 0:
        return True
    elif year % 400 == 0:
        return True
    else:
        return False
testdata = [1900, 2000, 2016, 1987]
testresults = [False, True, True, False]
for i in range(len(testdata)):
    yr = testdata[i]
    print(yr,"->",end=" ")
    result = IsYearLeap(yr)
    if result == testresults[i]:
        print("OK")
    else:
        print("Failed")

执行结果: 

1900 -> OK
2000 -> OK
2016 -> OK
1987 -> OK

题目二:您的任务是完善DaysInMonth函数,该函数接受两个参数(year,month),并返回给定的月/年对的天数。

def DaysInMonth(year,month):
    if month in [1,3,5,7,8,10,12]:
        return 31
    elif month in [4,6,9,11]:
        return 30
    elif month ==2:
        if year %4 ==0 and year % 100 !=0:
            return 29
        elif year % 400==0:
            return 29
        else:
            return 28
inputs = input("please input year/month:")#比如输入2000/10
#使用字符串的split方法获得年份和月份
yr =int(inputs.split('/')[0])
mo =int(inputs.split('/')[1])
result = DaysInMonth(yr,mo)
print(f"the days of {yr}/{mo} is {result}")

执行结果: 

please input year/month:2004/2
the days of 2004/2 is 29

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值