首页 > 解决方案 > 我的 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

标签: pythonpython-3.xwhile-loop

解决方案


应该是?

让我们分析一下代码流程。最初设置为countitem

count = 6; item = 3

count - item所以这意味着3我们进入循环。在循环中我们更新count3,所以:

count = 3; item = 3

所以这意味着你打印count - itemwhich is 0,但count它本身 is 3,所以if语句失败,我们根本打印"hey"

现在while循环检查是否count - item > 0不再是这种情况,所以它停止了。

在这里打印两次的最小修复"hey"是:

  1. 将 while 循环中的检查设置为count - item >= 0; 和
  2. 在循环中打印"hey",无论值count是什么,例如:


count = 6
item = 3

while count - item >= 0:
    count -= item
    print "hey"

推荐阅读