Here is my code, its pretty bad. I am trying to find out if population density was equal, how much population each country would have. The csv file is from wikipedia, having country, population, area, density as columns. It works now, but if I remove the commented blocks, only the first loop will work. The bottom loops will not. The print outside the loop works but not the one inside. I only had 2 loops but added a third to test wtf was happening and yeah, it only works if there's one loop.
import csv
total_population = 0
total_area = 0
with open("C:/Users/Aditya/Desktop/table1.csv", newline="") as csvfile:
dict1 = csv.DictReader(csvfile)
dict2 = csv.DictReader(csvfile)
# for row in dict1:
# population = float(row.get("Population"))
# area = float(row.get("Area"))
# density = population/area
# #print(area)
# #print(population)
# population = float(population)
# total_population += population
# total_area += area
average_density = 7910157000/122162000
def change_population(c_pop, c_den, c_area):
if c_den < average_density:
delta_pop = average_density*c_area - c_pop
elif c_den > average_density:
delta_pop = c_pop - average_density*c_area
return delta_pop
print(f"{total_population} people, {total_area} km2")
# for row in dict1:
# population = float(row.get("Population"))
# area = float(row.get("Area"))
# density = population/area
# print(area)
# print(population)
# population = float(population)
# total_population += population
# total_area += area
for row in dict2:
population = float(row.get("Population"))
area = float(row.get("Area"))
density = float(row.get("Density"))
change = change_population(population, density, area)
population2 = str(population + change)
row.update({"Population": population2})
print(f"{row}")