Bottom Page

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?
Quote
#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
Quote
#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
Quote
#4
just to add that continue is not necessary in this case
Quote
#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
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  Com Error with macro within for loop due to creating new workbook in the loop Lastwizzle 0 73 May-18-2019, 09:29 PM
Last Post: Lastwizzle
  syntax error near unexpected token btom529 5 267 Apr-21-2019, 09:03 PM
Last Post: btom529
  Getting an unexpected generator object ? mcgrim 19 424 Mar-29-2019, 11:35 AM
Last Post: gontajones
  Dictionary adds an unexpected list erina 1 188 Mar-14-2019, 01:13 PM
Last Post: ichabod801
  unexpected EOF while parsing whatloop 3 412 Mar-09-2019, 06:59 PM
Last Post: whatloop
  Unexpected round behavior pythonCoder 1 162 Feb-19-2019, 02:39 PM
Last Post: marienbad
  Unexpected expected type error result MartinMaker 1 199 Feb-16-2019, 05:02 PM
Last Post: micseydel
  Question about for loop not creating an infinite loop. FWendeburg 1 224 Feb-03-2019, 08:45 PM
Last Post: ichabod801
  unexpected sub result after overloading operator jolinchewjb 1 241 Jan-24-2019, 08:23 AM
Last Post: buran
  unexpected EOF wowo 3 447 Jan-13-2019, 04:36 AM
Last Post: wowo

Forum Jump:


Users browsing this thread: 1 Guest(s)