python - 我的 while 函数无法正常工作 PYTHON,我不知道出了什么问题
问题描述
我在下面创建了这个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"
是:
- 将 while 循环中的检查设置为
count - item >= 0
; 和 - 在循环中打印
"hey"
,无论值count
是什么,例如:
count = 6
item = 3
while count - item >= 0:
count -= item
print "hey"