简体   繁体   English

Python范围-开始==结束时没有迭代?

[英]Python range - No iteration when start == end?

As the title says. 如标题所示。

Tested using: 测试使用:

for x in range (0,0):
        print(str(x))

I am expecting to see "0", but nothing prints. 我希望看到“ 0”,但什么都不会打印。

I'm using Python 3 and was hoping: 我正在使用Python 3,并希望:

 for x in range(x,y)

Would at least get me one iteration when x == y, but it seems that isn't the case... is there a better way I could be doing this rather than manually handling the x == y scenario? 当x == y时,至少可以让我进行一次迭代,但是似乎并非如此……有没有比手动处理x == y场景更好的方法呢?

range is half-inclusive range是半数

range(x, y) includes x and excludes y . range(x, y)包括x不包括y Use range(x, y + 1) instead, so for your example you'd like to use range(0, 1) in your first codeblock. 请改用range(x, y + 1) ,因此对于您的示例,您想在第一个代码块中使用range(0, 1)

As by the documentation of range , range will return the largest start + i * step less than stop. 根据range文档 ,range将返回最大的start + i * step小于停止的start + i * step As 0 + step can never be less than 0, it will return an empty list. 由于0 + step永远不能小于0,它将返回一个空列表。 In your case you would want to use range(x, y + 1) . 在您的情况下,您想使用range(x, y + 1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM