python实现购物简单流程

匿名 (未验证) 提交于 2019-12-02 22:51:30

需求:

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

python环境:3.6.5

知识点:if-else,for,while

代码:

#!/usr/bin/env python # -*- coding: UTF-8 -*- # Author:coding2018  ''' 需求:     1.启动程序后,让用户输入工资,然后打印商品列表     2.允许用户根据商品编号购买商品     3.用户选择商品后,检测余额时候够,够就直接扣款,不够就提醒     3.可随时退出,退出时,打印已购买商品和余额 '''  #商品列表 product_list = [     ('iPhone',5800),     ('Mac Pro',9800),     ('Bike',800),     ('Watch',10600),     ('Coffee',31),     ('Ales Python',120) ] #购物车 shopping_list = [] #输入工资 salary = input("Input your salary:") #isdigit() 方法检测字符串是否只由数字组成。 if salary.isdigit():     #salary转换成int型     salary = int(salary)     #循环     while True:         #取product_list中商品下标和商品         #enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)         # 组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中         for index,item in enumerate(product_list):             print(index,item)         print("q 退出")         # for item in product_list:         #     print(product_list.index(item),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("product code [%s] is not exist!" % user_choice)         elif user_choice == 'q':             print('--------------shopping list---------------')             for p in shopping_list:                 print(p)             print("Your current balance:",salary)             exit()         else:             print("invalid option")   else:     print("该输入不是只由数字组成")

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!