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(' ')

转载于:https://www.cnblogs.com/Ruby517/p/5573597.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值