2. Now write a program named filereader.py that reads and displays the data in f
ID: 3850866 • Letter: 2
Question
2. Now write a program named filereader.py that reads and displays the data in friends.txt. This program should also determine and print the average age of the friends on file. That will require an accumulator and a counter. Use a while loop to process the file, print the data, and modify the accumulator and counter. Then close the file and display the average age accurate to one decimal place. See the Sample Output.. SAMPLE OUTPUT My friend Denny is 24 My friend Penny is 28 My friend Lenny is 20 My friend Jenny is 24 Average age of friends is 24.0
Explanation / Answer
# Feel free to comment ,if u have any doubt regarding code. Cheers :-):-) # Program starts count = 0; Total_age = 0; file = open("friends.txt","r") for line in file: count = count + 1 # count of number of lines in the given file if (count%2 == 0): # for second line print age print line, age = float(line) Total_age = Total_age + age else: line = line.strip(' ') print "My Friend {name} is".format(name = line), #For 1st line print name file.close() count = count/2 # count of persons ,because two lines contains only one person age Average_age = Total_age / count print " Average age of Friends is {}".format(Average_age);
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.