鱼C论坛

 找回密码
 立即注册
查看: 2840|回复: 6

这个sum很诡异

[复制链接]
发表于 2014-6-15 22:46:43 | 显示全部楼层 |阅读模式
10鱼币
  1. def sum(x):
  2.     result = 0
  3.     for each in x:
  4.         if(type(each)==int) or (type(each)== float):
  5.             result += each
  6.         else:
  7.             continue
  8.         return result
  9. print(sum([1,2,3,'4',5,'a',9,True]))   
复制代码
何解运行结果等1而不是20??
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2014-6-15 22:46:44 | 显示全部楼层
  1. def sum(x):
  2.     result = 0
  3.     for each in x:
  4.         if(type(each)==int) or (type(each)== float):
  5.             result += each
  6.         else:
  7.             continue
  8.         return result #此处缩进错误
  9. print(sum([1,2,3,'4',5,'a',9,True]))   
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2014-6-15 23:41:09 | 显示全部楼层
  1. def sum(x):
  2.     result = 0
  3.     for each in x:
  4.         if(type(each)==int) or (type(each)== float):
  5.             result += each
  6.     return result
  7. print(sum([1,2,3,'4',5,'a',9,True]))   
复制代码
如果只是把浮点数和整数相加,可以按照上面的代码,else: continus 会结束循环

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2014-6-16 10:11:49 | 显示全部楼层
本帖最后由 晓强在哪里 于 2014-6-16 10:15 编辑
  1. def sum(x):    result = 0    for each in x:        if(type(each)==int) or (type(each)== float):            result += each        else:            continue        return resultprint(sum([1,2,3,'4',5,'a',9,True]))   
复制代码

这个排版怎么回事?看下面的回答↓↓↓↓↓↓↓↓↓
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2014-6-17 17:56:38 | 显示全部楼层
{:1_1:}逗号表达式
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2014-6-18 00:38:30 | 显示全部楼层
来看一下,有鱼币吗?我发现一个问题,为什么用isinstance()判断后,会得出 21 的结果,你们试过了吗?我猜测,可能True是isinstance允许的数字‘1’。你们觉得呢?
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2014-6-18 23:00:58 | 显示全部楼层

续)这个sum很诡异
http://bbs.fishc.com/thread-48555-1-1.html

已重新发贴,有劳指点一二,感谢感谢
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-3-29 15:09

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表