TypeError:'noneType'对象不可迭代

时间:2020-02-23 14:43:46  来源:igfitidea点击:

在本教程中,我们将解决问题 TypeError: 'NoneType' object is not iterable

如果我们在类型的对象迭代,则会收到此错误 Nonefor或者 while环形。

让我们通过示例来理解。

countryList =["Netherlands","China","Russia","France"]
for country in countryList:
    print(country)

如果 countryList是类型 None,然后你可以收到这个错误。

让我们看看一个场景,我们可以其中收到此错误。

countryList =["Netherlands","China","Russia","France"]
def getCountryList():
    countryList.append("italy")
 
for country in getCountryList():
    print(country)

运行上面的程序时,我们将得到以下输出:

--------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-51-1558beedb4d8> in <module>
      3     countryList.append("italy")
      4 
----> 5 for country in getCountryList():
      6     print(country)
 
TypeError: 'NoneType' object is not iterable

如果我们注意到,我们忘了返回列表 countryListgetCountryList()这就是我们收到此错误的原因。
要在此特定情况下解决此问题,我们需要返回列表 countryListgetCountryList()并且错误将解决。

countryList =["Netherlands","China","Russia","France"]
def getCountryList():
    countryList.append("Italy")
    return countryList
 
for country in getCountryList():
    print(country,end=' ')

什么是non型?

在Python 2中,none型是类型 None

print(type(None)) #<type 'NoneType'>

在Python 3中,non型是类 None

print(type(None)) #<class 'NoneType'>

处理TypeError:'noneType'对象不可迭代

我们可以通过多种方式处理此问题。

检查对象是否在迭代之前没有

我们可以在迭代之前明确检查对象是否为none。

countryList =["Netherlands","China","Russia","France"]
def getCountryList():
    countryList.append("Italy")
    return countryList
 
if getCountryList() is None:
    print('List is None')
else:
    for country in getCountryList():
        print(country,end=' ')

使用try-except

我们也可以使用 try-except处理 TypeError: 'NoneType' object is not iterable让我们在举例的帮助下看:

countryList =["Netherlands","China","Russia","France"]
def getCountryList():
    countryList.append("Italy")
    return countryList
 
returnedCountryList=getCountryList()
try:
    for country in returnedCountryList:
        print(country,end=' ')
except Exception as e:
    print('returnedCountryList is None')