python-购物车程序练习


购物车练习题:
需求如下
1、启动程序后,让客户输入自己的金额,并打印出商品列表
2、让客户根据商品编号,选择商品
3、选择完成后,检测余额是否够,够就直接扣款并将商品保存至字典中,如果余额不足提示用户进行充值
4、用户可以随时选择退出,退出时打印自己购买的商品 ,消费总额和余额

product_list = [
  ["台式电脑", 4992],
  ["手机", 2999],
  ["移动硬盘", 390],
  ["U盘", 100],
  ["笔记本", 6223],
  ["鼠标", 200],
  ["键盘", 492]
]
####################################################
product_list = [["台式电脑", 4992],["手机", 2999], ["移动硬盘", 390],["U盘", 100], ["笔记本", 6223],["鼠标", 200], ["键盘", 492]]
shopping = {}
bbb= 0
# sho = {
# "台式电脑":{"price":4992,"num":3}
# }
salary = input("请输入您的工资:")
if salary.isdigit():
salary = int(salary)
while True:
# for i in product_list:
# print(product_list.index(i),i)
for a, b in enumerate(product_list):
print(a, b)
user_choice = input("选择要买的商品序列(q/Q结算):")
if user_choice.isdigit(): # 判断输入的是否是数字
user_choice = int(user_choice) # 将str数字转为int类型
if user_choice < len(product_list) and user_choice >= 0: # 判断数字时候是列表序列的范围
# 判断钱够不够
p_item = product_list[user_choice] # 这个是一个商品["台式电脑", 4992]
if p_item[1] <= salary: # 判断商品列表中的价格和你的工资的关系
if p_item[0] in shopping.keys():
shopping[p_item[0]]["num"] += 1
salary -= p_item[1] # 将工资总数减去你选的商品的价格
print(shopping)
print("Added %s into shopping cart, yu e is %s" % (p_item, salary))
else:
shopping[p_item[0]] = {"price":p_item[1],"num":1} # 如果是你工资大于等于商品价格,则将商品加入到shopping空列表中
salary -= p_item[1] # 将工资总数减去你选的商品的价格
print("Added %s into shopping cart, yu e is %s" %(p_item,salary))
print(shopping)
else:
print("资产不足,请充值:当前商品价格为:%s ,您资产剩余为: %s"%(p_item,salary))
chong = input("充值请输入c,结算请输入q,输入其他字符为无效")
if chong == "c":
b = input("请输入您要充值的金额:")
if b.isdigit():
b = int(b)
salary += b
print("您充值资产为:%s ,当前资产为 %s ,购物车列表为:%s" %(b,salary,shopping))
continue
elif chong == "q":
print("您购买的商品有:%s ,您的资产剩余 %s" % (shopping, salary))
for k, v in shopping.items():
n = v["price"]
m = v["num"]
zong = n * m
bbb = bbb + zong
print("总消费为: %s" % (bbb))
#for k,v in cat.items():
# print(k,v)
# n = v['num']
# m = v['one_proce']
# all_sum = n * m
# all_price = all_price + all_sum
exit()
else:
continue
else:
print("请输入正确的商品序号")
elif user_choice.lower() == "q":
print("您购买的商品有:%s ,您的资产剩余 %s" %(shopping,salary))
for k,v in shopping.items():
n = v["price"]
m = v["num"]
zong = n * m
bbb = bbb + zong
print("总消费为: %s" %(bbb))
exit()
else:
print("请输入正确的商品序号")



posted @ 2018-11-29 18:19  运维小菜鸟的开发之路  阅读(459)  评论(0编辑  收藏  举报