-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUS_population_program.py
74 lines (60 loc) · 2.4 KB
/
US_population_program.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#US_population_Program.py
# Similar to Assignment 2 Project 2: Fitness Tracker Project with a Console Interface
# The program assumes that all population changes are positive.
# That is, that each year the population was larger than the
# previous year.
def main():
# Setup variables
yearly_change = []
change = 0.0
total_change = 0.0
average_change = 0.0
greatest_increase = 0.0
smallest_increase = 0.0
greatest_year = 0
smallest_year = 0
# Constant for the base year
BASE_YEAR = 1950
try:
# Open the file for reading.
input_file = open('USPopulation.txt', 'r')
# Read all the lines in the file into a list.
yearly_population = input_file.readlines()
# Turn all read strings into numbers.
for i in range(len(yearly_population)):
yearly_population[i] = float(yearly_population[i])
# Calculate the change in population size for each two years.
for i in range(1, len(yearly_population)):
change = yearly_population[i] - yearly_population[i - 1]
yearly_change.append(change)
# If this is the first year, set trackers to its value.
if i == 1:
greatest_increase = change
smallest_increase = change
greatest_year = 1
smallest_year = 1
# This is not the first change in population size.
# Update trackers if relevant.
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 / len(yearly_change)
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)
except IOError:
print('The file could not be found.')
except IndexError:
print('There was an indexing error.')
except:
print('An error occurred.')
# Call the main function.
main()