Difference between revisions of "Python:Accumulate over a File with Multiple Variables"

From Progzoo
Jump to navigation Jump to search
Line 78: Line 78:
       pop  = int(f[3])
       pop  = int(f[3])
       gdp = int(f[4])
       gdp = int(f[4])
       if pop>30000000:
       if pop>3000000:
         b = b+1
         b = b+1

Revision as of 18:37, 12 July 2017

In these examples we accumulate more than one value. We still only need one loop - we just do more work in each.

Average population

Calculate the average population size for the countries of the world.

Print the total population divided by the number of countries.

Recall that there are three steps:

  • Declare and initialise your accumulators before the loop


totPop = 0
count = 0
  • Increment the accumulator inside the loop.
totPop += pop
  • Use the result - in this case print it, after the loop.
     print totPop/count
[Font] [Default] [Show] [Resize] [History] [Profile]

Is 3 million the median?

Show the number of countries with a population more than 3000000

Show the number of countries with a population less than 3000000

[Font] [Default] [Show] [Resize] [History] [Profile]

USA and the world

Show the GDP of "United States" as a percentage of the world GDP.

[Font] [Default] [Show] [Resize] [History] [Profile]