新手编程和我的任务之一有问题。 我试图让我的一个函数从txt文件中读取数据并计算欠款,但我确实没有做到这一点。我已经使其他功能正确,但无法解决这个问题。
对不起,如果好像我要求你们为我做功课,但我不是。我对我应该做的事情感到非常困惑,以使其发挥作用。
这是代码(我在第12行" calcData")
import csv
def readData():
fields = ("name", "city", "miles", "gallons")
f = open("travel.txt", "r")
travels = []
dReader = csv.DictReader(f, fieldnames=fields, delimiter="\t")
for row in dReader:
travels.append(row)
f.close()
return travels
def calcData(trips):
user = input("Enter user: ")
record = {'name' : user, 'miles': mi, 'gallons': gal}
mpg = mi/gal
owed = mi*.75
print(user, "is owed:" , owed)
print(user, " had an mpg of: ", mpg)
return trips
def displayData(trips):
fs = "%-8s %-16s %7s %s"
print(fs % ("Name", "City", "Miles", "Gallons"))
for t in trips:
fs = "%-8s %-16s %6s %5s"
print(fs % (t['name'], t['city'], t['miles'], t['gallons']))
def addTrip(trips):
nom = input("Enter your first name: ")
city = input("Enter the destination city: ")
mi = input("Enter the miles traveled: ")
gal = input("Enter the gallons used: ")
record = {'name' : nom, 'city': city, 'miles': mi, 'gallons': gal}
trips.append(record)
return trips
def storeData(trips):
fields = ("name", "city", "miles", "gallons")
f = open("travel.txt", "w")
dWriter = csv.DictWriter(f, fieldnames=fields, delimiter="\t",lineterminator="\n")
dWriter.writerows(trips)
f.close()
def main():
travel_log = readData()
while True:
print("""
Menu options. Choose 1, 2, or 3
1. Display all trip data
2. Calculate user expense
3. Add a trip
4. Save and exit
""")
opt = input(" Enter your choise, 1, 2, or 3: ")
if opt == "1":
print()
displayData(travel_log)
elif opt == "2":
print()
travel_log = calcData(travel_log)
elif opt == "3":
travel_log = addTrip(travel_log)
elif opt == "4":
storeData(travel_log)
print("Goodbye")
print()
break
main()
以下是我试图阅读的文字:
alice chicago 663 20.7
bob indianapolis 226 8.7
alice nashville 409 16.4
carl indianapolis 243 8.4
diane st. louis 581 16.4
bob st. louis 560 18.1
bob cincinnati 237 6.6
alice chicago 681 17.9
alice nashville 422 14.6
diane chicago 676 22.5
carl indianapolis 243 6.4
diane indianapolis 276 7.7
diane indianapolis 241 9.4
编辑:
Traceback (most recent call last): File "..." in <module> main() File ".." , in main travel_log = calcData(travel_log) File ".." , in calcData record = {'name' : user, 'miles': mi, 'gallon' : gal } NameError: name 'mi' is not defined
Here is what it is suppoesed to look like according to my professor
答案 0 :(得分:0)
您需要搜索“alice”的所有行程,并且只计算“她”的费用(并使用字符串格式作为奖励积分):
import csv
def calcData(trips):
user = input("Enter user: ")
mi = 0
gal = 0
for t in trips:
if t["name"] != user:
continue # next one, not alice
mi += float(t["miles"]) # add up all hers
gal += float(t["gallons"]) # same
mpg = mi / gal
owed = mi * .75
print('{} is owed: {:8.2f}'.format(user,owed)) # format float as you like
print('{} had an mpg of: {:8.2f}'.format(user, mpg))
return trips
另外,我会改变你的阅读/写作:
def readData():
fields = ("name", "city", "miles", "gallons")
travels = []
# f = open("travel.txt", "r")
with open("travel.txt", "r") as f: # more robust regarding errors and autocloses
dReader = csv.DictReader(f, fieldnames=fields, delimiter="\t")
for row in dReader:
travels.append(row)
return travels
def storeData(trips):
fields = ("name", "city", "miles", "gallons")
with open("travel.txt", "w", newline="") as f: # this recreates the file all the time
dWriter = csv.DictWriter(f, fieldnames=fields, delimiter="\t",lineterminator="\n")
dWriter.writerows(trips)
使其更加强大,防止异常并避免使用无意义的换行符。