我在下面创建了这个while循环,但是当它应该打印两次时它只打印一次“嘿”,请帮助:
count = 6
item = 3
while count - item > 0:
print count
count -= item
print count
if count == 0:
print "hey"
一开始,计数是 6,然后是 3,但它永远不会变为 0
我在下面创建了这个while循环,但是当它应该打印两次时它只打印一次“嘿”,请帮助:
count = 6
item = 3
while count - item > 0:
print count
count -= item
print count
if count == 0:
print "hey"
一开始,计数是 6,然后是 3,但它永远不会变为 0
应该是?
让我们分析一下代码流程。最初设置为count
:item
count = 6; item = 3
count - item
所以这意味着3
我们进入循环。在循环中我们更新count
为3
,所以:
count = 3; item = 3
所以这意味着你打印count - item
which is 0
,但count
它本身 is 3
,所以if
语句失败,我们根本不打印"hey"
。
现在while
循环检查是否count - item > 0
不再是这种情况,所以它停止了。
在这里打印两次的最小修复"hey"
是:
count - item >= 0
; 和"hey"
,无论值count
是什么,例如:count = 6
item = 3
while count - item >= 0:
count -= item
print "hey"
你是什么意思?"hey"
应该只打印一次。
我想你的意思是
count = 6
item = 3
while count > 0:
count -= item
print count - item
if count == 0:
print "hey"
在您的情况下,它正在检查是否count-item
大于 0。