簡體   English   中英

TypeError:類型為'NoneType'的對象沒有len()python

[英]TypeError: object of type 'NoneType' has no 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對象。

這是searchList ,從返回searchQueryForm(myList)

因此,當它不應該是時為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 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM