Python中的无限循环帮助

2024-10-02 02:35:23 发布

您现在位置:Python中文网/ 问答频道 /正文

有人能帮我弄清楚为什么这个循环是无限的吗?我所在的类会根据最后两行自动为我输入变量。它以数字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)

Tags: 代码ifdef数字建议tooprint漏洞
2条回答

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)

第一:习惯于测试你的代码。因为有涉及数字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时会发生什么情况?我们打印“太多”,然后继续循环,而不再次增加N。因此循环将始终停留在N=5

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

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

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

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

相关问题 更多 >

    热门问题