1. 需求分析:
  • 输入工资,实现购物车购物
    • 请用户输入工资,然后选择需要购买的商品
      • 选择商品,对比是否能买得起商品,如果买得起,则钱数随着所购物品更新
      • 购买的商品和所剩余额保存到文件中
  1. 代码实现:
#!/usr/bin/python
#coding:utf-8

product_list = [
('Iphone X',9000),
('Mac',10000),
('Bike',1500),
('book',100),
('watch',3000)
]

shopping_list = []
file = "shopping.txt"
money = "money.txt"
name = "shopping list"
salary = raw_input("Plesse Input your salary: ").strip()
if salary.isdigit():
    salary = int(salary)

    while True:
        for index,item in enumerate(product_list):
            print index,item
        user_choice = raw_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 = salary - p_item[1]
                    with open(money,'a+') as f:
                        f.write(str(salary)+'\n')
                    print ("Added %s into shopping cart,your current balance is %s") %(p_item,salary)
                else:
                    print ("\033[42;1m你的余额还剩[%s],无法购买\033[0m" % salary)
            else:
                print ("你选择的商品%d不存在" % user_choice)
                exit()
        elif user_choice == "quit":
            print (name.center(50,"-"))
            for i in shopping_list:
                with open(file,'a+') as f:
                f.write(str(i)+'\n')
            print ("Your current balance:",salary)
            exit()
else:
    print "对不起,您输入的工资不是数字,已经强制退出!"