设为首页 收藏本站
查看: 901|回复: 0

[经验分享] Python-w2

[复制链接]
YunVN网友  发表于 2018-8-12 09:15:09 |阅读模式
  一个购物车实例,大量的列表,字典,文件互相写入,读取操作。
  对于嵌套字典的取值,比较繁琐。
  该程序功能较为单一,代码了较大,没有使用函数,有很多地方可以改进。
  #!/usr/bin/env python
  # -*- coding: utf-8 -*-
  import os,sys,time
  # init menu prod list
  _prod_list = []
  # init a shopping cart
  _shopping_his = []
  _shopping_cart = []
  # init user info list
  _user = {}
  # load prod list
  if not os.path.exists("w2_prod.txt"):
  open("w2_prod.txt", "w").close()
  else:
  with open("w2_prod.txt","r") as prod_list:
  lines = prod_list.readlines()
  if lines:
  print("Load prod list...")
  for line in lines:
  _prod_list.append(line.strip())
  else:
  print("Nothing in prod list. Please import production with the format: prod_name,prod_price")
  exit()
  # create user list and buy list
  if not os.path.exists("w2_user.txt"):
  open("w2_user.txt","w").close()
  if not os.path.exists("w2_buy.txt"):
  open("w2_buy.txt","w").close()
  # init user info
  with open("w2_user.txt","r+") as names:
  lines = names.readlines()
  if lines:
  print("Load user information...")
  for i in range(len(lines)):
  _user[str(i)] = {}
  (_id,_uname,_upwd,_ustate,_ubalance) = lines.strip().split(",",5)
  _user[str(i)]["name"] = _uname
  _user[str(i)]["password"] = _upwd
  _user[str(i)]["state"] = _ustate
  _user[str(i)]["balance"] = int(_ubalance)
  else:
  print("It is empty")
  print("Hello, it is your first time to access....")
  print("Please enter your information:")
  _name = input("Name:")
  _pwd = input("Password:")
  _state = 'enable'
  _salary = int(input("Salary:"))
  _uid = str(len(_user))
  names.write("%s,%s,%s,%s,%d" %(_uid,_name,_pwd,_state,_salary))
  #load user info
  _user[_uid] = {}
  _user[_uid]["name"] = _name
  _user[_uid]["password"] = _pwd
  _user[_uid]["state"] = _state
  _user[_uid]["balance"] = _salary

  #login system and user>  print("Login".center(30,"="))
  _name = input("Name:")
  with open("w2_user.txt", "r") as users:
  lines = users.readlines()
  for i in range(len(lines)):
  if _name == _user[str(i)]["name"]:
  _pwd = input("password:")
  if _pwd == _user[str(i)]["password"]:
  print("Welcome to login !")
  else:
  print("The password is error...")
  exit()
  else:
  print("The user is not exist.")
  exit()
  #load shopping cart
  with open("w2_buy.txt","r") as buy_lists:
  lines =  buy_lists.readlines()
  if lines:
  print("\033[1;37;44m Shopping_History \033[0m ".center(30,"="))
  for i in lines:
  _shopping_his.append(i.strip())
  print("\033[1;37;44m",_shopping_his,"\033[0m")
  else:
  print("Nothing in shopping cart".center(40,"="))
  #load balance
  _balance = []
  for i in _user.keys():
  balance = int(_user["balance"])
  _balance.append(balance)
  print("\033[1;31m Balance:",_balance,"\033[0m")
  balance = int(_balance[0])
  while True:
  # load prod list
  print("The Production List".center(30,"="))
  for index, menu_list in enumerate(_prod_list):
  print(index, menu_list)
  #user operation
  _select1 = input("Your selection[History:h|Recharge:r|Quit:q]:")
  if _select1.isdigit():
  _select1 = int(_select1)
  if _select1 > -1 and _select1 <= len(_prod_list):
  (pname,pprice) = str(_prod_list[_select1]).strip().split(",")
  pprice = int(pprice)
  for i in _user.keys():
  balance = _user[str(i)]["balance"]
  print(balance)
  print(pprice)
  if balance >= pprice:
  balance -= pprice
  print("\033[1;34m Add %s to shopping cart. \033[0m" %pname)
  _shopping_cart.append(pname)
  print("\033[1;35m Shopping_Cart:",_shopping_cart,"\033[0m")
  print("Shopping His:",_shopping_his)
  print("\033[1;31m Balance RMB:",balance,"\033[0m")
  for i in _user.keys():
  _user["balance"] = balance
  else:
  print("\033[1;31m Balance is not enough.\033[0m")
  continue
  else:
  print("\033[1;31m It is out of range! \033[0m")
  elif _select1 == "q":
  print("\033[1;35m Total:", _shopping_cart, "\033[0m")
  print("Saving summary report of \033[1;31m w2_report.txt \033[0m ...")
  for i in range(20):
  sys.stdout.write("#")
  sys.stdout.flush()
  time.sleep(0.2)
  #build report
  shopping = _shopping_cart+_shopping_his
  item = set(shopping)
  with open("w2_report.txt","w") as report:
  for i in item:
  print(i,shopping.count(i),file=report)
  #update user info
  for i in _user.keys():
  _quid = i
  _qname = _user[str(i)]["name"]
  _qpassword = _user[str(i)]["password"]
  _qstate = _user[str(i)]["state"]
  _qbalance = _user[str(i)]["balance"]
  with open("w2_user.txt","w+") as names:
  names.write("%s,%s,%s,%s,%d" %(_quid,_qname,_qpassword,_qstate,_qbalance) )
  #store prod in file
  with open("w2_buy.txt","a") as saves:
  for i in _shopping_cart:
  print(i,file=saves)
  exit()
  elif _select1 == "h":
  print("\033[1;37;44m You had got items before:",_shopping_his,"\033[0m")
  elif _select1 == "r":
  _money = input("How much cash do you want to add:")
  if _money.isdigit():
  _money = int(_money)
  for i in _user.keys():
  _user[str(i)]["balance"] = int(_user[str(i)]["balance"]) + _money
  print(_user[str(i)]["balance"])
  break
  else:
  print("\033[1;31m It is not a digit! \033[0m")
  continue
  else:
  print("\033[1;31m It is not a digit! \033[0m")

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-550455-1-1.html 上篇帖子: Python要self的理由 下篇帖子: python列表(Lists)
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表