我正在自学 Python,并且正在尝试用 Python 创建一个订购应用程序。该程序将用户给定的产品编号及其价格添加到新字典中。
但是我想不出将这些物品的价格加在一起的方法。
alijst = {}
kera = {1001 : {"naam" : '60 X 60 Lokeren', 'prijs' : 31.95},#the third item (31.95) is the prize and needs to be used in a calculation later
1002 : {"naam" : '40 X 80 Houtlook' , 'prijs' : 32.5},
1003 : {"naam" : '60 X 60 Beïge', 'prijs' : 29.95}}
# The below is for finding the code linked to a product
def keramisch():
global kera
global alijst
klaar = False
while klaar != True:
product = int(input("type a product code or press 0 to close: "))
if product in kera:
alijst[product] = kera[product]
else:
if product == 0:
klaar = True
# The below is what I tried for calculation (it sucks)
def berekenprijs():
global alijst
global prijslijst
for i, prijs in alijst:
print(i)
aantal = int(input("give an amount"))
totaalprijs = aantal * prijs
prijslijst[totaalprijs]
watbestellen()
berekenprijs()
Run Code Online (Sandbox Code Playgroud)
我如何将价格纳入最后一个定义?
我认为你的错误在这里:
for i, prijs in alijst:
Run Code Online (Sandbox Code Playgroud)
这将为您提供订单代码 ( i) 和产品,而不是价格。然后产品有一个属性列表,其中一个是“naam”,另一个是“prijs”。
另请注意,您需要.items()迭代键和值。
for i, prijs in alijst.items():
Run Code Online (Sandbox Code Playgroud)
因此,要访问产品名称,您需要编写
print(prijs["naam"])
Run Code Online (Sandbox Code Playgroud)
要访问价格,您需要
print(prijs["prijs"])
Run Code Online (Sandbox Code Playgroud)
后者很明显这里的命名出错了。
因此我建议将这些变量重命名为
for productcode, product in alijst.items():
Run Code Online (Sandbox Code Playgroud)
然后访问产品的属性
print(product["naam"])
print(product["prijs"])
Run Code Online (Sandbox Code Playgroud)
还有一些问题,我会留给你练习,例如
global prijslijst 引用未定义的变量watbestellen()没有定义。可能你的意思keramisch(),而不是prijslijst[totaalprijs]什么都不做,但由于prijslijst缺少,我很难弄清楚你想做什么| 归档时间: |
|
| 查看次数: |
209 次 |
| 最近记录: |