In: Computer Science
DO NOT ANSWER THIS[1. Write a program named filemaker.py that will be used to store the first name and age of some friends in a text file named friends.txt. The program must use a while loop that prompts the user to enter the first name and age of each friend. Each of these entries should be written to its own line in the text file (2 lines of data per friend). The while loop should repeat until the user presses Enter (Return on a Mac) for the name. Then, the file should be closed and a message should be displayed. See Sample Output. SAMPLE OUTPUT Enter first name of friend or Enter to quit Denny Enter age (integer) of this friend 24 Enter first name of friend or Enter to quit Penny Enter age (integer) of this friend 28 Enter first name of friend or Enter to quit Lenny Enter age (integer) of this friend 20 Enter first name of friend or Enter to quit Jenny Enter age (integer) of this friend 24 Enter first name of friend or Enter to quit File was created] DO NOT ANSWER THIS
Code for the above program
fp = open("friends.txt", "w")
firstname = input("Enter first name of friend or Enter to quit ")
while firstname!="":
age = int(input("Enter age (integer) of this friend "))
print(firstname, file=fp)
print(age, file=fp)
firstname = input("Enter first name of friend or Enter to quit ")
fp.close()
print("File was Created")
the QUESTION IN PYTHON
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
// text code for filereader.py
#open file in read mode
fp = open("friends.txt", "r")
# initialize accumulator and counter to 0
accumulator = 0
counter = 0
#is name tracks whether we are scanning Name or age in
file
is_name = True
# name will store the last name from file
name = ""
# for each line in file
for line in fp:
# if line is name
if(is_name == True):
# make is_name false, means we are reading age
is_name = False
#rstrip('\n') removes the new line at the end of line
name = line.rstrip('\n')
else:
# make is_name false
is_name = True
# increment counter
counter = counter + 1
# add the age
accumulator = accumulator + int(line.rstrip('\n'))
#print the name and age
print("My friend", name, "is", line.rstrip('\n'))
#close the file
fp.close()
# print the avearge if counter is not zero
if(counter != 0):
print("Average age of friends is", round((accumulator/counter),
1))
else: print("There is no friend in the list")
# SCREENSHOTS
# filereader.py
# friends.txt file
# OUTPUT