Python Forum
Unexpected ininite loop behavior
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Unexpected ininite loop behavior
#1
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.")
        continue
What's wrong?
Reply
#2
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
Reply
#3
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
Reply
#4
just to add that continue is not necessary in this case
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#5
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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Inconsistent loop iteration behavior JonWayn 2 954 Dec-10-2022, 06:49 AM
Last Post: JonWayn
  Unexpected round behavior pythonCoder 1 2,228 Feb-19-2019, 02:39 PM
Last Post: marienbad
  A little unexpected output from a while loop linuxnoob 3 3,079 Jul-17-2018, 01:02 AM
Last Post: gontajones
  Unexpected input in While Loop fier259 1 2,397 May-07-2018, 12:47 AM
Last Post: woooee
  Unexpected behavior appending to a List of Dictionaries Nomad 2 2,699 Apr-03-2018, 04:22 AM
Last Post: Nomad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020