为什么这个表达式返回10而我期望它返回15?

2024-04-19 23:59:36 发布

您现在位置:Python中文网/ 问答频道 /正文

在Python控制台中,此代码应返回15,但返回10。 怎么了?你知道吗

print(sum(range(5)))

Tags: 代码rangesumprint
2条回答

因为range是独占的,所以它们不包括您指定的来自the documentation on range objects的最后一个(stop)元素:

For a positive step, the contents of a range r are determined by the formula r[i] = start + step*i where i >= 0and r[i] < stop

省略step默认值为1。你知道吗

你基本上是在总结:

list(range(5))
[0, 1, 2, 3, 4]

很明显,它们的总和是10。你知道吗

在python中

range(5)等价于[0,5)

相关问题 更多 >