-
Notifications
You must be signed in to change notification settings - Fork 45
/
Copy pathexercise_10.py
54 lines (40 loc) · 1.5 KB
/
exercise_10.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#This program computes the fuel efficiency of a multi-leg journey
def MPG(odom, infile):
count = 0
#get information about a series of legs
totGas = 0
totDistance = 0
for leg in infile.readlines():
leg = str(leg)
while leg != "\n":
#current odometer and amount of gas used separated by space
try:
newodom, gas = leg.split(" ")
newodom = eval(newodom)
gas = eval(gas)
count = count + 1
#distance traveled per leg
distance = newodom - odom
#total distance
totDistance = distance + totDistance
#compute MPG for leg
legMPG = distance/gas
#set new odometer reading
odom = newodom
print("On leg {0}, you got {1}/gal.".format(count, round(legMPG, 2)))
#add values to trip total
totGas = totGas + gas
totMPG = totDistance / totGas
break
except ValueError:
break
return totMPG
def main():
#Prompt the user for the starting odometer
fname = input("Enter filename: ")
infile = open(fname, "r")
odom = int(input("What is your current odometer reading: "))
totMPG = MPG(odom, infile)
#print out miles/gal on each leg and the total MPG for the trip
print("On whole trip, you averaged {0}/gal.".format(round(totMPG, 2)))
main()