Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

For a Python program and only using while loops Suppose we record in a file the

ID: 3765152 • Letter: F

Question

For a Python program and only using while loops

Suppose we record in a file the following information for each leg of a car trip:

number of miles traveled amount of gas used

Write a program that gets the name of the file in which the above information is stored and after reading in the entire file, prints the gas mileage for each leg and the average mileage for the entire trip.

Suppose the file td1.txt contains the following data.
100 2
50 2
200 10

Here is a sample interaction.

Enter file name: td1.txt

Leg 1 50.0

Leg 2 25.0

Leg 3 20.0

Overall mileage 25.0

1) The information must be printed only after the entire data has been read in.
2) The file may be empty.
3) Must use while loops and no for loops

Explanation / Answer

filename = raw_input("Enter name of file ")
file_ptr = open(filename)
content = file_ptr.read()
total_mile = 0
total_fuel = 0
count = 0
i=0
data = content.split(" ")
length = len(data)
if(length==0):
    print "No data available"
else:
    while(i<length):
        row = data[i].split()
        if(len(row)!=2):
            print "Invalid file"
            exit()
        i += 1
        count += 1
        total_mile += int(row[0])
        total_fuel += int(row[1])
        leg = ((int)(row[0])*1.0)/(int)(row[1])
        print "Leg",count,leg
      

    print "Overall mileage",total_mile/total_fuel

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote