3.5k views
1 vote
Write the code to read from a file of unknown length. The file contains data that must be read in sets of 3 pieces of data. The data is a loan id (string), followed by the number of months (number) remaining to payout the loan, followed by the monthly payment (number). You must read the file until the load id is "XXX" (all uppercase). You may assume the file is open for you with a variable named infile. That is: infile

1 Answer

6 votes

Answer:

Check the explanation

Step-by-step explanation:

infile = open("loans.py","r")

totalPay, totalMonth, count = 0,0,0

for line in infile: #for line in file

id = line.split()[0] #extract id

mon = int(line.split()[1]) #months

pay = int(line.split()[2]) #payout

if id == "XXX": break #id found

totalPay = totalPay+mon*pay

totalMonth = totalMonth+mon

if mon>60: count=count+1 #month>60

#print statements

print('Total payout remaining:',totalPay)

print('Loans with more than 60 months left:',count)

print('Average monthly payout till XXX:',totalPay/totalMonth)

#this is for all loans from the file

#ignore this if not required

infile = open("loans.py","r")

totalPay, totalMonth= 0,0

#for whole file, same code

for line in infile:

id = line.split()[0]

mon = int(line.split()[1])

pay = int(line.split()[2])

totalPay = totalPay+mon*pay

totalMonth = totalMonth+mon

print('Average monthly for al loans in file:',totalPay/totalMonth)

User Adam Mills
by
5.9k points