snowdream的Python简单循环应用(二)
product_list = [{‘name’: ‘苹果’, ‘price’: 10},
{‘name’: ‘榴莲’, ‘price’: 30},
{‘name’: ‘草莓’, ‘price’: 20},
{‘name’: ‘菠萝’, ‘price’: 15}]
超市买水果功能分析
(1)输入自己所有的钱。
(2)展示商品的序号,名称及其价格。
(3)输入要买商品的序号。
(4)输入要买商品的数量。
(5)购物车中显示购买的水果名称及其对应的数量和剩余钱。
(6)如果序号输入有误就提示用户重新输入。
(7)如果钱不够了提示用户钱不够,并且退出程序。
本问题解决方法代码如下:
product_list = [{'name': '苹果', 'price': 10},
{'name': '榴莲', 'price': 30},
{'name': '草莓', 'price': 20},
{'name': '菠萝', 'price': 15}]
mone=int(input("请输入金额:"))
rmone=0
c=0
a=0
while a<len(product_list):
product_list[a]["id"]=a+1
a+=1
print(product_list)
while True:
if c==1:
print("你的余额不足,无法购买商品")
break
else:
id = int(input("输入商品的序号:"))
sum = int(input("输入商品的数量:"))
b = 0
if id > len(product_list):
print("没有{}商品".format(id))
continue
while b <= len(product_list):
if b == id:
print("你选中{0}号商品:{1},你要买{1}的数量{2}斤".format(id, product_list[id - 1]["name"], sum))
rmone = rmone + ((product_list[id - 1]["price"]) * sum)
print("你已经选购{}元的商品".format(rmone))
e = mone - rmone
print("你剩余的钱{}元".format(e))
b += 1
if e <= 0:
c = 1