I'm stuck writing some code for an intro programming class. I'm pretty sure the mistake is probably that I mixed integers with strings trying to get a result, but I'm just not sure which code I need to replace after messing with it all day and getting many different traceback errors trying different options. Suggestions would be fantastic. I have read the documentation on strings that comes with python, and tried to find a reference to this error and how to work around it in my textbook. Anyway, here's the code with the traceback included at the bottom.

#milesPerGallon.py
#a program to compute fuel efficiency in a multi-leg journey.
#prompt for starting odometer reading, and give reading after each leg of journey
#blank line from user to stop entering data and get final reseult
#odom and gallons used must be >1, odometer reading and gallons used should
#be entered by user seperated by a space
#print out mpg for each leg and total avg mpg

def main():

    odom1 = int(input("Please enter a starting value for the odometer: "))
    odom2 = 0
    tripmiles = 0
    miles = 0
    gallons = 0
    tripgallons = 0



    while True:  
        odom2, gallons = int(input("\nPlease enter odometer reading and gallons used (odometer gallons) [Enter if done]: "))
        while odom2 and gallons != "":

            if odom2 >1 and gallons > 1:
                miles = odom2 - odom1
                odom1 = odom2
                tripmiles = tripmiles + miles
                tripgallons = tripgallons + gallons
                print("MPG for this leg: ", miles / gallons)

            else:
                print("\nMiles and gallons must be a positive number greater than 1, seperated by a single space.\n")

        print("Your total average miles per gallon: ", tripmiles / tripgallons)

main()


##>>> ================================ RESTART ================================
##>>> 
##Please enter a starting value for the odometer: 100000
##
##Please enter odometer reading and gallons used (odometer gallons) [Enter if done]: 100500 10
##Traceback (most recent call last):
##  File "C:/Users/Dad/Documents/Python Programming/milesPerGallon.py", line 35, in <module>
##    main()
##  File "C:/Users/Dad/Documents/Python Programming/milesPerGallon.py", line 20, in main
##    odom2, gallons = int(input("\nPlease enter odometer reading and gallons used (odometer gallons) [Enter if done]: "))
##ValueError: invalid literal for int() with base 10: '100500 10'
  1. ask for each value separately. Otherwise "Enter if done" returns a "need 2 values to unpack" error.
  2. you can do something like what is in your program but it returns a string

       odom2, gallons = input("\nPlease enter odometer reading and gallons used (odometer gallons) [Enter if done]: ").split()
        print odom2, type(odom2), gallons, type(gallons)
    
  3. this works but seems very cumbersome

    odom2, gallons = (int(x) for x in raw_input("\nPlease enter odometer reading and gallons used (odometer gallons) [Enter if done]: ").split())
    print odom2, type(odom2), gallons, type(gallons)
    

Thanks, that gave me some ideas. It gets the values into the expressions and the math is good... now just need to figure out why my loop repeats without going back up to ask for the next value. Darn.

def main():

    odom1 = int(input("Please enter a starting value for the odometer: "))
    odom2 = 0
    tripmiles = 0
    miles = 0
    gallons = 0
    tripgallons = 0

    while True:

        odom2, gallons = (int(x) for x in input("\nPlease enter odometer reading and gallons used (odometer gallons) [Enter if done]: ").split())
        print (odom2, type(odom2), gallons, type(gallons))

        while odom2 and gallons != "":

                if odom2 >1 and gallons > 1:
                    miles = odom2 - odom1
                    odom1 = odom2
                    tripmiles = tripmiles + miles
                    tripgallons = tripgallons + gallons
                    print("MPG for this leg: ", miles / gallons)
                    print("Enter next value or press enter if done.")

                else:
                    print("\nMiles and gallons must be a positive number greater than 1, seperated by a single space.\n")

        print("Your total average miles per gallon: ", tripmiles / tripgallons)

    print()

main()

Still working on this. Figured out the loop problem partially, but I can't seem to get it to exit out to the total trip calculations unless I enter 0 0 for the values of odom2 and gallons. I need that to be a blank string (hitting enter) to exit the loop. I added some formatting to make the MPG display a little nicer. Where did I go wrong? I would have thought "while odom2 or gallons == True:" should have exited on an empty string. Still really new at this, been looking at it all day, missing something obvious to someone who knows what they are doing I bet. Thanks for any help in advance.

Here's the updated code and traceback.

#milesPerGallon.py
#a program to compute fuel efficiency in a multi-leg journey.
#prompt for starting odometer reading, and give reading after each leg of journey
#blank line from user to stop entering data and get final reseult
#odom and gallons used must be >1, odometer reading and gallons used should
#be entered by user seperated by a space
#print out mpg for each leg and total avg mpg

def main():

    odom1 = int(input("Please enter a starting value for the odometer: "))
    odom2 = 0
    tripmiles = 0
    miles = 0
    gallons = 0
    tripgallons = 0

    while True:
        odom2, gallons = (int(x) for x in input("\nPlease enter odometer reading and gallons used (odometer gallons) [Enter if done]: ").split())
        print (odom2, type(odom2), gallons, type(gallons))

        while odom2 or gallons == True:

            if odom2 >1  and gallons >1:
               miles = odom2 - odom1
               odom1 = odom2
               tripmiles = tripmiles + miles
               tripgallons = tripgallons + gallons
               print("MPG for this leg: {0:0.2f}".format(miles / gallons))
               odom2, gallons = (int(x) for x in input("\nPlease enter odometer reading and gallons used (odometer gallons) [Enter if done]: ").split())
               print (odom2, type(odom2), gallons, type(gallons))

            else:
                print("\nMiles and gallons must be a positive number greater than 1, separated by a single space.\n")

        print("Your total average miles per gallon: {0:0.2f}".format(tripmiles / tripgallons))

    print()

main()


##>>> ================================ RESTART ================================
##>>> 
##Please enter a starting value for the odometer: 22
##
##Please enter odometer reading and gallons used (odometer gallons) [Enter if done]: 333 4
##333 <class 'int'> 4 <class 'int'>
##MPG for this leg: 77.75
##
##Please enter odometer reading and gallons used (odometer gallons) [Enter if done]: 5555 86
##5555 <class 'int'> 86 <class 'int'>
##MPG for this leg: 60.72
##
##Please enter odometer reading and gallons used (odometer gallons) [Enter if done]: 
##Traceback (most recent call last):
##  File "C:\Users\Dad\Documents\Python Programming\milesPerGallon.py", line 40, in <module>
##    main()
##  File "C:\Users\Dad\Documents\Python Programming\milesPerGallon.py", line 30, in main
##    odom2, gallons = (int(x) for x in input("\nPlease enter odometer reading and gallons used (odometer gallons) [Enter if done]: ").split())
##ValueError: need more than 0 values to unpack

Last go at it for the night. This code actually hits all the requirements of the assignment but it's not what I want. Please see comments in the code. I'd love to hear ideas on how to do this properly.

#milesPerGallon.py
#a program to compute fuel efficiency in a multi-leg journey.
#prompt for starting odometer reading, and give reading after each leg of journey
#blank line from user to stop entering data
#odom and gallons used must be >1, odometer reading and gallons used should
#be entered by user seperated by a space
#print out mpg for each leg and total avg mpg

def main():

    tripmiles = 0
    miles = 0
    gallons = 0
    tripgallons = 0
    odom2 = 0
    odom1 = int(input("Please enter a starting value for the odometer: "))

    if odom1 <= 1:
        print("Odometer reading must be greater than 1.")
        main()
    else:
        print("Thank you, now let's calculate your trip.")
        print("Remember, enter odometer reading first and then gas used(in gallons) with only a space between the two values!")

        try:    
            while odom1 > 0:
                odom2, gallons = (int(x) for x in input("\nPlease enter odometer reading and gallons used (odometer gallons) [Enter if done]: ").split())

                if odom2 > 1  and gallons > 1:
                   miles = odom2 - odom1
                   odom1 = odom2
                   tripmiles = tripmiles + miles
                   tripgallons = tripgallons + gallons
                   print("MPG for this leg: {0:0.2f}".format(miles / gallons))
                   print("Your total average miles per gallon: {0:0.2f}".format(tripmiles / tripgallons))

                else:
                    print("\nMiles and gallons must be greater than 1, separated by a single space.\n")

#this next print statement never gets used since I can't seem to get this while loop to exit properly
#the workaround was to use the try/except to have the ValueError perform the exit and I moved the total averages inside the loop
#This works but it's not what I intended or want to have happen                

            print("Your total average miles per gallon: {0:0.2f}".format(tripmiles / tripgallons))

        except ValueError:
            print("\nThanks for using milesPerGallon, see you next trip! \n")
main()

Recursively calling the main() function (lines 16 to 21) if the input is incorrect it's not good at all. An easy fix would be this:

odom2 = odom1 = 0
while (odom1<=1):
    odom1 = int(input("Please enter a starting value for the odometer: "))
    if odom1 <= 1:
        print("Odometer reading must be greater than 1.")

Thanks for the tip, that's much better.

Still looking for ideas on the bottom while loop to get it to exit properly if user just hits enter/sends empty string. I think my issue is in comparing the user input [empty string] to the expected while odom1 > 0:, but if I recall yesterday's attempts correctly(was a long night) I originally went to int values because of different errors. I'll be mucking around with it today and looking at more documentation. I need a while statement that will exit that loop correctly on user input of just hitting enter.

You can get around the "Enter problem" by catching the input as a tuple and testing for length.

lit="\nPlease enter odometer reading and gallons used (odometer gallons) [Enter if done]: "
ret_tuple=input(lit).split()
if len(ret_tuple) > 1:
    odom = int(ret_tuple[0])  
    gallons = int(ret_tuple[1])
    print odom, gallons

## test while loop input with exit="Enter"
repeat="0" 
while len(repeat):
    repeat=input() ## can be string or tuple as long as it has a len()
    print repeat
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.