python 基础 day02—training1_购物车程序练习

自学练习,记录下来,如有不对的地方,欢迎各位大神指出来!

程序:购物车程序

需求:

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

代码:

#cherry_cui

mall_list = [
    ('Bicycle',800),
    ('computer',4800),
    ('pizza',50),
    ('skirt',200),
    ('shoes',1200),
    ('iphone6',3200),
    ('watch',2700)
]
shopping_cart =[]
budget = input("Input your budget:")                                 #输入购物预算
if budget.isdigit():                                                   #判断budget 是否只由数字组成。
    budget = int(budget)                                               #转换成int类型

    while True:
        for num,item in enumerate(mall_list):                          # enumerate()获取mall_list的下标
            print(num,item)

        choice = input("which goods you want(enter the number):")  #输入需要购买的商品编号
        if choice.isdigit():                                           #判断choice 是否只由数字组成。
            choice = int(choice)                                       #转换成int类型

            if choice < len(mall_list) and choice >= 0:               #len() 方法返回mall_list列表元素个数
                u_item = mall_list[choice]
                if u_item[1]<=budget:
                    budget-=u_item[1]
                    shopping_cart.append(u_item)                       #把已购买的商品加入购物车shopping_cart
                    print("%s had added to your shopping list,your current balance is %s !" %(u_item[0],budget))

                else:
                    print("Your current balance is %s ,not enough to buy %s ,choose again!" %(budget,u_item[0]))

            else:
                print("Product code %s is not exist,choose again" %choice)


        elif choice == 'q':
            print("-----shopping_cart-----")
            for c in shopping_cart:
                print(c)

            print("Your current balance is %s" %budget)
            exit()


        else:
            print("Input error!")
            exit()


else:
    print("Input error!")
View Code

猜你喜欢

转载自www.cnblogs.com/cherrycui/p/8980903.html