购物车程序实现

 题目来源:老男孩教育Python视频

购物车程序实现_第1张图片

#  -*- coding: utf-8 -*-
"""
@Author:yhf1995
@time:2020/1/30 8:24
"""
salary = input("Please input your money number:")
product_list =[
    ("Apple watch", 4500),
    ("milk", 60),
    ("bike", 1000),
    ("Starbucks", 40),
    ("book",80)
]
shopping_list = []
if salary.isdigit():
    salary = int(salary)
# 判断输入的金额是否为数字,如果是将其转为int类型,如果不是,输出 输入有误
    while True:
        for item in product_list:
            print(product_list.index(item),item)
            # 打印商品列表
        choice_number = input("Please enter the number of the product you want:>>>")
        if choice_number.isdigit():
            choice_number = int (choice_number)
            # 判断输入的商品编号是否为数字,如果是转为int型,如果不是,提示输入有误
            if choice_number < len(product_list) and choice_number >= 0:
                # 判断商品是否存在
                if salary >= product_list[choice_number][1]:
                    shopping_list.append(product_list[choice_number])
                    salary -= product_list[choice_number][1]
                    print("add shop %s in your shopping cart,and your salary is \033[31;1m%s\033[0m!"%(product_list[choice_number],salary))
                    # 判断余额是否足够,余额足够,将商品放入购物车,余额减去该商品价格,输出放入购物车的商品和余额
                else:
                    print("You have insufficient balance!")
                    # 余额不足
            else:
                print("product_number does not exist!")
                # 商品不存在
        elif choice_number == "Q":
            print("The shopping cart list is as follows:")
            for shop_item in shopping_list:
                print(shop_item)
            print("Your current balance is %s."%(salary))
            exit()
            # 输入Q 打印购物车商品和余额,并退出购物车程序
        else:
            print("The product_number is error!")
            # 商品编号有误
else:
    print("The amount entered is not a number!")
    # 金额有误

 这是学习老男孩教育Python课程的一个记录,我觉得该课程讲的挺好的。可参考金角大王Python之路02。

你可能感兴趣的:(购物车程序实现)