1 #!/usr/bin/python3

2 #coding:utf-8

3 from __future__ importprint_function4 importos5 importrandom6 importsys7 '''

8 需求功能点9 -------------------------------------------------------10 购物:11 1.用户输入工资、然后打印购物菜单12 2.用户可以不断的购买商品、知道钱不够为止13 3.退出时格式化打印用户已购买的商品和剩余金额14 -------------------------------------------------------15 '''

16

17 __author__ = 'luting'

18

19

20 classShop(object):21

22 def __init__(self):23 self.test_data = {'user': 'luting', 'password': '123456', 'current_balance': '20000'}24

25 @staticmethod26 defread_text(file_name):27 """

28 读取 文本29 :param file_name: 文件名 string类型30 :return: 返回文本值,list类型31 """

32 file_path =os.path.join(os.getcwd(), file_name)33 try:34 with open(file_path, 'rb') as file:35 context =file.readlines()36 if len(context) !=0:37 value_list =[]38 for value incontext:39 value_list.append((value.decode('utf-8')).strip())40 returnvalue_list41 else:42 print('\033[1;31;0m The file is empty!\033[0m')43 return[]44 exceptFileNotFoundError as error:45 print('\033[1;31;0mThe FileNotFoundError is: {0}\033[0m'.format(error))46

47 @staticmethod48 defwrite_txt(file_name, write_values):49 """

50 写入 文本51 :param file_name: 文件名 string类型52 :param write_values: 写入的文本值,string类型53 :return: 无返回值54 """

55 file_path =os.path.join(os.getcwd(), file_name)56 if os.path.exists(file_path) is False and os.path.isfile(file_path) isFalse:57 print('\033[1;31;0mFile name is Error\033[0m')58 else:59 with open(file_path, 'a') as file:60 file.write(write_values + '\n')61

62 @staticmethod63 defidentifying_code():64 """

65 验证码66 :return: 四位验证码 string类型67 """

68 code_num = random.randint(0, 9)69 letter =[]70 for i in range(3):71 for letter_value in chr(random.randint(65, 90)):72 letter.append(letter_value)73 code = str(code_num) + ''.join(letter)74 returncode75

76 deflogin_main(self):77 """

78 登录 逻辑79 :return: 无返回值80 """

81 lock_user = self.read_text('lock.txt')82 code =self.identifying_code()83 print('*******************************************************verification code is \033[31;1m%s\033[0m*******************************************************' %code)84 login_count =085 while login_count < 3:86 globalset_user87 set_user = str(input('Please input user name!')).strip()88 set_password = str(input('Please input user password!')).strip()89 set_code = str(input('Please enter the verification code!')).strip()90 if set_user inlock_user:91 input('\033[1;31;0mThe user has been locked!\033[0m')92 elif set_user == '' or set_password == '' or set_code == '':93 print('\033[1;31;0mThe input is empty!\033[0m')94 elif set_user not in self.test_data['user']:95 print('\033[1;31;0mUser name input error!\033[0m')96 elif set_user == self.test_data['user'] and set_password == self.test_data['password'] and set_code ==code:97 print('\033[31;1m*******************************************************%s,Welcome to the electronic mall!*******************************************************\033[0m' %set_user)98 print('\033[31m会员:%-20s当前余额:%s\033[0m' % (self.test_data['user'],self.test_data['current_balance']))99 self.shopping()100 break

101 else:102 print('You input user name :%s is error,please input again!also \033[31;1m%s \033[0m chance' % (set_code, 2 -login_count))103 login_count += 1

104 else:105 self.write_txt('lock.txt', set_user)106

107 defshopping(self):108 """

109 购物 逻辑110 :return: 无返回值111 """

112 buy_shop_list =[]113 print('\033[31m\n商品列表:\033[0m')114 whileTrue:115 goods = self.read_text('goods.txt')116 if notgoods:117 print('There is no goods')118 else:119 goods_dict ={}120 goods_list =[]121 for goods_value ingoods:122 goods_list.append((str(goods_value).strip('\n')).split('.'))123 for good_value ingoods_list:124 goods_dict[good_value[0]] = good_value[1]125 print('\033[31m*******************************************************\n编号:%-5s 商品名称:%-15s 商品价格:(元)\033[0m' % ('\t', '\t'))126 for key, value ingoods_dict.items():127 index, goods_name, goods_price = key, (str(value).split(',')[0]), (str(value).split(',')[1])128 print('\033[31m%-10s\t %-20s \t %s\033[0m' %(index, goods_name, goods_price))129 print('\033[31m*******************************************************\033[0m')130 break

131 now_monkey = int(self.test_data['current_balance'])132 whileTrue:133 buy_input = str(input('Enter the number to buy the goods')).strip()134 if buy_input == '':135 print('\033[31mThe input is empty,please again!\033[0m')136 elif buy_input not in [key for key ingoods_dict.keys()]:137 print('\033[31mInput error, please again!\033[0m')138 else:139 price ={}140 for key, value ingoods_dict.items():141 price[key] = str(value).split(',')[1]142 buy_price =price[buy_input]143 buy_shop =goods_dict[buy_input]144 if int(now_monkey) >=int(buy_price):145 now_monkey -=int(buy_price)146 buy_shop_list.append(buy_shop)147 print('purchase succeeded! you have %s ¥' %now_monkey)148 else:149 print('You poor force,get out!')150 whileTrue:151 quit_input = str(input('Do you want to log out Y or N')).strip()152 if quit_input == '':153 print('\033[31mThe input is empty,please again!\033[0m')154 elif quit_input not in ['Y', 'N']:155 print('\033[31mInput error, please again!\033[0m')156 elif quit_input == 'Y':157 print(158 '\033[31m购买的商品:\n*******************************************************\n商品名称:%-15s 商品价格:(元)\033[0m' % '\t')159 if len(buy_shop_list) ==0:160 break

161 else:162 shop_list =[]163 for value inbuy_shop_list:164 shop_list.append(str(value).split(','))165 for shop_value inshop_list:166 print('\033[31m%-20s \t %s\033[0m' % (shop_value[0], shop_value[1]))167 sys.exit()168 else:169 break

170

171 if __name__ == '__main__':172 shop =Shop()173 shop.login_main()

python可以处理的文件类型_Python学习笔记之数据类型与文件处理相关推荐

  1. python读取mdb文件显示_Python学习笔记(读mdb文件)

    1. 读取一个文件夹里所有文件名字 ① os.listdir(path) 仅当前路径下的文件名,不包括子目录中的文件 import os s_path = r'C:\Users\Desktop\标准文 ...

  2. python目录和文件的基本操作_python学习笔记(七)——文件和目录操作

    目录和文件操作 语言只有和外部连起来操作才会实现更强大的功能,比如操作文件.数据库等,这样数据可以有一块单独存储的地方,而不是存放在内存中.更强大的是网络编程,当然这些后续都会学习.接下来学习pyth ...

  3. python如何区分文件类型_Python库 使用filetype精确判断文件类型

    一个小巧自由开放Python开发包,主要用来获得文件类型. filetype支持版本: python2/python3 filetype安装: pip install filetype filetyp ...

  4. python怎么写入到文件中_Python学习笔记之将数据写入到文件中

    原博文 2019-10-29 16:04 − 10-3 访客:编写一个程序,提示用户输入其名字:用户作出响应后,将其名字写入到文件guest.txt 中. 编写Python代码: 1 username ...

  5. python列表和元组的应用_python学习笔记之列表(list)与元组(tuple)详解

    前言 最近重新再看python的基础知识,感觉自己还是对于这些知识很陌生,需要用的时候还是需要翻书查阅,还是先注重基础吧--我要重新把python的教程阅读一遍,把以前自己忽略的部分学习,加强练习和记 ...

  6. python文本进度条94页_Python学习笔记 | 实例4:文本进度条

    本文为中国大学MOOC<Python语言程序设计>课程学习笔记,课程主讲:嵩天老师,练习平台:Python123,参考教材:<Python语言程序设计基础> 文本进度条-简单的 ...

  7. python2 float类型_Python学习笔记2:基本数据类型

    Python中的变量不需要声明.每个变量在使用前都必须赋值,变量赋值以后该变量才会被创建. 在 Python 中,变量就是变量,它没有类型,我们所说的"类型"是变量所指的内存中对象 ...

  8. python爬取基金历史净值_Python学习笔记之抓取某只基金历史净值数据实战案例

    摘要:这篇Python开发技术栏目下的"Python学习笔记之抓取某只基金历史净值数据实战案例",介绍的技术点是"Python学习笔记.Python.历史净值数据.学习笔 ...

  9. 88是python语言的整数类型_Python学习系列之数据类型(三)

    一.Python中的数据类型 常用数据类型: 整数类型:int 浮点类型:float 布尔类型:bool(True,False) 字符串类型:str 1.整数类型: 英文未integer,简写为int ...

最新文章

  1. 用TVM在硬件平台上部署深度学习工作负载的端到端 IR 堆栈
  2. python 读取文件到字典读取顺序_python_实现dictionary按照输入顺序输出
  3. ajax兼容低版本浏览器
  4. 数组中元素的动态增加和删除
  5. winhex教程 转
  6. 碰撞次数与π的关系问题程序求解
  7. matlab最大回撤值,用matlab计算区间最大回撤值和最大回撤率
  8. 【API调用】人脸检测+人脸属性(旷视 / 百度)
  9. 学计算机Java和c语言哪个出路比较好
  10. 长春有学计算机的中专吗,长春比较好的中专学校
  11. gms认证流程_【热点资讯】详解Google GMS认证流程可大大缩短终端手机上市时间...
  12. PAT-L2-027(名人堂与代金券)(结构体排序)
  13. Elasticsearch 8.x 破解x-pack-core
  14. windows下配置安装 Mycat详细步骤
  15. 【Java并发编程实战】(十七):Future和CompletableFuture的原理及实战——异步编程没有那么难
  16. SET NOCOUNT { ON | OFF }
  17. 计算机网络课程背景,课程发展的历史沿革
  18. WIN10按shift取消大写锁定(非Caps Lock设置和粘滞键)
  19. 3年外包裸辞,面试阿里、字节全都一面挂,哭死.....
  20. 怎么恢复三星全智能手机数据

热门文章

  1. day22,ConfigParser,subprocess,xlrd三个模块
  2. ubuntu 18.04下 配置qt opencv的坑
  3. 深入理解BodyTagSupport,包括SKIP_PAGE, EVAL_PAGE等
  4. Razor 中的@rendersection
  5. json序列化后日期如何变回来
  6. 解决fatal: unable to connect to github.com问题
  7. sqlserver2008安装报错 “Previous releases of Microsoft Visual Studio 2008″ failed.
  8. Java SSM框架学习之Mybatis篇
  9. python提醒事件_监控服务器空间使用情况-crontab+python邮件提醒
  10. python删除首行_Python删除文件第一行