【Python学习】程序练习《购物车程序》

【Python学习】程序练习《购物车程序》

需求:

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

补充知识

#       for index,item in enumerate(product_list)

enumerate的作用,就是取出出来下标!取代index每次都要寻找使效率低下!

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-iVWgrvOR-1602765340716)(F:\博客\day02\3.jpg)]product_list = [
     ('Iphone',5800),
     ('Mac PrO',9800),
     ('Bike',800),
     ('Watch',10600),
     ('coffee',31),
     ('python',120),
]
shopping_list = []

salary = input("输入你的钱:")
if salary.isdigit():
    salary = int(salary)
    while True:
        for index,item in enumerate(product_list):
            print(index,item)
        user_choice = input("选择要买什么?:>>>")
        if user_choice.isdigit():
            user_choice = int(user_choice)
            if user_choice < len(product_list) and user_choice >=0:
                p_item = product_list[user_choice]
                if p_item[1]<=salary:    #买得起
                    shopping_list.append(p_item)
                    salary -= p_item[1]
                    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("你选的商品不正确!请重新选择!")
        elif user_choice == 'q':
            print("------------shopping_list--------------")
            for p in  shopping_list:
                print(p)
            print("你的余额:",salary)
            exit()
        else:
            print("输入错误")

数字染色小知识

在这里插入图片描述

上述代码分块剖析!
在这里插入图片描述

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_45571972/article/details/109104956