用函数的方式实现购物程序
如果已有商品
shang_pin_info = {
101: {"name": "屠龙刀", "price": 10000},
102: {"name": "倚天剑", "price": 10000},
103: {"name": "九阴白骨爪", "price": 8000},
104: {"name": "九阳神功", "price": 9000},
105: {"name": "降龙十八掌", "price": 8000},
106: {"name": "乾坤大挪移", "price": 10000}
}
要求先实现判断用户是购物还是结算,分别实现功能:
一、购物
1、打印商品数据 ,展示给用户看
2、用户输入商品编号及购买数量
3、添加购买的商品到购物车
二、结算
1、打印购物车中的商品数据
2、计算已购商品的总价格
3、输入付款金额,并打印找零
代码如下:
shang_pin_info = {
101: {"name": "屠龙刀", "price": 10000},
102: {"name": "倚天剑", "price": 10000},
103: {"name": "九阴白骨爪", "price": 8000},
104: {"name": "九阳神功", "price": 9000},
105: {"name": "降龙十八掌", "price": 8000},
106: {"name": "乾坤大挪移", "price": 10000}
}ding_dan = []
def gou_wu():
"""
购物流程
"""
while True:
item = input("请输入数字:1代表购买,2代表结算。")
if item == "1":
shopping()
elif item == "2":
buying()flag = input("是否继续购物或者结算,输入exit退出,其他符号继续:")
if flag == "exit":
break
def buying():
"""
结算流程
"""
all_shang_money = 0
for item in ding_dan:
shang_pin = shang_pin_info[item["cid"]]
total_price = shang_pin["price"] * item["count"]
print(f"商品:{shang_pin['name']},单价:{shang_pin['price']},数量:{item['count']},小计:{total_price}元")
all_shang_money += total_pricewhile True:
try:
all_now_money = float(input("总价%d元,请输入金额:" % all_shang_money))
if all_now_money >= all_shang_money:
print("购买成功,找回:%d元。" % (all_now_money - all_shang_money))
ding_dan.clear()
break
else:
print("金额不足.")
except ValueError:
print("请输入有效的金额.")
def shopping():
"""
购物车添加商品流程
"""
for key, value in shang_pin_info.items():
print(f"编号:{key},名称:{value['name']},单价:{value['price']},总价:{value['price'] * 1}元")
while True:
try:
cid = int(input("请输入商品编号:"))
if cid in shang_pin_info:
break
else:
print("该商品不存在")
except ValueError:
print("请输入有效的商品编号.")while True:
try:
count = int(input("请输入购买数量:"))
if count > 0:
break
else:
print("数量必须大于0")
except ValueError:
print("请输入有效的购买数量.")ding_dan.append({"cid": cid, "count": count})
print("添加到购物车。")
gou_wu()