有人能帮我弄清楚为什么这个循环是无限的吗?我所在的类会根据最后两行自动为我输入变量。它以数字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)
将
N = N + 1
缩进循环之外,否则它永远无法添加或者更好地使用
N += 1
:第一:习惯于测试你的代码。因为有涉及数字1和4的条件,所以应该测试小于1和大于4的数字,以查看超出这些边的情况。果然,输入5会产生一个无限循环:
为什么会这样
user_cycles == 5
因此循环直到N == 6
(或任何大于5的值)才会停止当
N == 5
时会发生什么情况?我们打印“太多”,然后继续循环,而不再次增加N。因此循环将始终停留在N=5请注意,使用这些值进行测试还表明,我们从未达到
Too few
条件这是死代码!不可能达到此条件,因为N
始终从1开始,并且从不减少修复无限循环的方法取决于所需的行为。只要N超过4,您就可以
break
该循环:另一个选项是确保N始终递增,方法是在该条件块内递增N,或者在整个
if...elif...else
语句外递增N,而不是在else
内递增N(该语句只对1到4之间的值运行)相关问题 更多 >
编程相关推荐