Python购物车小程序

版权声明:本文为博主原创文章,未经博主允许不得转载。不准各种形式的复制及盗图 https://blog.csdn.net/qq_26816591/article/details/88085973

问题描述:

商店有一系列商品,给出购买序列,然后输入你的金额,然后选择要购买的商品序号或是退出,如果持续购买余额不足则提醒用户余额不足,然后如果用户退出则打印用户购买的商品列表,并打印用户余额。

# 购物车程序
product_list = [
    ('Mac', 9000),
    ('Kindle', 8000),
    ('tesla', 900000),
    ('Python_book', 105),
    ('bike', 2000),
]
shopping_car = []  # 购物车
money = input('please input your money')  # 你的金钱
if money.isdigit():
    money = int(money)
    # for i in product_list:#方法一:
    #     print(product_list.index(i)+1,':',i)
    #
    # for i in enumerate(product_list,1): #方法二:    enumerate()带索引的打印  下标从1开始,不加1,默认从0开始。
    #     print(i)
    while True:
        for i, v in enumerate(product_list, 1):  # 方法三: 方法二 打印的是一个个元组,我们用两个变量i,v接收元组
            print(i, v)
        choice = input('please input the num[exit:q]')
        if choice.isdigit():
            choice = int(choice)
            if (choice >= 1) and (choice <= len(product_list)):  # 求列表的长度
                p_item = product_list[choice - 1]
                p_price = float(p_item[1])
                if p_price < money:
                    money -= p_price
                    shopping_car.append(p_item)
                else:
                    print('your money is not enough %s' % money)
                print(p_item, p_price)
            else:
                print('编码不存在!')
        elif choice == 'q':
            print('您购买的商品如下:')
            for i, v in enumerate(shopping_car, 1):  # 方法三: 方法二打印的是一个个元组,我们用两个变量i,v接收元组
                print(i, v)
            print('您还剩余%s元' % money)
            break
        else:
            print('input invalid')
else:
    print('your input is not reasonable')

 要点:

  • a=[('Mac',9000),('bike',1000)] 列表的使用
  • a.isdigit() 输入是否是数字判断函数
  • for i,v in enumerate(a,1)  定义两个变量 带索引的遍历 1 表示索引值从1开始,默认从0开始 i为索引 v为元组元素
  • len(a) 表示列表长度
  • shopping_car.append(b) 向shopping_car 追加b
  • print('%s' % item) 占位符的使用
  • break 退出循环或判断 到上一层

猜你喜欢

转载自blog.csdn.net/qq_26816591/article/details/88085973