python练习-购物车

练习-购物车

需求

  • 用户启动的时先输入工资
  • 用户启动程序后打印商品列表
  • 允许用户选择购买商品
  • 允许用户不断的购买各种商品
  • 购买时检余额是否足够,如果足够直接扣款,否则打印余额不足
  • 允许用户主动退出程序,退出时打印已购列表
#!/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 ... ')
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值