1. Write a python program that computes the fuel efficiency of a multi-leg journ
ID: 3766844 • Letter: 1
Question
1. Write a python program that computes the fuel efficiency of a multi-leg journey. The program will first prompt for the starting odometer reading and then get information about a series of legs. For each leg, the user enters the current odometer reading and the amount of gas used (separated by a space). The user signals the end of the trip with a blank line. The program should print out the miles per gallon achieved on each leg and the total MPG for the trip.
2. Modify the program to get its input from a file.
Note: 1 and 2 are combined into one program.
Explanation / Answer
def main():
print('Multi-leg Journey's fuel efficiency calculator. ')
try:
# Get starting point of odometer
# No data validate since you need to check possible of Empty String enter
while True:
oStart = input('What's status of starting odometer: ')
if oStart == '': oStart = 0
# THIS GO ERROR IF ITS NOT STRING NUMBER!!
oStart = float(oStart)
if oStart < 0:
print('Error, correct your odometer. ')
else:
break
# keep oStart to calculate Total MPG for all trip
oLast = oStart
gLast = 0
legCount = 1
legMPG = []
# Now collect all detail of each leg
# Sentinel Loop pattern
raw = input(' Leg #{}, What's odometer status now? and how much gas been used?
Please separate each data by space [Odometer Gas]:'.format(legCount))
while raw !='':
oTotal,gTotal = raw.split()
oTotal = float(oTotal)
gTotal = float(gTotal)
legMPG.append(round((oTotal-oLast)/(gTotal-gLast),1))
oLast = oTotal
gLast = gTotal
legCount = legCount+1
raw = input(' Leg #{}, What's odometer status now? and how much gas been used?
Please separate each data by space [Odometer Gas]:'.format(legCount))
if legCount > 1:
print(' Your fuel efficiency are:')
# at this point legCount must be at least 1
for i in range(legCount-1):
print('Leg#{} has {} MPG.'.format(i+1,legMPG[i]))
#when trip end calculate total MpG of whole trip
print(' Your total MPG is',round((oTotal-oStart)/gTotal,2))
else:
print(' No result.')
except ValueError:
print(' Please correct your input.')
except:
print(' Unknow Error! Please try again.')
if __name__ =='__main__': main()
Open a file:
with open('trip.log','r') as inf:
#use inf.readlines()
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.