Python--作业1--购物车程序
程序:购物车程序
需求:
- 启动程序后,让用户输入工资,然后打印商品列表
- 允许用户根据商品编号购买商品
- 用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒
- 可随时退出,退出时,打印已购买商品和余额
=============方法1================双重列表=============方法1============
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author:Huanglinsheng product_list = [ ("IPhone", 5000), ("mac pro", 8900), ("bick", 800), ("watch", 10600), ("python book", 120), ] shopping_list = [] salary = input("input your salary:") if salary.isdigit(): salary = int(salary) while True: for index,item in enumerate(product_list): print(index,item) ''' for item in product_list: print(product_list.index(item),item) ''' user_choice = input("input the number of your choice:") #输入的是商品序号 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 your car,your courrent balance is \033[31;1m%s\033[0m"%(p_item,salary)) else:#买不起 print("\033[41;1m你的余额还剩%s是,请充值!\033[0m" % salary) break # 输入的商品不存在 else: print("the product of you input is not exit,place input again!") continue #用户需要退出的操作 elif user_choice == "q": for p in shopping_list: print(p) print("\033[41;1m你的账户余额还剩%s\033[0m" % salary) exit() else: print("input error, plase input again!")
=============方法2================字典和列表组合=============方法2============
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author:Huanglinsheng product_dict = {'iphone': 5000, 'mobike': 100, 'watch': 5000, 'computer': 15000} shopping_list = [] salary = int(input("Input your salary:")) # salary = input("Input your salary:") # if salary.isdigit(): # salary = int(salary) print("\033[33;1m商品列表如下:\033[0m:") for key in sorted(product_dict): print(key, product_dict[key]) while True: options = input('\033[32;1m选择要买的商品:\033[0m:') if options in product_dict.keys(): if salary >= product_dict[options]: shopping_list.append(options) salary -= product_dict[options] print("你已经成功购买了 [%s] 商品,账户余额为: \033[31;1m%d\033[0m" % (options, salary)) else: print("你的余额不足,无法购买该商品 [%s] 请充值!" % options) if salary >= min(product_dict.values()): print("你的钱还可以购买以下商品:") for hls in sorted(product_dict): if salary >= product_dict[hls]: print(hls, product_dict[hls]) else : print("你的账户余额不足于购买任何商品,请充值!") break tag = '' while True: flag = input("是否继续购买商品(Y/N):") if flag == "y": tag = True break elif flag == "n": tag = False break else: print("\033[31;1m你的输入有误,请重新输入:\033[0m:") continue if tag is True: continue else: break else: print("\033[31;1m你的商品输入有误,请重新输入:\033[0m:") continue if len(shopping_list) == 0: print("\033[31;1m穷逼没钱买东西\033[0m:") else: print("\033[33;1m你已经购买的商品列表如下:\033[0m:") for hc in shopping_list: print(hc) print("账户余额为: \033[31;1m%d\033[0m" % salary)
posted on 2018-07-24 14:34 huanglinsheng 阅读(159) 评论(0) 编辑 收藏 举报