首页 文章

我的功能不起作用PYTHON,我不知道出了什么问题

提问于
浏览
-2

我在下面创建了这个循环,但它只打印“嘿”一次应该打印两次,请帮助:

count = 6
item = 3

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

在开始时,计数是6,然后是3,但它永远不会达到0

2 回答

  • 0

    你什么意思? "hey" 应该只打印一次 .

    我想你的意思是

    count = 6
    item = 3
    
    while count > 0:
        count -= item
        print count - item
        if count == 0:
            print "hey"
    

    在您的情况下,它正在检查 count-item 是否大于0 .

  • 0

    应该是?

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

    count = 6; item = 3
    

    所以这意味着 count - item3 所以我们进入循环 . 在循环中,我们将 count 更新为 3 ,因此:

    count = 3; item = 3
    

    所以这意味着你打印 count - item ,这是 0 ,但 count 本身是 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"
    

相关问题