PythonでTypeError:'NoneType'object is not iterable

959 ワード

例:
def contain():
        score = 4    
        if score in num:                                          
            return True,score;
        
num = [1,2,3,0]
iscontain,score = contain()  
print iscontain,score
結果:
>>> 

Traceback (most recent call last):
  File "D:\Program Files\python\chengxu\temp.py", line 8, in 
    iscontain,score = contain()
TypeError: 'NoneType' object is not iterable
>>> 

説明:if条件のみで複数の変数が返される場合、if条件が満たされないと例外が発生します.
解決策:else文を付ける
def contain():
        score = 4    
        if score in num:                                          
            return True,score;
        else:
            return False,score;
num = [1,2,3,0]
iscontain,score = contain()  
print iscontain,score
結果:
>>> 
False 4

参考記事:
http://blog.csdn.net/dataspark/article/details/9953225