我的程序不接受我的功能。但是,该功能在控制台

时间:2016-03-18 21:58:12

标签: python

我正在写一个小程序,在那里我打印出过去6位总统的第一个月和最后一个月的工作数量。我写了一个名为presidents()的函数,但由于某些原因我无法在程序中使用它。当我尝试在python控制台中运行presidents()函数时,它工作得很好。但是当我尝试在主程序中使用unsorted_pres list和numberPres变量时,我得到一个错误,它没有被定义。

PS。为了测试,我已经从控制台中的presidents()函数复制了输出。这些是注释掉的两行。

import csv

def readcsv(file,y,m):
    with open(file) as f:
        reader = csv.reader(f)
        next(reader)
        list = []
        for row in reader:
            list.append(row)
    year = int(y)
    yIndex = year - 1974
    return list[yIndex][m]


def presidents():
    f = open("presidents.txt", 'r')
    unsorted_pres = []
    for line in f:
        pList = line.split(", ")

        name_raw = pList[0]
        name_split = name_raw.split(" ")
        name_list = name_split[-1:]
        name = "".join(name_list)
        pList.insert(0, name)
        pList.pop(1)

        years_raw = pList[1]
        years_split = years_raw.split("-")
        firstYear = years_split[0]
        lastYear = int(years_split[1]) - 1
        pList.insert(1, firstYear)
        pList.insert(2, lastYear)
        pList.pop(3)

        party_raw = pList[3]
        party_split = party_raw.split("\n")
        party = party_split[0]
        pList.insert(3, party)
        pList.pop(4)

        unsorted_pres.append(pList)

    return unsorted_pres, numberPres

print "Government Employment by President (thousands):"
print "%10s%15s%16s%15s%15s%16s" % ("President","Party","First Month","Last Month","Difference","Percentage")

presidents()
#unsorted_pres = [['Carter', '1977', 1980, 'Democrat'], ['Reagan', '1981', 1988, 'Republican'], ['Bush', '1989', 1992, 'Republican'], ['Clinton', '1993', 2000, 'Democrat'], ['Bush', '2001', 2008, 'Republican'], ['Obama', '2009', 2015, 'Democrat']]
#numberPres = 6 #len(unsorted_pres)

while numberPres > 0:
    for element in unsorted_pres:
        firstMonth = readcsv("government.csv", element[1],1)
        lastMonth = readcsv("government.csv", element[2],12)
        diff = int(lastMonth) - int(firstMonth)
        perc = diff / float(firstMonth) * 100
        print "%10s%15s%16s%15s%15s%15s%%" % (element[0],element[3],format(int(firstMonth), ",d"),format(int(lastMonth), ",d"),format(diff, ",d"), round(perc,1))
        numberPres -= 1

这是'president.txt'文件,由presidents()使用:

James Earl Carter, 1977-1981, Democrat
Ronald Wilson Reagan, 1981-1989, Republican
George Herbert Walker Bush, 1989-1993, Republican
William Jefferson Clinton, 1993-2001, Democrat
George Walker Bush, 2001-2009, Republican
Barack Hussein Obama, 2009-2016, Democrat

1 个答案:

答案 0 :(得分:0)

我可以看到两个问题。首先,numberPres似乎没有在任何地方定义。你从函数中返回它,但它从未定义过。

其次,您从函数返回unsorted_presnumberPres,但您没有将它们分配给任何内容。您需要将返回值分配给某些内容: unsorted_pres, numberPres = presidents() 在你使用它之前。