[英]python error “list indices must be integers not Nonetype”
I am new to python and learning the language from Udacity. 我是python的新手,正在从Udacity学习语言。 I wanted to write a python program that takes 2 dates and outputs the day difference between these 2 dates, assuming the second date is latter. 我想编写一个python程序,该程序需要2个日期,并假设第二个日期是后者,然后输出这2个日期之间的日期差。
It throws an error saying that: 它抛出一个错误,说:
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)
Here is the code: 这是代码:
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
You are missing a return
in your is_leap
function: 您在is_leap
函数中缺少return
值:
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!
Otherwise, this function will implicitly return None
in that place, which is non-truthy, but not a bool
, and therefore not an int
( bool
is a subclass of int
, which makes the 0-1-index magic possible in the first place) that can be used as a list
index. 否则,此函数将在该位置隐式返回None
,它不是真实的,但不是bool
,因此也不是int
( bool
是int
的子类,这使得0-1索引魔术首先可能),可以用作list
索引。 Btw, you do not need the else
if there is a return
in the if
block: 顺便说一句, if
块中有return
, if
不需要else
:
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
Whether this is more readable very often depends on the concrete circumstances. 这是否更具可读性通常取决于具体情况。 But here, with multiple nested branches, I think it helps keeping the indentation levels low and understanding what is happening. 但是在这里,有多个嵌套分支,我认为这有助于将缩进级别保持在较低水平并了解正在发生的情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.