我一直得到这个错误
TypeError: object of type 'NoneType' has no len()
下面是代码:
def main():
myList = [ ]
myList = read_csv()
## myList = showList(myList)
searchList = searchQueryForm(myList)
if len(searchList) == 0:
print("I have nothing to print")
else:
showList(searchList)
searchQueryForm
显然返回一个None
,如果它没有找到。由于不能将len
应用于None
,因此必须显式检查:
if searchList is None or len(searchList) == 0:
您想要从中获得len()
的对象显然是None
对象。
从searchQueryForm(myList)
返回searchList
所以这是None
,当它不应该。
要么修复这个函数,要么接受它可以返回None
:
if len(searchlist or ()) == 0:
或
if not searchlist:
searchQueryForm()
函数返回None
值,len()
内置函数不接受None类型参数。因此引发TypeError
异常。
:
>>> searchList = None
>>> print type(searchList)
<type 'NoneType'>
>>> len(searchList)
Traceback (most recent call last):
File "<console>", line 1, in <module>
TypeError: object of type 'NoneType' has no len()
在if循环中增加一个条件来检查searchList
是否为None
:
>>> if searchList==None or len(searchList) == 0:
... print "nNothing"
...
nNothing
当代码没有进入最后一个if loop
时,searchQueryForm()
函数中缺少return语句。默认的 None
值是在没有从函数返回任何特定值时返回的。
def searchQueryForm(alist):
noforms = int(input(" how many forms do you want to search for? "))
for i in range(noforms):
searchQuery = [ ]
nofound = 0 ## no found set at 0
formname = input("pls enter a formname >> ") ## asks user for formname
formname = formname.lower() ## converts to lower case
for row in alist:
if row[1].lower() == formname: ## formname appears in row2
searchQuery.append(row) ## appends results
nofound = nofound + 1 ## increments variable
if nofound == 0:
print("there were no matches")
return searchQuery
return []
# ^^^^^^^ This was missing