TypeError: 类型为 'NoneType' 的对象没有 len() python



我一直得到这个错误

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 

最新更新