Python syxtax公司

2024-06-28 20:35:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着写这个程序来计算两个日期之间的天数差,计算闰日,第二个输入日期总是在第一个之后

更新:不再有NoneType错误,但显示def test()语法错误: 这行def test()(以及下面的内容)是由提问者编写的(Udacity.com网站)语法错误是什么?你知道吗

def order4(y,m,d): #refers to the order of the date counting from the last leap year
    mo=0
    for i in range(m-1):
        if i in set([0,2,4,6,7,9,11]):
            mo=mo+31
        if i == 1:
            mo=mo+28
        if i in set([3,5,8,10]):
            mo = mo+30
# mo = number of days from the beginning of the year to the current month
    order = 365*(y%4)+mo+d
    if order > 59 and (y%4,m,d)!=(0,2,29):
        order = order+1
    return int(order) 

print(order4(2011,6,30)) #to check that they are correct output numbers
print(order4(2012,6,30)) #to check that they are correct output numbers

def daysBetweenDates(year1,month1,day1,year2,month2,day2):
    diffdate = order4(year2,month2,day2)-order4(year1,month1,day1)
    if diffdate<0:
        diffdate=diffdate+1461
    return int((year2-year1)/4)+diffdate

print(daysBetweenDates(2012,1,1,2012,2,28))

def test():
    test_cases = [((2012,1,1,2012,2,28), 58), 
                  ((2012,1,1,2012,3,1), 60),
                  ((2011,6,30,2012,6,30), 366),
                  ((2011,1,1,2012,8,8), 585 ),
                  ((1900,1,1,1999,12,31), 36523)]
    for (args, answer) in test_cases:
        result = daysBetweenDates(*args)
        if result != answer:
            print ("Test with data:", args, "failed")
        else:
            print ("Test case passed!")

Tags: ofthetointestifdeforder
1条回答
网友
1楼 · 发布于 2024-06-28 20:35:43

我将您的代码剪切并粘贴到本地文件中,在Python3和Python2中运行,没有收到任何语法错误,并且都生成了输出:

1277
182
58

请记住,Python区分了制表符和空格,尽管它们看起来相同。听起来你的文件可能包含不正确的缩进,因为文件中有制表符?你知道吗

作为建议,我建议您使用编辑器,例如Emacs或sublimitext,它具有Python模式,可以帮助您确保源代码的格式正确。你知道吗

相关问题 更多 >