TypeError:“NoneType”类型的对象没有len()python

时间:2015-05-19 08:48:24

标签: python csv typeerror

我一直收到此错误

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)

3 个答案:

答案 0 :(得分:6)

searchQueryForm如果找不到任何内容,显然会返回None。由于您无法将len应用于None,因此您必须明确检查:

if searchList is None or len(searchList) == 0:

答案 1 :(得分:1)

您想要获取len()的对象显然是None对象。

searchList返回searchQueryForm(myList)

所以这不是None

要么修复该功能,要么认为它可以返回None

if len(searchlist or ()) == 0:

if not searchlist:

答案 2 :(得分:0)

searchQueryForm()函数返回None值和len() in-build函数不接受无类型参数。所以提高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
当代码未进入上一个searchQueryForm()时,if loop函数中缺少

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