我的def main()
部分遇到了问题,特别是当我调用循环其他变量时。
我检查了我的参数是否检查,他们做了什么。当我评论该部分时,代码“工作”,并且它不会崩溃。但是,当取消注释时,它会一直说在分配之前引用了我的fileInput
变量。
然后我尝试将fileIn
中的def readFile()
切换到if yearIn
== 2008之前,但现在错误显示了预期的字符串值(我没有“”我的因为我希望它是一个整数)。
我究竟做错了什么?我希望我的代码能够运行并输出一个文件,列出具有最高和最低MPG的汽车。
def readFile(yearIn):
# open file
if yearIn == 2008:
fileInput = open("epaVehicleData2008.csv", "r")
else:
fileInput = open("epaVehicleData2009.csv", "r")
fileIn = open(fileInput, "r")
# open file
# if yearIn == 2008:
# fileInput = open("epaVehicleData2008.csv", "r")
# else:
# fileInput = open("epaVehicleData2009.csv", "r")
count = 0
#empty list
manufactureList =[]
carTypeList = []
mpgList = []
for line in fileIn:
line = line.strip()
carInfo = line.split(",")
if count != 0:
if "VAN" not in carInfo[0] and "PICKUP" not in carInfo[0] and "CLASS" not in carInfo[0]:
manufactureList(carInfo[1])
carTypeList(carInfo[2])
mpgList.append(carInfo[9])
count += 1
maxMPG = max(mpgList)
minMPG = min(mpgList)
minCars = []
maxCars = []
for X in range(len(mpgList)):
if mpgList[X] == minMPG:
result = manufactureList[X] + " " + carTypeList[X]
minMPG.append(result)
if mpgList[X] == maxMPG:
result = manufactureList[X] + " " + carTypeList[X]
maxCars.append(result)
#close
fileIn.close()
return maxMPG, minMPG, maxCar, minCar
def writeFile(fileName, year, maxMPG, minMPG, maxCar, minCar):
#open file
fileOut = open(fileName, "w")
print("EPA Highway MPG Calculator", year, file = fileOut)
print("-----------------------------------")
print("Maximum Mileage (highway):", maxMPG, file=fileOut)
print("\n".join(maxCars), file=fileOut)
print("Minimum Mileage (highway):", minMPG, file=fileOut)
print("\n".join(minCar), file=fileOut)
#close file
fileOut.close()
def main():
print("Welcome to EPA Mileage Calculator.")
#user select year
yearIn = int(input("What year would you like to view data for (2008 or 2009)? "))
#invalid input if neither 2008/2009
while yearIn != 2008 and yearIn != 2009:
print("Invalid input, please try again.")
yearIn = int(input("What year would you like to view data for (2008 or 2009)? "))
fileNameSave = input("Enter the filename to save results to (.txt file): ")
print("Operation Success! Mileage data has been saved to", fileNameSave)
print("Goodbye.")
maxMPG, minMPG, maxCar, minCar = readFile(yearIn)
#minMPG = readFile(yearIn)
#carTypeList = readFile(yearIn)
#manufactureList = readFile(yearIn)
writeFile(fileNameSave, yearIn, maxMPG, minMPG, maxCar, minCar)
main()