python初学者:能打出来但是不知道怎么自定义函数!


就是这样自定义一个函数
def showGoods(x):
函数体
之后调用这个函数showGoods(goods)
把goods列表传递给函的x参数
这样在函数体中就可以通过x参数访问goods列表了,使用for循环遍历x列表中的字典并输出
你题目的解答代码如下:
def showGoods(x):
t = 0
for i,d in enumerate(x):
n = d["name"]
m = d["mount"]
p = d["price"]
print(i+1,n,m,p)
t += p*m
print(f'本次购物总价为{t}元')
goods = [
{"name":"面包","mount":7,"price":5},
{"name":"牛奶","mount":3,"price":10},
{"name":"香蕉","mount":1,"price":12},
{"name":"大米","mount":2,"price":98},
{"name":"苹果","mount":3,"price":5},
]
showGoods(goods)

如有帮助,望采纳!谢谢!