您的位置:首页 > 编程语言 > Python开发

python练习-购物车

2017-03-19 13:42 323 查看

练习-购物车

需求

用户启动的时先输入工资

用户启动程序后打印商品列表

允许用户选择购买商品

允许用户不断的购买各种商品

购买时检余额是否足够,如果足够直接扣款,否则打印余额不足

允许用户主动退出程序,退出时打印已购列表

#!/usr/bin/env python
# _*_ coding:utf-8 _*_
#  用户输入工资
salary = input('please input salary :')
if salary.isdigit() :
salary = int(salary)
else:
print('Invaild data type ...')
exit()
#  打印欢迎信息
welcome_msg = 'welcome to Shooping mall'.center(50,'-')
print(welcome_msg)

# 商品列表
product_list = [
('iphone',5888),
('Mac Air',8888),
('Mac Pro',9999),
('XiaoMi 2 ',19),
('Coffee',30),
('Tesla',820000),
('Bike',900),
('Cloth',200)
]
# 定义购物车
shop_car = []

exit_flag = False
while not exit_flag:
#  打印商品列表
#  enumerate(枚举函数)方法打印列表下标
print('product list'.center(50,'-'))
for i,item in enumerate(product_list):
p_name,p_price = item
print('%s. %s   %s元' %(i,p_name,p_price))
#  用户选择商品
user_choice = input('[q=quit,c=check]What do you want to buy?:')
# 判断输入的是否是数字,如果是数字肯定是购买商品
if user_choice.isdigit():
user_choice =  int(user_choice)
# 判断输入的数字是否合法,是否超出的商品列表的长度
if user_choice < len(product_list):
# 取出已经选定的购买的商品
p_item = product_list[user_choice]
if p_item[1] <= salary : #判断是否买的起
shop_car.append(p_item) #放入购物车
salary -= p_item[1]  # 计算余额
#\033[32;1m[%s]\033 linux系统上添加颜色,固定格式,32是绿色
print('Added  \033[32;1m[%s]\033[0m into shop car,you current balance is [%s]'
%(p_item,salary))
else:
print('Your balance is [%s],cannot afford this ..' % salary)
else:
print('Please Choose the right goods ... ')
# 判断是否是检查购物车
elif user_choice == 'c' or user_choice == 'check':
print('purchased product'.center(50,'*'))
for item in shop_car:
print(item[0],item[1])
print('END'.center(50,'*'))
print('Your balance is [%s]' % salary)
# 判断是否是退出
elif  user_choice == 'q' or user_choice =='quit' :
# 打印已经购买的商品列表
print('purchased product'.center(50,'*'))
for item in shop_car:
print(item[0],item[1])
print('END'.center(50,'*'))
print('Your balance is \033[31;1m[%s]\033[0m' % salary)
exit_flag = True
else:
print('Please Choose the right option ... ')
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python