首页 > 解决方案 > 嗨,你能协助完成这个 python 任务吗?

问题描述

试图结账

price = {'sugar' : 45,'rice': 60,'tealeaves':450,'wheat':40,'oil':100};
ordered = {'sugar':2,'rice': 3,'tealeaves':0.5,'wheat':4,'oil':1}

total = list()

for k,v in price:
    value = price[k]*kgsordered[k]
    print (k,':',value)
    total.append(value)

print('*'*4,'CG Grocery Store','*'*4)

print('Your final bill is ₹',total.sum())

print('Thank you for shopping with us!!')

追溯来了

回溯(最近一次通话最后):

文件“C:\Users\user\Desktop\My Python Files\curiosity gym python HW.py”,第 4 行,价格为 k,v:ValueError:解包值太多(预期为 2)

标签: python-3.x

解决方案


首先,您必须使用.items()遍历字典。

其次,您使用的是kgsordered[k]instead of ordered[k],这会给您一个错误,因为kgsordered未定义。

最后,如果你想计算一个列表中所有元素的总和,你可以这样做 sum(total)total你的列表在哪里

price = {'sugar' : 45,'rice': 60,'tealeaves':450,'wheat':40,'oil':100};
ordered = {'sugar':2,'rice': 3,'tealeaves':0.5,'wheat':4,'oil':1}

total = list()

for k,v in price.items():
    value = price[k]*ordered[k]
    print (k,':',value)
    total.append(value)

print('*'*4,'CG Grocery Store','*'*4)

print('Your final bill is ₹',sum(total))

print('Thank you for shopping with us!!')

# output

sugar : 90
rice : 180
tealeaves : 225.0
wheat : 160
oil : 100
**** CG Grocery Store ****
Your final bill is ₹ 755.0
Thank you for shopping with us!!

推荐阅读