码迷,mamicode.com
首页 > 其他好文 > 详细

def语句常见错误

时间:2016-06-10 14:52:41      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:

自觉不才,使用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(‘ ‘)

def语句常见错误

标签:

原文地址:http://www.cnblogs.com/Ruby517/p/5573597.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!