def语句常见错误

自觉不才,使用def语句时容易出现以下错误,

参考: 习题—25

http://www.2cto.com/shouce/Pythonbbf/ex25.html

def add():

    print "A true man does what he will, not what he must!"

 

add()                # 输出print过的内容

a = add()         # 同上

print add()       # 输出print过的内容和return过的值

print a             # 输出return过的值,没有则输出None

a                    # 仅作为变量存在,无输出

 

---------------------------------------------------------------------

摘自习题—25

 

def break_words(words):          # def: (define)定义函数

    print words.split(' ')              # 记得 '  ' 要有空格,不然提示出错信息:

                                                  ValueError: empty  separator(分隔符)

def sort_words(words):

    print sorted(words)

 

txt = "A true man does what he will, not what he must!"

list = break_words(txt)

sort_words(list)

ValueError: 'NoneType' object is not iterable(迭代)

 

偶觉得这是一个经典的错误,因为NoneType表示变量的值是空的。而上面说

过的return,返回的是值。所以应该这样改。就是因为是print而不是return,

返回值,所以才会出现NoneType,(返回的值是空)这种情况。

def break_words(words)

    return words.split(' ')

或者把list = break_words(txt) 改为 list = txt.split(' ')

posted @ 2016-06-10 13:43  坏小孩D_R  阅读(634)  评论(0编辑  收藏  举报