首页 文章

程序不会多次循环输入(Python 3.3)

提问于
浏览
0

在我创建的这个小程序中,我希望程序循环输入直到输入正整数 . 输入正数和负数时会打印不同的输出,这就是我想要的 . 但是,当我输入两次负数时,循环将会中断 .

例如,当我输入-6一次时,它将打印'您的距离输入不是正数,请输入两个传感器之间的距离,以米为单位' . 但是当我输入另一个负数,如-6或-75时,程序继续而不是循环 .

我不知道为什么会发生这种情况,我只想答复或反馈为什么会这样 . 请随意更改我的代码,使其循环,直到输入正数 .

这是我的计划 .

distance = (0)

while distance == 0:
   distance = int(input('Distance between the two sensors, in meters \n'))
   if distance > 0:
      print ('Your distance is', distance)
   else:
            distance = int(input('Your distance input is not positive, please enter the distance between the two sensors, in meters \n'))

print ('This will only print after the loop')

1 回答

  • 1

    您的程序不会循环,因为输入负数时 while 循环会中断 . 继续你的循环的唯一输入是0.也许你想要这样的东西:

    distance = int(input('Distance between the two sensors, in meters \n'))
    while distance <= 0:
        distance = int(input('Your distance input is not positive, please'
                ' enter the distance between the two sensors, in meters\n'))
    print ('Your distance is', distance)
    

相关问题