#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @File : 购物车3.0.py
# @Author: Anthony.waa
# @Date : 2018/5/14 0014
# 原始购物清单
goods = [
{"name": "电脑", "price": 1999},
{"name": "鼠标", "price": 10},
{"name": "游艇", "price": 20},
{"name": "美女", "price": 998},
]
# 购物车
shopping_car = {}
# 商品个数
good_count = 1
# 输入不合法是打印
def return_error():
print("\033[1;31m 输入不合法,请重新输入 \033[0m")
# 打印购物车商品和剩余金额
def end_shopping():
print("\033[1;32m 剩余金额为: \033[0m", all_money)
print('\033[1;32m 已购商品有: \033[0m', shopping_car, )
while True:
# 用户输入总资产
all_money = input("\033[1;32m 请输入总资产: \033[0m").strip()
if all_money.isdigit():
all_money = int(all_money)
# 显示购物商品列表
print('\033[1;32m ========== 商 品 清 单 ========== \033[0m'.center(20))
for good_index, good in enumerate(goods, 1):
print('\033[1;32m {0} {1} {2} \033[0m'.format(good_index, good['name'],good['price']).center(20))
print('\033[1;32m 选择"q"退出 \033[0m'.center(20))
while True:
# 选择商品序号,或选择退出购物
choice_count = input("\033[1;32m 请输入商品序号: \033[0m").strip()
if choice_count.isdigit():
choice_count = int(choice_count)
# 商品序号小于商品列表长度
if choice_count > 0 and choice_count <= len(goods):
good_price = goods[choice_count - 1]['price']
# 用户资产大于商品价格,否则提示充值
if all_money > good_price:
good_name = goods[choice_count - 1]['name']
all_money -= good_price
# 商品是否存在购物车中
if good_name not in shopping_car:
shopping_car[good_name] = good_count
else:
for shopping_index, shopping_name in enumerate(shopping_car):
if shopping_name == good_name:
shopping_car[shopping_name] += 1
end_shopping()
else:
print('\033[1;31m 余额不足,请充值: \033[0m'.center(17))
add_money = input("请输入总资产:").strip()
if add_money.isdigit():
add_money = int(add_money)
all_money += add_money
print('\033[1;32m 充值成功,剩余金额为: \033[0m'.center(17), all_money)
continue
elif choice_count.lower() == 'q':
print("\033[1;32m 购物结束,欢迎下次光临 \033[0m")
end_shopping()
exit()
return_error()