购物车程序

  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # @Time : 2018/3/6 21:01
  4. # @Author : hyang
  5. # @Site :
  6. # @File : shop_cart.py
  7. # @Software: PyCharm
  8.  
  9. """
  10. 购物车程序
  11. 数据结构:
  12. goods = [
  13. {"name": "电脑", "price": 1999},
  14. {"name": "鼠标", "price": 10},
  15. {"name": "游艇", "price": 20},
  16. {"name": "美女", "price": 998},
  17. ......
  18. ]
  19.  
  20. 功能要求:
  21. 基础要求:
  22.  
  23. 1、启动程序后,输入用户名密码后,让用户输入工资,然后打印商品列表
  24.  
  25. 2、允许用户根据商品编号购买商品
  26.  
  27. 3、用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒
  28.  
  29. 4、可随时退出,退出时,打印已购买商品和余额
  30.  
  31. 5、在用户使用过程中, 关键输出,如余额,商品已加入购物车等消息,需高亮显示
  32.  
  33. 扩展需求:
  34.  
  35. 1、用户下一次登录后,输入用户名密码,直接回到上次的状态,即上次消费的余额什么的还是那些,再次登录可继续购买
  36.  
  37. 2、允许查询之前的消费记录
  38. """
  39. import os
  40.  
  41. # 商品列表
  42. goods = [
  43. {"name": "电脑", "price": 1999},
  44. {"name": "鼠标", "price": 10},
  45. {"name": "游艇", "price": 20},
  46. {"name": "IPAD", "price": 1998},
  47. {"name": "手机", "price": 998},
  48. {"name": "玩具", "price": 50},
  49. {"name": "教科书", "price": 100}
  50. ]
  51.  
  52. last_shop = [] # 上次购买数据
  53. last_bal = [] # 得到每次购买余额
  54.  
  55. def is_shop(user):
  56. """
  57. 判断该用户是否已消费数据
  58. :param user:
  59. :return:
  60. """
  61. flg = False
  62. if os.path.exists(r"user_shop.txt"):
  63. # 查询用户有购买记录
  64. with open(r"user_shop.txt", "r", encoding='utf-8') as f:
  65. for line in f:
  66. if line.find(user) != -1:
  67. flg = True
  68. break
  69. else: # 创建空文件
  70. with open(r"user_shop.txt", "w", encoding='utf-8') as f:
  71. f.write("")
  72. return flg
  73.  
  74. def login():
  75. """
  76. 用户登录
  77. :return:
  78. """
  79. err_cnt = 0
  80. suc_user = '' # 返回成功登录用户
  81. # 判断锁标志
  82. while err_cnt < 3:
  83. user = input('输入用户名: ')
  84. pwd = input('输入密码: ')
  85. if user == 'alex' and pwd == '':
  86. print('登录成功')
  87. suc_user = user
  88. break
  89. else:
  90. print('登录失败')
  91. err_cnt += 1
  92. else:
  93. print('您登录失败已超过3次')
  94. return suc_user
  95.  
  96. def check_salary():
  97. """
  98. 检查收入
  99. :return:
  100. """
  101. while True:
  102. salary = input('输入工资: ')
  103. if salary.isdigit():
  104. break
  105. else:
  106. print('工资输入错误,请重新输入!')
  107. return int(salary)
  108.  
  109. def shop(user, salary):
  110. """
  111. 用户购物
  112. """
  113. shop_cart = [] # 购物车
  114. while True:
  115. print('-------商品列表--------')
  116. for index, value in enumerate(goods):
  117. print('商品编号:%s 商品名称:%s 商品价格:%s' % (index, value['name'], value['price']))
  118.  
  119. choice = input('输入商品编号:---输入q退出购买 ')
  120. if choice.isdigit():
  121. choice = int(choice)
  122. if 0 <= choice < len(goods):
  123. price = goods[choice]['price']
  124. if (salary - price) > 0:
  125. salary = salary - price
  126. shop_cart.append(goods[choice])
  127. print('\033[1;32;40m购买商品编号:%s 购买商品名称:%s 购买商品价格:%s\033[0m'
  128. % (choice, goods[choice]['name'], goods[choice]['price']))
  129. print('\033[1;32;40m工资余额=%s\033[0m' % salary)
  130. else:
  131. print('余额不足')
  132. continue
  133. else:
  134. print('商品编号不存在!')
  135.  
  136. elif choice == 'q':
  137. print('\033[1;31;40m-------本次购物退出--------\033[0m')
  138. if len(shop_cart) > 0:
  139. print('-------本次购买商品列表--------')
  140. with open(r"user_shop.txt", "a+", encoding='utf-8') as f:
  141. f.write("user:%s\n" % user)
  142. for value in shop_cart:
  143. shop_info = '购买商品名称:%s|购买商品价格:%s' % (value['name'], value['price'])
  144. print('\033[1;32;40m%s\033[0m' % shop_info)
  145. f.write(shop_info + "\n")
  146. bal_info = '工资余额:%s' % salary
  147. print('\033[1;32;40m%s\033[0m'% bal_info)
  148. f.write(bal_info + "\n")
  149. break
  150.  
  151. def get_shop(user):
  152. """
  153. 读取文件得到用户已消费数据
  154. :param user:
  155. :return:
  156. """
  157. flg = False
  158. resume_goods = [] # 消费商品
  159. with open(r"user_shop.txt", "r", encoding='utf-8') as f:
  160. for line in f:
  161. if line.find("购买") != -1:
  162. shop_li = line.split("|")
  163. resume_goods.append([shop_li[0].split(":")[1].strip(), shop_li[1].split(":")[1].strip()])
  164. elif line.find("余额") != -1:
  165. last_bal.append(line.split(":")[1].strip())
  166. print("\033[1;32;40m历史购物:%s\033[0m" % resume_goods) # 带绿色输出
  167. print('\033[1;32;40m还剩下余额:%s\033[0m' % last_bal[-1]) # 带绿色输出
  168.  
  169. if __name__ == '__main__':
  170. user = login()
  171. if user != '':
  172. print('{}登录成功'.format(user))
  173. while True:
  174. action = input('输入c查询消费记录,输入b购买商品,输入q退出:')
  175. if action == 'q':
  176. print('\033[1;31;40m---退出程序------\033[0m') # 带红色输出
  177. get_shop(user)
  178. break
  179. elif action == 'c':
  180. if is_shop(user):
  181. print("---查询之前的消费记录---")
  182. get_shop(user)
  183. else:
  184. print("---查询之前无消费记录---")
  185. elif action == 'b':
  186. if not is_shop(user):
  187. salary = check_salary()
  188. else:
  189. salary = int(last_bal[-1])
  190. print('您工资现有:', salary)
  191. shop(user, salary)

输出结果

三级菜单程序

  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. # @Time : 2018/3/1 9:38
  4. # @Author : hyang
  5. # @File : three_menu.py
  6. # @Software: PyCharm
  7. """
  8. 可依次选择进入各子菜单
  9. 可从任意一层往回退到上一层
  10. 可从任意一层退出程序
  11. """
  12. menu = {
  13. '北京':{
  14. '海淀':{
  15. '五道口':{
  16. 'soho':{},
  17. '网易':{},
  18. 'google':{}
  19. },
  20. '中关村':{
  21. '爱奇艺':{},
  22. '汽车之家':{},
  23. 'youku':{},
  24. },
  25. '上地':{
  26. '百度':{},
  27. },
  28. },
  29. '昌平':{
  30. '沙河':{
  31. '老男孩':{},
  32. '北航':{},
  33. },
  34. '天通苑':{},
  35. '回龙观':{},
  36. },
  37. '朝阳':{},
  38. '东城':{},
  39. },
  40. '上海':{
  41. '闵行':{
  42. "人民广场":{
  43. '炸鸡店':{}
  44. }
  45. },
  46. '闸北':{
  47. '火车站':{
  48. '携程':{}
  49. }
  50. },
  51. '浦东':{},
  52. },
  53. '山东':{},
  54. }
  55.  
  56. current_menu = menu # 当前菜单
  57. last_menu = [] # 上层菜单
  58. prompt = "输入菜单名,进入子菜单\n 输入'b',返回上层菜单\n 输入'q',退出程序\n"
  59. while True:
  60. if len(current_menu) == 0:
  61. print('已经到最底层,该菜单下无节点')
  62. else:
  63. for k in current_menu:
  64. print('菜单->', k)
  65. input_str = input(prompt).strip()
  66. if input_str == 'q':
  67. print('退出程序')
  68. break
  69. elif input_str in current_menu:
  70. last_menu.append(current_menu) # 保存上一层菜单
  71. current_menu = current_menu[input_str] # 保存当前层
  72. elif input_str == 'b':
  73. if len(last_menu) != 0:
  74. current_menu = last_menu.pop() # 弹出上一层菜单
  75. else:
  76. print('已经是顶层菜单')
  77. else:
  78. print('该节点菜单不存在')
  79. continue

python基础练习题的更多相关文章

  1. python基础练习题1

    深深感知python基础是有多么重要,Ljh说一定要多练题,so,我现在开始要每天打卡练习python.加油! 01:求‘1-100’的偶数和 #第一种解法: sum=0 num=0 while nu ...

  2. python基础练习题(九九乘法表)

    又把python捡起来了,动手能力偏弱,决定每日一练,把基础打好! ------------------------------------------------------------------ ...

  3. Python基础 练习题

    DAY .1 1.使用while循环输出 1 2 3 4 5 6     8 9 10 n = 1 while n < 11: if n == 7: pass else: print(n) n ...

  4. Python基础练习题100例(Python 3.x)

    1:题目:有四个数字:1.2.3.4,能组成多少个互不相同且无重复数字的三位数?各是多少? 程序分析:可填在百位.十位.个位的数字都是1.2.3.4.组成所有的排列后再去 掉不满足条件的排列. 程序源 ...

  5. python基础练习题30道

    1.执行python脚本的两种方式 答:1>可以在python /home/xxxx.py 2>cd /home    ./xxxx.py  因为py脚本里面指定了python解释器的位置 ...

  6. 08: python基础练习题

    1.while循环实现输出2 - 3 + 4 - 5 + 6 ... + 100 的和 # 使用while循环实现输出2 - 3 + 4 - 5 + 6 ... + 100 的和 s = 0 i = ...

  7. 『Python基础练习题』day02

    1.判断下列逻辑语句的True, False 1) 1 > 1 or 3 < 4 or 4 > 5 and 2 > 1 and 9 > 8 or 7 < 6 2) ...

  8. Python学习【day03】- Python基础练习题(列表、元组、字典)

    #!/usr/bin/env python # -*- coding:utf8 -*- # 1.有两个列表 # l1 = [11,22,33] # l2 = [22,33,44] # a.获取内容相同 ...

  9. Python学习【day02】- Python基础练习题

    #!/usr/bin/env python # -*- coding:utf8 -*- # 执行Python 脚本的两种方式 # 答:①在windows的cmd窗口下 > D:/Python/p ...

随机推荐

  1. win10安装elementary os双系统

    elementary os是ubuntu的一个分支,界面有点像苹果,比较漂亮.如图: 从已有的磁盘中划出一块空白分区,将elementary单独安装在这个分区里,这个分区需要比其他分区的剩余空间都要大 ...

  2. OpenLayer3调用天地图,拖拽后,地图消失的问题[已解决]

    拖拽后,地图直接消失了,而且右上角的坐标变成了NaN,NaN 后来经过测试发现,原来是自己封装有问题,坐标点一定要用parseFloat()转换下,但不清楚为什么页面刚开始加载的时候没有问题,总之能解 ...

  3. latex编辑器

    \prod \left ( a b c \right ) http://latex.codecogs.com/eqneditor/editor.php

  4. WinForm中使用DDE技术(含源码)

    提起DDE技术,相信很多人不知道是啥东东,尤其是90后的程序员们.不过,有时候这个东西还是有用处的,用一句话可以总结:实现Winform程序间的通信.比如:两个Winform程序A和B需要实现通信,用 ...

  5. Spring Boot 注解详解

    一.注解(annotations)列表 @SpringBootApplication:包含了@ComponentScan.@Configuration和@EnableAutoConfiguration ...

  6. 试用MarkDown

    自定义界面风格 可以在设置中选择日间,或者夜间模式进行定义.具体的定义项的说明,可以查看菜单栏 (Windows版本位于托盘按钮上) 自定义的帮助. MarkEditor几乎所有跟色彩有关的界面,都已 ...

  7. 如何通过以太坊智能合约来进行众筹(ICO)

    前面我们有两遍文章写了如何发行代币,今天我们讲一下如何使用代币来公开募资,即编写一个募资合约. 写在前面 本文所讲的代币是使用以太坊智能合约创建,阅读本文前,你应该对以太坊.智能合约有所了解,如果你还 ...

  8. ubuntu17 安装python3.6 pip

    安装python: wget https://www.python.org/ftp/python/3.6.3/Python-3.6.3.tgz .tgz cd Python- #安装编译依赖包 sud ...

  9. JVM笔记1-内存溢出分析问题与解决

    假设我们项目中JVM内存溢出了,大项目中上百万行代码,是很难定位的.因此我们需要借用一个Memory Analyzer工具, 官网地址为:http://www.eclipse.org/download ...

  10. Spring+SpringMVC+MyBatis+easyUI整合进阶篇(十四)Redis缓存正确的使用姿势

    作者:13 GitHub:https://github.com/ZHENFENG13 版权声明:本文为原创文章,未经允许不得转载. 简介 这是一篇关于Redis使用的总结类型文章,会先简单的谈一下缓存 ...