我是蟒蛇新手并从Udacity学习语言。我想写一个python程序,它占用2个日期并输出这两个日期之间的日差,假设第二个日期是后者。
它抛出错误说:
File /Users/gonewiththewind/Documents/days old.py", line 20, in daysBetweenDates
currentDaysOfMonths = daysOfMonths[isLeap(year)][month - 1]
TypeError: list indices must be integers, not NoneType"
when I tried to call the function by "daysBetweenDates(1995,7,28,2018,1,26)
以下是代码:
daysOfMonths = [[31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]]
def isLeap(year):
if year % 400 == 0:
return True
else:
if year % 100 == 0:
return False
else:
if year % 4 == 0:
return True
def daysBetweenDates(year1, month1, day1, year2, month2, day2):
counter = 0
month = month1
year = year1
day = day1
while(year != year2 or month != month2 or day != day2):
currentDaysOfMonths = daysOfMonths[isLeap(year)][month - 1]
if(day < currentDaysOfMonths):
day = day + 1
counter = counter + 1
print 'counter = '+ counter
else:
day = 1
if(month1 < 12):
month = month + 1
else:
month = 1
year = year + 1
counter = counter + 1
print 'counter = '+ counter
return counter
答案 0 :(得分:3)
return
函数中缺少is_leap
:
def isLeap(year):
if year % 400 == 0:
return True
else:
if year % 100 == 0:
return False
else:
if year % 4 == 0:
return True
else:
return False # <-- here!
否则,此函数将在该位置隐式返回None
,这是非真实的,但不是bool
,因此不是int
(bool
是int
的子类,它可以使0-1-index魔法成为可能,可以用作list
索引。顺便说一句,如果else
块中有return
,则不需要if
:
def isLeap(year):
if not year % 400:
return True
if not year % 100:
return False
# return not year % 4 # is also possible here
if not year % 4:
return True
return False # <-- needed to avoid None being returned
这是否更具可读性取决于具体情况。但是在这里,有多个嵌套分支,我认为它有助于保持较低的缩进水平并了解正在发生的事情。