计算这个 1 到 100 之和的代码为什么会出错?

2017-07-25 15:03:09 +08:00
 Kung815

sum = 0 for x in range(101): sum = sum + x print(sum)

报错说 invalid syntax 如果将 print 缩进, 则是将每次和都返回, 不是我想要的结果。 所以请问怎么只返回 5050

5438 次点击
所在节点    Python
27 条回复
SuT2i
2017-07-26 08:20:24 +08:00
@Xs0ul 17 楼说的对 解释器中 循环体结束后 才能继续敲语句 (双击回车,再 print )
araraloren
2017-07-26 08:56:46 +08:00
。。。唉 垃圾 python 用个 REPL 也要注意空格。。
wizardoz
2017-07-26 09:28:51 +08:00
from functools import reduce

sum = reduce(lambda a,b: a + b, range(100))
zhangsen1992
2017-07-26 09:46:36 +08:00
sum(range(1,101))
jsoncai
2017-07-26 09:48:50 +08:00
因为没有用游标卡尺
helloSwift
2017-07-26 09:53:37 +08:00
@Kung815

11 楼说的对,留空行


@yangzzcc

Atom 编辑器,
主题 one dark, atom 自带的,终端我用这个 https://github.com/nathanbuchar/atom-one-dark-terminal
字体 Source Code Pro-Light 13 , https://github.com/adobe-fonts/source-code-pro


@ikeeper

是 atom
直接写的,没啥特别配置 😂
jerryshao
2017-07-26 21:21:46 +08:00
你新加的那个图...
`for x in number(range(101))` 里面这 number 是哪来的?

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/377827

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX