简体   繁体   English

python中while循环的停止点

[英]The stopping point in while loop in python

i=0
>>> while i<3:
...     print i
...     i += 1
... else:
...     print ‘Done with i =’, i
...
0
1
2
Done with i = 3

Hi all, I am wondering why the while loop is done when i=3, not when i=2. 大家好,我想知道为什么在i = 3而不是i = 2时执行while循环。 When i=2, i=i+1=2+1=3, the expression becomes False, then execution gets finished. 当i = 2,i = i + 1 = 2 + 1 = 3时,表达式变为False,然后执行完成。 Isn't that right? 是不是?

The else in a while ... else block always executes. 一段while ... elseelse while ... else块始终执行。 So your while loop ends with i == 2 , but then you increment with i += 1 , so i == 3 . 因此,您的while循环以i == 2结尾,但随后以i += 1递增,所以i == 3 Then your while loop quits, and you perform the else block. 然后退出while循环,然后执行else块。

That else block will always execute. else块将始终执行。 It's the same as simply writing print "Done with i =", i . 这与只写print "Done with i =", i As BlivetWidget said, you are adding 1 to i and then executing the else block. 正如BlivetWidget所说,您要向i加1,然后执行else块。 Instead, you could use print "Done with i = ", i-1 . 相反,您可以使用print "Done with i = ", i-1

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

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