如何使AveragePopulation工作

时间:2015-12-15 05:10:01

标签: python

我已经编写了这个程序来阅读美国人口普查从1900年到2000年的列表.PingleYear工作PrintList工作,如果名称有效,但对于AveragePopulation我无法弄清楚如何得到我输入的两个日期的平均值。

import math

f = open('c:/Python34/us_census.txt')

f.readline()

def SingleYear(year):
    totalyears = 0
    for line in f:
        yearlist = line.split()
        totalyears = totalyears + 1
        if year == yearlist[2]:
            population = yearlist[3]

    print(line[0], '/' , line[3], '/', year , 'there were', population, 'in the United States.')

def AveragePopulation(year1, year2):
    for line in f:
        yearlist = line.split()
        if year1 == yearlist [2]:
            population = yearlist[3]
        if year2 == yearlist [2]:
            population = yearlist[3]

    print((year1-year2)/2)

def PrintList():
    for line in f:
        print(line)


if __name__ =='__main__':
    cont=1
    while cont !=0:
        print('''
            1:Get population for a single year between 1900 and 2000
            2: Get average population on a range of years between 1900 and 2000
            3: Show the whole list

            0: Exit program''')

        ans = input("Enter your selectiion (0-3)")
        if ans == '1':
            SingleYear(input("enter a valid year(1900-2000)"))
        if ans == '2':
            AveragePopulation(input("First year"),input("Second year"))
        if ans == '3':
            PrintList()
        if ans == '0':
            cont = 0

1 个答案:

答案 0 :(得分:2)

在功能中,您将人口值设置为 function __clone(){ $this->A_2 = clone $this->A_2; } ,但您打印的是两年的平均值。 它应该是:

yearlist[3]

def AveragePopulation(year1, year2): for line in f: yearlist = line.split() if year1 == yearlist [2]: year1pop = int(yearlist[3].replace(',','')) if year2 == yearlist [2]: year2pop = int(yearlist[3].replace(',','')) print (year1pop+year2pop)/2 替换了这些逗号,.replace基本上将字符串转换为整数。

此外,您不需要在打印的语句周围使用括号 - 例如在PrintList中,

int()

就够了。 :)