本文主要内容:用python实现一个购物程序
功能介绍:
1、显示商品列表
2、根据输入的工资判断是否能买得起选择的商品
3、购物车存放已经购买的商品
#1.购物车程序
# 输入工资
while True:
wage = input("请输入您的工资:")
if not wage.isdigit():
print("请输入整数")
else:
wage=int(wage)
break
# 商品列表
goods = [
{"id": 1, "name": "iPhone", "price": 5000},
{"id": 2, "name": "MacBook", "price": 9000},
{"id": 3, "name": "iPad", "price": 3000}
]
# 打印商品列表
print("商品列表:")
for i, commodity in enumerate(goods):
print(f"{i + 1}. {commodity['name']} 价格:{commodity['price']}")
# 购物循环
cart = []
while True:
# 选择商品
id = int(input("请输入商品编号(0退出):"))
if id == 0:
break
# 检查商品是否存在
g = None
for commodity in goods:
if commodity["id"] == id:
g = commodity
break
if not g:
print("商品不存在!")
continue
# 检查余额是否足够
if g["price"] > wage:
print("余额不足!")
continue
# 购买商品
cart.append(g)
wage -= g["price"]
print("购买成功!")
# 打印购物车和余额
print("购物车:", end="")
for c in cart:
print(c["name"], end=",")
print()
print("余额:", wage)
# 如果购物车为空
if not cart:
print("您未购买任何商品! 余额:", wage)
else:
print("购物结束,您的购物车为:", end="")
for c in cart:
print(c["name"], end=",")
print("\n余额:", wage)
执行效果: