Unexpected ininite loop behavior - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Unexpected ininite loop behavior (/thread-15680.html) |
Unexpected ininite loop behavior - RedSkeleton007 - Jan-27-2019 Hi, I'm trying to code a basic while True loop, but I get an infinite loop whether or not I use the continue statement (after I purposely enter invalid data to test the loop): #!/usr/bin/env python3 print("Welcome to the Miles Per Gallon Program.") print() milesDriven = float(input("Enter miles driven: ")) gallonsUsed = float(input("Enter the number of gallons used: ")) while True: if milesDriven > 0 and gallonsUsed > 0: mpg = round((milesDriven / gallonsUsed),2) print("Miles Per Soul... uh... Gallon: ",mpg) break else: print("Both entries must be greater than 0. Please Try again.") continueWhat's wrong? RE: Unexpected ininite loop behavior - Larz60+ - Jan-27-2019 while True is by default infinite and since your input statements are outside of the loop, you have no way of satisfying the break condition if it isn't true upon entry. You need to move the inputs to inside of while loop RE: Unexpected ininite loop behavior - RedSkeleton007 - Jan-27-2019 Thanks for the quick response. It works now: #!/usr/bin/env python3 print("Welcome to the Miles Per Gallon Program.") print() while True: milesDriven = float(input("Enter miles driven: ")) gallonsUsed = float(input("Enter the number of gallons used: ")) if milesDriven > 0 and gallonsUsed > 0: mpg = round((milesDriven / gallonsUsed),2) print("Miles Per Soul... uh... Gallon: ",mpg) break else: print("Both entries must be greater than 0. Please Try again.") continue RE: Unexpected ininite loop behavior - buran - Jan-27-2019 just to add that continue is not necessary in this case
RE: Unexpected ininite loop behavior - aakashjha001 - Jan-27-2019 while (True) is infinite by default. The value of the 2 variables are outside the loop and if you enter the values less than 0,it goes into an infinite loop |