[英]How to count the total amount of list correctly
我正在嘗試編寫一本會計賬簿,但在計算總金額時遇到了困難,可以在列表打印出來后進行計算,但數字不正確。 我試着用+
來計算總量,但沒有用。
我究竟做錯了什么?
import os
def read_file(filename):
items = []
with open(filename, 'r', encoding='utf-8') as f:
for line in f:
if 'your product,your price' in line:
continue
#product,price = line.strip().split(',')
#item.append([product, price])
else:
print("list>>> ----v")
return item
def user_input(item):
while True:
product = input("\nitem:")
if product == 'q':
break
price = input("\nprice:")
price = int(price)
item.append([product, price])
return item
def print_file(item):
for price in item:
print(price[0], 'is: ', price[1])
#total amount
count = price[1]
total_count = count + count
num = (f"you spend total {total_count}")
print(num)
def write_file(filename, item):
with open(filename, 'w', encoding='utf-8') as f:
f.write('your product,your price\n')
for price in item:
f.write(price[0] + ':' + str(price[1]) + '\n')
def main():
filename = 'list.text'
if os.path.isfile(filename):
print("File Found")
file = read_file(filename)
else:
print("Wlecome")
item = []
item = user_input(item)
print_file(item)
write_file('list.txt', item)
main()
您在添加計數時犯了一個小的命名錯誤,試試這個:
def print_file(item):
total_count = 0
for price in item:
print(price[0], 'is: ', price[1])
#total amount
count = price[1]
total_count += count
num = (f"you spend total {total_count}")
print(num)
選擇:
def print_file(item):
total = 0
for price in item:
print(price[0], 'is: ', price[1])
total += price[1]
num = (f"you spend total {total_count}")
print(num)
或者簡單地
def print_file(item):
total = sum([price[1] for price in item])
print(f"you spend total {total}")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.