私は最後の6名の大統領の最初と最後の月のジョブ数をプリントアウトする小さなプログラムを書いています。私はpresident()と呼ばれる関数を書いていますが、なんらかの理由で自分のプログラムで働かせることはできません。私がpythonコンソールでpresidents()関数を実行しようとすると、うまく動作します。しかし、メインプログラムでunsorted_presリストとnumberPres変数を使用しようとすると、定義されていないというエラーが表示されます。私のプログラムは私の機能を受け入れません。しかし、この機能はコンソールでうまく動作します
PS。テストのために、コンソールのpresidents()関数の出力をコピーしました。これらはコメントアウトされた2行です。
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' ファイル、()です:
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
'numberPres'は' presidents() 'メソッド内では宣言されていません –
あなたのスコープはどこにでもあります。 – TigerhawkT3
@ TigerhawkT3「スコープ」とはどういう意味ですか?はい、私は合計n00bですので、私のコードはおそらく恐ろしいです... –