侯体宗的博客
  • 首页
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

Python 模拟购物车的实例讲解

Python  /  管理员 发布于 7年前   170

1.功能简介

此程序模拟用户登陆商城后购买商品操作。可实现用户登陆、商品购买、历史消费记查询、余额和消费信息更新等功能。首次登陆输入初始账户资金,后续登陆则从文件获取上次消费后的余额,每次购买商品后会扣除相应金额并更新余额信息,退出时也会将余额和消费记录更新到文件以备后续查询。

2.实现方法

架构:

本程序采用python语言编写,将各项任务进行分解并定义对应的函数来处理,从而使程序结构清晰明了。主要编写了六个函数:

(1)login(name,password)

用户登陆函数,实现用户名和密码验证,登陆成功则返回登陆次数。

(2)get_balance(name)

获取用户余额数据。

(3)update_balance(name,balance)

更新用户余额数据,当用户按q键退出时数据会更新到文件。

(4)inquire_cost_record(name)

查询用户历史消费记录。

(5)update_cost_record(name,shopping_list)

更新用户消费记录,当用户按q键退出时本次消费记录会更新到文件。

(6)shopping_chart()

主函数,完成人机交互,函数调用,各项功能的有序实现。

主要操作:

(1)根据提示按数字键选择相应选项进行操作。

(2)任意时刻按q键退出退出登陆,退出前会完成用户消费和余额信息更新。

使用文件:

(1)userlist.txt

存放用户账户信息文件,包括用户名、密码、登陆次数和余额。每次用户登陆成功会更新该用户登陆次数,每次按q键退出时会更新余额信息。

(2)***_cost_record.txt

存放某用户***消费记录的文件,用户首次购买商品后创建,没有购买过商品的用户不会产生该文件。每次按q键退出时会将最新的消费记录更新到文件。

3.流程图

4.代码

# Author:Byron Li#-*-coding:utf-8-*-'''----------------------------------------------使用文件说明----------------------------------------------------------使用文件说明userlist.txt     存放用户账户信息文件,包括用户名、密码、登陆次数和余额***_cost_record.txt 存放某用户***消费记录的文件,用户首次购买商品后创建,没有购买过商品的用户不会产生该文件---------------------------------------------------------------------------------------------------------------------'''import osimport datetimedef login(name,password):  #用户登陆,用户名和密码验证,登陆成功则返回登陆次数  with open('userlist.txt', 'r+',encoding='UTF-8') as f:    line = f.readline()    while(line):      pos=f.tell()      line=f.readline()      if [name,password] == line.split()[0:2]:        times=int(line.split()[2])        line=line.replace(str(times).center(5,' '),str(times+1).center(5,' '))        f.seek(pos)        f.write(line)        return times+1  return Nonedef get_balance(name):  #获取用户余额数据  with open('userlist.txt', 'r',encoding='UTF-8') as f:    line = f.readline()    for line in f:      if name == line.split()[0]:        return line.split()[3]  print("用户%s不存在,无法获取其余额信息!"%name)  return Falsedef update_balance(name,balance):  #更新用户余额数据  with open('userlist.txt', 'r+',encoding='UTF-8') as f:    line = f.readline()    while(line):      pos1=f.tell()      line=f.readline()      if name == line.split()[0]:        pos1=pos1+line.find(line.split()[2].center(5,' '))+5        pos2=f.tell()        f.seek(pos1)        f.write(str(balance).rjust(pos2-pos1-2,' '))        return True  print("用户%s不存在,无法更新其余额信息!" % name)  return Falsedef inquire_cost_record(name):   #查询用户历史消费记录  if os.path.isfile(''.join([name,'_cost_record.txt'])):    with open(''.join([name,'_cost_record.txt']), 'r',encoding='UTF-8') as f:      print("历史消费记录".center(40, '='))      print(f.read())      print("".center(46, '='))      return True  else:    print("您还没有任何历史消费记录!")    return Falsedef update_cost_record(name,shopping_list):  #更新用户消费记录  if len(shopping_list)>0:    if not os.path.isfile(''.join([name, '_cost_record.txt'])):   #第一次创建时第一行标上“商品 价格”      with open(''.join([name, '_cost_record.txt']), 'a',encoding='UTF-8') as f:        f.write("%-5s%+20s\n" % ('商品', '价格'))        f.write(''.join([datetime.datetime.now().strftime('%c'), ' 消费记录']).center(40,'-'))  #写入消费时间信息方便后续查询        f.write('\n')        for product in shopping_list:          f.write("%-5s%+20s\n"%(product[0],str(product[1])))    else:      with open(''.join([name, '_cost_record.txt']), 'a',encoding='UTF-8') as f:        f.write(''.join([datetime.datetime.now().strftime('%c'), ' 消费记录']).center(40, '-'))        f.write('\n')        for product in shopping_list:          f.write("%-5s%+20s\n"%(product[0],str(product[1])))    return True  else:    print("您本次没有购买商品,不更新消费记录!")    return Falsedef shopping_chart():  #主函数,用户交互,函数调用,结果输出  product_list=[    ('Iphone',5000),    ('自行车',600),    ('联想电脑',7800),    ('衬衫',350),    ('洗衣机',1000),    ('矿泉水',3),    ('手表',12000)  ]  #商店商品列表  shopping_list=[]  #用户本次购买商品列表  while(True):    username = input("请输入用户名:")    password = input("请输入密码:")    login_times=login(username,password)  #查询输入用户名和密码是否正确,正确则返回登陆次数    if login_times:      print('欢迎%s第%d次登陆!'.center(50,'*')%(username,login_times))      if login_times==1:        balance = input("请输入工资:")  #第一次登陆输入账户资金        while(True):          if balance.isdigit():balance=int(balance)break          else:balance = input("输入工资有误,请重新输入:")      else:        balance=int(get_balance(username)) #非第一次登陆从文件获取账户余额      while(True):        print("请选择您要查询消费记录还是购买商品:")        print("[0] 查询消费记录")        print("[1] 购买商品")        choice=input(">>>")        if choice.isdigit():          if int(choice)==0:         #查询历史消费记录inquire_cost_record(username)          elif int(choice)==1:        #购买商品while (True):  for index,item in enumerate(product_list):    print(index,item)  choice=input("请输入商品编号购买商品:")  if choice.isdigit():    if int(choice)>=0 and int(choice)<len(product_list):      if int(product_list[int(choice)][1])<balance:  #检查余额是否充足,充足则商品购买成功        shopping_list.append(product_list[int(choice)])        balance = balance - int(product_list[int(choice)][1])        print("\033[31;1m%s\033[0m已加入购物车中,您的当前余额是\033[31;1m%s元\033[0m" %(product_list[int(choice)][0],balance))      else:        print("\033[41;1m您的余额只剩%s元,无法购买%s!\033[0m" %(balance,product_list[int(choice)][0]))    else:      print("输入编号错误,请重新输入!")  elif choice=='q':   #退出账号登陆,退出前打印本次购买清单和余额信息,并更新到文件    if len(shopping_list)>0:      print("本次购买商品清单".center(50,'-'))      for product in shopping_list:        print("%-5s%+20s"%(product[0],str(product[1])))      print("".center(50, '-'))      print("您的余额:\033[31;1m%s元\033[0m"%balance)      update_cost_record(username,shopping_list)      update_balance(username, balance)      print("退出登陆!".center(50, '*'))      exit()    else:      print("您本次没有消费记录,欢迎下次购买!")      print("退出登陆!".center(50, '*'))      exit()  else:    print("选项输入错误,请重新输入!")          else:print("选项输入错误,请重新输入!")        elif choice=='q':  #退出账号登陆          print("退出登陆!".center(50, '*'))          exit()        else:          print("选项输入错误,请重新输入!")      break    else:      print('用户名或密码错误,请重新输入!')shopping_chart() #主程序运行

以上这篇Python 模拟购物车的实例讲解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。


  • 上一条:
    Python模拟三级菜单效果
    下一条:
    python添加模块搜索路径方法
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在python语言中Flask框架的学习及简单功能示例(0个评论)
    • 在Python语言中实现GUI全屏倒计时代码示例(0个评论)
    • Python + zipfile库实现zip文件解压自动化脚本示例(0个评论)
    • python爬虫BeautifulSoup快速抓取网站图片(1个评论)
    • vscode 配置 python3开发环境的方法(0个评论)
    • 近期文章
    • 在windows10中升级go版本至1.24后LiteIDE的Ctrl+左击无法跳转问题解决方案(0个评论)
    • 智能合约Solidity学习CryptoZombie第四课:僵尸作战系统(0个评论)
    • 智能合约Solidity学习CryptoZombie第三课:组建僵尸军队(高级Solidity理论)(0个评论)
    • 智能合约Solidity学习CryptoZombie第二课:让你的僵尸猎食(0个评论)
    • 智能合约Solidity学习CryptoZombie第一课:生成一只你的僵尸(0个评论)
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(95个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2018-04
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2022-01
    • 2023-07
    • 2023-10
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客