【问题标题】:Infinite Loop help in PythonPython 中的无限循环帮助
【发布时间】:2021-11-20 02:08:17
【问题描述】:

谁能帮我弄清楚为什么这个循环是无限的?我所在的班级会根据最后两行自动为我输入变量。它通过了数字 2 和 4 的测试。但是,还有另一个输入,我看不到,它保持它作为无限循环运行。我无法弄清楚这段代码中允许无限循环的差距在哪里。有什么建议吗?

def shampoo_instructions(user_cycles):
    N = 1
    while N <= user_cycles:
        if N < 1:
            print('Too few')
        elif N > 4:
            print('Too many')
        else:
            print(N,': Lather and rinse.')
            N = N + 1
    print('Done.')
                
user_cycles = int(input())
shampoo_instructions(user_cycles)

【问题讨论】:

  • 缩进都搞砸了。据我所知(如果我对如何修复缩进进行了一些猜测),如果您给它提供除 1 以外的任何值,该函数将立即退出,这让我认为这不是您实际运行的代码。
  • 欢迎来到 SO。请修正你的缩进。
  • 我添加了更新的缩进。对不起。 @ewong
  • 我添加了更新的缩进。对不起。 @Samwise
  • 用您自己的话来说,N = N + 1 的发生必须满足哪些条件?用您自己的话来说,如果那没有发生,那么N &lt;= user_cycles 的结果为什么要改变呢?如果 that 没有发生,为什么循环会结束?

标签: python loops while-loop infinite


【解决方案1】:

缩进 N = N + 1 退出循环,否则永远无法添加。

或者更好地使用N += 1:

def shampoo_instructions(user_cycles):
    N = 1
    while N <= user_cycles:
        if N < 1:
            print('Too few')
        elif N > 4:
            print('Too many')
        else:
            print(N,': Lather and rinse.')
        N = N + 1
    print('Done.')
                
user_cycles = int(input())
shampoo_instructions(user_cycles)

【讨论】:

    【解决方案2】:

    首先:习惯于测试你的代码。由于您有涉及数字 1 和 4 的条件,因此您应该测试小于 1 和大于 4 的数字以查看超出这些边的情况。果然,输入 5 会产生无限循环:

    0
    Done.
    1
    1 : Lather and rinse.
    Done.
    4
    1 : Lather and rinse.
    2 : Lather and rinse.
    3 : Lather and rinse.
    4 : Lather and rinse.
    Done.
    5
    1 : Lather and rinse.
    2 : Lather and rinse.
    3 : Lather and rinse.
    4 : Lather and rinse.
    Too many
    Too many
    Too many
    Too many
    Too many
    Too many
    

    为什么会这样? user_cycles == 5 所以循环不会停止直到N == 6(或任何大于 5 的值。

    N == 5 时会发生什么?我们打印“Too many”,然后继续循环不再增加 N。因此,循环将始终卡在 N = 5。

    请注意,使用这些值进行测试还表明我们从未遇到过Too few 条件——这是死代码!永远不可能达到这个条件,因为N 总是从 1 开始并且永远不会减少。

    修复无限循环的方法取决于所需的行为。只要 N 超过 4,您就可以 break 循环:

            elif N > 4:
                print('Too many')
                break
    

    另一种选择是确保 N 始终递增,方法是在该条件块内递增它,或者在整个 if...elif...else 语句之外而不是在 else 内递增它(它只运行 1 之间的值和 4)。

    【讨论】:

    • 非常感谢您的详细解释!为了便于理解,这正是我需要的措辞。非常感谢您的帮助!这帮助我看到我也没有为变量 user_cycles 设置限制,这是生成输入的地方。再次感谢您!
    猜你喜欢
    • 2011-10-27
    • 2021-05-31
    • 1970-01-01
    • 2011-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-21
    相关资源
    最近更新 更多