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

Python 3 Reading From File Write a program that will read the contents of the fi

ID: 3824791 • Letter: P

Question

Python 3 Reading From File

Write a program that will read the contents of the file USPopulation.txt into a list, and calculate and display:

The average annual change in population during the time period 1950 - 1990 (inclusive)

The year with the greatest increase in population during the time period 1950 - 1990 (inclusive)

The year with the the smallest increase in population during the time period 1950 - 1990 (inclusive)

USPopulation.txt file lists the population, in thousands, of the United States during the years 1950 - 1990 (inclusive). The first line of the file is the population in year 1950, the second line the population in the year 1951 etc. Here is what is in the file:

151868

153982

156393

158956

161884

165069

168088

171187

174149

177135

179979

182992

185771

188483

191141

193526

195576

197457

199399

201385

203984

206827

209284

211357

213342

215465

217563

219760

222095

224567

227225

229466

231664

233792

235825

237924

240133

242289

244499

246819

249623

Explanation / Answer

def main():

yearly_change = []

change=0.0

total_change=0

average_change=0

greatest_increase=0

smallest_increase=0

greatest_year=0

smallest_year=0

BASE_YEAR=1950

try:

input_file = open("USPopulation.txt", "r")

yearly_population= input_file.readlines()

for i in range(len(yearly_population)):

yearly_population[i] = float(yearly_population[i])

for i in range(1,len(yearly_population)):

change = yearly_population[i] - yearly_population[i-1]

if i==1:

greatest_increase = change

smallest_increase = change

greatest_year = 1

smallest_year = 1

else:

if change>greatest_increase:

greatest_increase = change

greatest_year = i

elif change<smallest_increase:

smallest_increase = change

smallest_year = i

total_change = float(sum(yearly_change))

average_change = total_change/40

print("The average annual change in population during the time period is",

format(average_change, '.2f'))

print("The year with the greatest increase in population was",

BASE_YEAR+greatest_year)

print("The year with the smallest increase in population was",

BASE_YEAR+smallest_year)

input_file.close()

except IOError:

print("The file could not be found")

except IndexError:

print("There was an indexing error")

except:

print("An error occurred")

main()