我无法弄清楚为什么这个while循环没有正常运行

时间:2015-07-07 06:02:12

标签: python

integer1 = eval(input('Enter the first integer between -10 and 10: '))

integer2 = eval(input('Enter the second integer between -10 and 10: '))

while (integer1 >= 10 or integer1 <= -10):
    replace1 = eval(input('Integer 1 is invalid, Please enter a valid number: '))

while (integer2 > 10 or integer2 < -10):
    replace2 = input('Integer2 is invalid, Please enter a valid number: ')

2 个答案:

答案 0 :(得分:1)

我认为这是你的期望:

integer1 = eval(input('Enter the first integer between -10 and 10: '))

integer2 = eval(input('Enter the second integer between -10 and 10: '))

while (integer1 >= 10 or integer1 <= -10):
    integer1 = eval(input('Integer 1 is invalid, Please enter a valid number: '))

while (integer2 > 10 or integer2 < -10):
    integer2 = input('Integer2 is invalid, Please enter a valid number: ')

由于integer1的值在第一次循环中没有改变,因此它将作为无限循环

您可以使用int()代替eval,因为使用eval坚持使用int

会产生一些有害影响

<强>修改:

integer1 = int(input('Enter the first integer between -10 and 10: '))

integer2 = int(input('Enter the second integer between -10 and 10: '))

while (integer1 >= 10 or integer1 <= -10):
    integer1 = int(input('Integer 1 is invalid, Please enter a valid number: '))

while (integer2 > 10 or integer2 < -10):
    integer2 = int(input('Integer2 is invalid, Please enter a valid number: '))

答案 1 :(得分:1)

while (integer1 >= 10 or integer1 <= -10):
    replace1 = eval(input('Integer 1 is invalid, Please enter a valid number: '))

你永远不会改变integer1,所以如果条件为真,那么总是为真,它会永远循环。

分配给integer1而不是replace1。同样适用于第二种。