4.1、购物车系统

购物车系统

  1. 启动程序后,让用户输入工资,然后打印商品列表
  2. 允许用户根据商品编号购买商品
  3. 用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒
  4. 可随时退出,退出时,打印已购买商品和余额
#!/usr/bin/env python
# coding: utf-8
# Author: Yerban

product_list = [
    ('iphone', 5800),
    ('macbook', 14000),
    ('bike', 800),
    ('iwatch', 10600),
    ('coffee', 31),
    ('alex python', 120)
]

shopping_list = []
salary = input("input your salary:")

# isdigit() 方法检测字符串是否只由数字组成。
if salary.isdigit():
    salary = int(salary)
    while True:
# enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。
# enumerate() 方法的语法:enumerate(sequence, [start=0])
# sequence -- 一个序列、迭代器或其他支持迭代对象。
# start -- 下标起始位置。enumerate(product_list, start=3)
        for index, item in enumerate(product_list):
            print(index, item)
# 笨方法打印出列表索引,先遍历出原list的元素,然后再用index打印出下标。
#        for item in product_list:
#            print(product_list.index(item), item)

        user_choice = input("Input purchase item? >>>:")

        if user_choice.isdigit():
            user_choice = int(user_choice)
            if len(product_list) > user_choice >= 0:
                p_item = product_list[user_choice]
                if p_item[1] <= salary:  # 买得起
                    shopping_list.append(p_item)
                    salary -= p_item[1]
                    # 31是字体标红,41是字体背景标红
                    print("Added %s into shopping cart, your current balance is \033[31;1m%s\033[0m ." % (p_item, salary))
                else:
                    print("\033[41;1m你的余额剩余[%s],还买个毛线啊...\033[0m ." % salary)
            else:
                print("product code [%s] is not exist!" % user_choice)
        elif user_choice == "q":
            print("------shopping list------")
            for p in shopping_list:
                print(p)
            print("Your current balance :", salary)
            exit()

else:
    print("Input is wrong!")

你可能感兴趣的:(4.1、购物车系统)