简体   繁体   中英

TypeError: object of type 'NoneType' has no len() python

I keep getting this error

TypeError: object of type 'NoneType' has no len()

here is the code:

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 apparently returns a None if it finds nothing. Since you can't apply len to None , you'll have to check for that explicitly:

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

The object which you want to get the len() from is obviously a None object.

It is the searchList , returned from searchQueryForm(myList) .

So this is None when it shouldn't be.

Either fix that function or live with the fact that it can return None :

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

or

if not searchlist:

The searchQueryForm() function return None value and len() in-build function not accept None type argument. So Raise TypeError exception.

Demo :

>>> 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()

Add one more condition in if loop to check searchList is None or not

Demo :

>>> if searchList==None or len(searchList) == 0:
...   print "nNothing"
... 
nNothing

return statement is missing in the searchQueryForm() function when code is not go into last if loop . By default None value is return when we not return any specific value from function.

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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM