0

In this small program I have created, I want the program to loop an input until a positive integer is entered. Different outputs are printed when I enter a positive and a negative number, which is what I want. However, when I enter a negative number twice, the loop will break.

For example when I enter -6 once, it will print 'Your distance input is not positive, please enter the distance between the two sensors, in meters'. But when I enter another negative number like -6 or -75, the program continues instead of looping.

I don't know why this happens and I just want answers or feedbacks on why this happens. Please feel free to alter my code so it loops until a positive number is entered.

Here is my program.

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')
3
  • Let me know if my answer is what you're looking for. Commented Mar 4, 2015 at 19:14
  • If you find my answer suitable, you can close the question with the check-mark beside my answer. Commented Mar 4, 2015 at 19:17
  • Right. Glad I could help :) Commented Mar 4, 2015 at 19:25

1 Answer 1

1

Your program does not loop because your while loop breaks when you input a negative number. The only input which will continue your loop is 0. Perhaps you want something like this instead :

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.