NoneType错误,Python

时间:2013-09-10 21:49:16

标签: python return iterable nonetype

我正在

TypeError: 'NoneType' object is not iterable 

在这一行:

temp, function = findNext(function) 

并且不知道为什么会失败。我在while循环中使用函数:

while 0 < len(function):
    …

但我没有迭代它。 findNext(function)中的所有回报都非常

return 'somestring',function[1:]

并且无法理解为什么它认为我正在迭代其中一个对象。

2 个答案:

答案 0 :(得分:1)

我猜测findNext在没有返回任何内容的情况下失败,这使得它自动返回None。有点像这样:

>>> def findNext(function):
...     if function == 'y':
...         return 'somestring',function[1:]
...
>>> function = 'x'
>>> print(findNext(function))
None
>>> temp, function = findNext(function)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not iterable

解决方案是永远返回一些东西。

答案 1 :(得分:0)

声明:

return 'somestring',function[1:]

实际上是返回长度为2的元组,元组是可迭代的。将该陈述写成:

更为惯用
return ('somestring', function[1:])

这使得它的元组性质更加明显。

相关问题