Python 实现购物商城,含有用户入口和商家入口的示例


Posted in Python onSeptember 15, 2017

这是模拟淘宝的一个简易的购物商城程序。

用户入口具有以下功能:

登录认证

可以锁定用户

密码输入次数大于3次,锁定用户名

连续三次输错用户名退出程序

可以选择直接购买,也可以选择加入购物车

用户使用支付密码完成支付,支付密码连续输入错误达3次,锁定用户名

商家入口具有以下功能:

登录认证

可以锁定用户

密码输入次数大于3次,锁定用户名

连续三次输错用户名退出程序

商家可以编辑商品

上架新品

下架商品

修改商品信息:商品名、单价、库存

每个用户的用户名、密码、余额、支付密码,以行记录定义在 user_list.txt 文件中,以逗号分隔;

每件商品的商品名、单价、库存,以行记录定义在 product_list.txt 文件中,以逗号加一个空格分隔;

被锁定用户名记录在 lock_list.txt 文件中,以行分隔;

商家的用户名、密码定义在 seller_list.txt 文件中,以逗号分隔;

# Joe Young

import getpass
import os

# 调用os模块的system方法传入'cls'参数,清屏
os.system('cls') 

while True:
 entrance = input('请选择:\n\t1. 用户登陆\n\t2. 商家登陆\n>>>')
 if entrance != '1' and entrance != '2':
  print('\n输入有误,请重试...\n')
 else:
  break

# 打印商品列表
def print_product_list():
 index = 1
 with open('product_list.txt', 'r') as product_file:
  for product_line in product_file:
   L = [commodity, price, stock] = product_line.strip('\n').split(', ')
   commodity_list.append(L)
   print((str(index) + '. ' + commodity).ljust(20) + ('单价:' + price + '元').ljust(15) + '库存:' + stock)
   index += 1
 return

# 用户入口
if entrance == '1':

 info = []   # 存放用户的信息,初始为空
 if_payed = True # if_payed 表示订单是否已支付
 username = ''

 # 登录接口
 count = 0
 while count < 3:
  username = input('\n用户名: ')

  # 打开锁定列表文件
  with open('lock_list.txt', 'r+') as lock_file: 
   for lock_line in lock_file:
    # 用户名在锁定名单里面,则退出程序
    if username == lock_line.strip('\n'): 
     exit('\n用户名 %s 已被锁定,请联系管理员...' % username)

  login = False # 登录标志,初始为False

  # 打开用户名列表文件,读权限
  user_file = open('user_list.txt', 'r')  

  for user_line in user_file:
   # 获取每行的用户信息,用户名、密码、余额、支付密码,存入info列表
   info = [user, passwd, balance, pay_passwd] = user_line.strip('\n').split(',')
   # 用户名匹配,则进入密码输入环节
   if user == username: 
    n = 0
    # 3次输入机会
    while n < 3: 
     password = getpass.getpass('密码: ')
     # 密码匹配,显示登录成功
     if passwd == password: 
      print('\n欢迎 %s 登录商城,祝您购物愉快!\n' % username)
      login = True  # 登录标志赋值为True
      break
     # 密码不匹配
     else: 
      # n = 2 时是最后一次机会,不必提示还剩下0次机会
      if n != 2: 
       print('\n密码错误,请重新输入,您还有 %d 次机会\n' % (2-n))
     n += 1
    # 密码错误次数达到3次,锁定用户名,退出程序
    else: 
     open('lock_list.txt', 'w').write(username + '\n')
     exit('\n错误次数过多,账户已被锁定...')

    # 登录成功,跳出for循环
    if login: 
     break
  else:
   if count != 2:
    print('\n用户名不存在,请重试,您还有 %d 次机会' % (2-count))

  user_file.close()

  count += 1

  # 登录成功,跳出while循环
  if login: 
   break

 else:
  exit('\n错误次数过多,程序已退出...')

 # 购买程序
 shopping_cart = [] # 购物车初始为空
 commodity_list = []

 print_product_list()

 while True:
  i = input('\n请选择商品(输入序号),或输入 c 取消购买:')

  if i == 'c':
   while True:
    a = input('\n是否继续购买?(Y/N):')
    if a == 'n' or a == 'N':
     exit('\n交易结束...')
    elif a == 'y' or a == 'Y':
     break
    else:
     print('\n输入格式有误,请重试...')
     continue

  if not i.isdigit():
   print('\n输入格式有误,请重试...')
   continue

  i = int(i)

  if i <= 0 or i > len(commodity_list):
   print('\n此商品不存在,请重试...')
   continue

  item_name = commodity_list[i-1][0]  # 商品名称
  item_price = commodity_list[i-1][1]  # 商品价格
  item_stock = commodity_list[i-1][2]  # 商品库存

  print('\n您已选择了 %s ,请输入购买的数量,或输入 b 重新选择:' % item_name)

  back = False

  while True:
   num = input('>>>')
   if num == 'b':
    back = True
    break
   if not num.isdigit():
    print('输入格式有误,请重试...')
    continue
   if int(num) > int(item_stock):
    print('数量大于库存,请重试...')
    continue
   if int(num) == 0:
    print('数量应大于0,请重试...')
   break
  if back:
   continue

  item = [item_name, item_price, num]

  print('\n您已选择了 %s,单价:%s 元,数量:%s,您想立即购买还是加入购物车?\n' % (item_name, item_price, num))
  print('\t1. 立即购买\n\t2. 加入购物车\n')

  while True:
   choice = input('>>>')
   if not (choice == '1' or choice == '2'):
    print('输入有误,请重试...')
    continue
   break

  user_balance = int(info[2])

  # 立即购买
  if choice == '1': 
   amount = int(item_price) * int(num)
   count = 0
   cancel = False

   while count < 3:
    user_pay_passwd = getpass.getpass('\n请输入支付密码,或输入 c 放弃支付:')
    if user_pay_passwd == 'c':
     print('\n取消支付成功...')
     cancel = True
     break
    elif user_pay_passwd != info[3]:
     if count != 2:
      print('\n密码错误,请重试,您还有 %d 次机会...' % (2-count))
     count += 1
    else:
     break

   if count == 3:
    with open('lock_list.txt', 'w') as lock_file:
     lock_file.write(username + '\n')
    exit('密码错误,账户已被锁定...')

   if cancel:
    while True:
     choice = input('\n是否继续购买?(Y/N):')
     if not (choice == 'Y' or choice == 'y' or choice == 'N' or choice == 'n'):
      print('\n输入格式有误,请重试...')
      continue
     break
    if choice == 'Y' or choice == 'y':
     continue
    else:
     break

   # 如果用户的账户余额大于总金额
   if user_balance >= amount: 
    user_balance -= amount
    print('\n支付成功!您已成功购买 %s ,单价:%s 元,数量:%s,总金额:%s 元,账户余额:%s 元'
      % (item_name, item_price, num, amount, user_balance))
    lines = open('product_list.txt', 'r').readlines()
    # 定位到用户所购买的商品所在行,分割成列表赋值给select
    select = lines[i-1].strip('\n').split(', ')    
    # 修改商品的库存
    select[-1] = (str(int(select[-1]) - int(num)) + '\n') 
    # 拼接成字符串
    lines[i-1] = ', '.join(select)       
    # 将修改写回文件
    open('product_list.txt', 'w').writelines(lines)   

    lines = open('user_list.txt', 'r').readlines()
    # 修改用户余额
    for line in lines: 
     if username in line.split(','):  # 定位到用户名所在行
      j = lines.index(line)   # 获取用户名所在行的行号索引
      select = line.split(',')  # 分割用户名所在行赋值给列表select
      select[-2] = str(user_balance) # 修改用户余额
      lines[j] = ','.join(select)  # 修改后的列表拼接成字符串,覆盖用户名所在行
      open('user_list.txt', 'w').writelines(lines) # 将修改写回文件
   else:
    print('\n对不起,您的余额不足...')

  else: # 加入购物车
   j = 0
   for j in range(len(shopping_cart)):
    # 如果商品在购物车里面,更新商品数量
    if item_name in shopping_cart[j]: 
     shopping_cart[j][2] = str(int(shopping_cart[j][2]) + int(num))
     break
   # 商品若不在购物车,则添加到购物车
   else:
    shopping_cart.append(item) 
   print('\n成功加入购物车!')

  while True:
   choice = input('\n是否继续购买?(Y/N):')
   if not (choice == 'Y' or choice == 'y' or choice == 'N' or choice == 'n'):
    print('\n输入格式有误,请重试...')
    continue
   break

  if choice == 'Y' or choice == 'y':
   continue
  else:
   break

 # 如果购物车不为空
 if shopping_cart: 
  print('\n您的购物车里有以下宝贝:\n')
  i = 1
  total_sum = 0
  for item in shopping_cart:
   (commodity, price, number) = (item[0], item[1], item[2])
   print((str(i) + '. ' + commodity).ljust(20) + ('单价:' + price + ' 元').ljust(15) + '数量:' + number)
   total_sum += int(price) * int(number)
   i += 1
  print('\n合计:%d 元' % total_sum)

  while True:
   if_buy = input('\n是否结算?(Y/N):')
   if not (if_buy == 'Y' or if_buy == 'y' or if_buy == 'N' or if_buy == 'n'):
    print('\n输入有误,请重试...')
    continue
   break

  while True:
   # 结算
   if if_buy == 'Y' or if_buy == 'y': 
    count = 0
    cancel = False

    while count < 3:
     user_pay_passwd = getpass.getpass('\n请输入支付密码,或输入 c 放弃支付:')
     if user_pay_passwd == 'c':
      print('\n取消支付成功...')
      cancel = True
      break
     elif user_pay_passwd != info[3]:
      if count != 2:
       print('\n密码错误,请重试,您还有 %d 次机会...' % (2-count))
      count += 1
     else:
      break

    if cancel:
     if_payed = False

    elif count == 3:
     with open('lock_list.txt', 'w') as lock_file:
      lock_file.write(username + '\n')
     exit('\n密码错误,账户已被锁定...')

    else:
     if total_sum <= user_balance:
      user_balance -= total_sum
      print('\n支付成功!您已成功购买以下商品:\n')
      i = 1
      for item in shopping_cart:
       (commodity, price, number) = (item[0], item[1], item[2])
       print((str(i) + '. ' + commodity).ljust(20) +
         ('单价:' + price + ' 元').ljust(15) + '数量:' + number)
       lines = open('product_list.txt', 'r').readlines()
       for line in lines: # 修改商品库存
        if commodity in line.split(', '):     # 定位到商品所在行
         j = lines.index(line)       # 获取商品所在行的行号索引
         select = line.split(', ')      # 商品所在行分割为字符串列表
         select[-1] = (str(int(select[-1]) - int(number)) + '\n') # 修改商品库存
         lines[j] = ', '.join(select)      # 将修改后的字符串列表组成字符串
         open('product_list.txt', 'w').writelines(lines) # 把修改写回文件
       i += 1

      lines = open('user_list.txt', 'r').readlines()

      for line in lines: # 用户余额写入文件
       if username in line.split(','):
        j = lines.index(line)
        select = line.split(',')
        select[-2] = str(user_balance)
        lines[j] = ','.join(select)
        open('user_list.txt', 'w').writelines(lines)

      exit('\n合计:%d 元, 账户余额:%d 元' % (total_sum, user_balance))

   # 不结算
   else: 
    print('\n您有一笔未支付订单...')
    while True:
     choice = input('\n是否进行支付?(Y/N):')
     if not (choice == 'Y' or choice == 'y' or choice == 'N' or choice == 'n'):
      print('\n输入有误,请重试...')
      continue
     break
    if choice == 'n' or choice == 'N':
     exit('\n订单已取消,感谢光临购物商城,再见...')
    else:
     if_buy = 'Y'
     continue

   if not if_payed:
    print('\n您有一笔未支付订单...')
    while True:
     choice = input('\n是否进行支付?(Y/N):')
     if not (choice == 'Y' or choice == 'y' or choice == 'N' or choice == 'n'):
      print('\n输入有误,请重试...')
      continue
     break

    if choice == 'n' or choice == 'N':
     exit('\n订单已取消,感谢光临购物商城,再见...')
    else:
     if_buy = 'Y'
     continue

# 商家入口
if entrance == '2':  

 seller_name = ''

 # 登录接口
 count = 0
 while count < 3:
  seller_name = input('\n用户名:')

  with open('lock_list.txt', 'r') as lock_file:
   for lock_line in lock_file:
    if seller_name == lock_line.strip('\n'):
     exit('\n用户名 %s 已被锁定,请联系管理员...' % seller_name)

  seller_file = open('seller_list.txt', 'r')
  login = False

  for seller_line in seller_file:
   (seller, passwd) = seller_line.strip('\n').split(',')
   if seller_name == seller:
    n = 0
    while n < 3:
     password = getpass.getpass('密码:')
     # 登录成功,跳出while循环
     if password == passwd:
      print('\n欢迎 %s 登录商城' % seller_name)
      login = True
      break 
     else:
      if n != 2:
       print('\n密码错误,请重试,您还有 %d 次机会' % (2-n))
     n += 1
    # n = 3,锁定用户名
    else:   
     open('lock_list.txt', 'w').write(seller_name + '\n')
     exit('\n错误次数过多,账户已被锁定...')
    # 登录成功,跳出for循环
    if login:  
     break

  # 用户名不存在
  else:  
   if count != 2:
    print('\n用户名不存在,请重试,您还有 %d 次机会' % (2-count))

  # 登录成功,跳出while循环
  if login: 
   break

  count += 1

 else:
  exit('\n错误次数过多,程序已退出...')


 # 商品列表编辑程序
 
 L = []
 # 存放商品列表,初始为空
 commodity_list = []
 index = 1

 print('\n您的货架上有以下商品:\n')
 
 print_product_list()

 while True:
  choice = input('\n是否编辑您的商品列表?(Y/N):')
  if not (choice == 'Y' or choice == 'y' or choice == 'N' or choice == 'n'):
   print('\n输入有误,请重试...')
   continue
  break

 if choice == 'Y' or choice == 'y':
  while True:
   print('\n请选择(输入 q 退出):\n')
   print('1. 上架新品\n\n2. 下架商品\n\n3. 修改商品信息')
   choice = input('\n>>>')
   if not (choice == '1' or choice == '2' or choice == '3' or choice == 'q'):
    print('输入有误,请重试...')
    continue

   # 上架新品
   if choice == '1':
    while True:
     if_add = False # 是否添加商品的标志,初始为False
     new_commodity = input('\n输入商品名:')

     product_file = open('product_list.txt', 'r')

     for product_line in product_file:
      commodity = product_line.strip('\n').split(', ')[0]  # 获取商品列表中的商品名
      if new_commodity == commodity:
       print('\n此商品已在货架上...')
       continue
      else:
       while True:
        if_sure = input('\n确定上架新品 %s 吗?(Y/N):' % new_commodity)
        if not (if_sure == 'Y' or if_sure == 'y' or if_sure == 'N' or if_sure == 'n'):
         print('\n输入有误,请重试...')
         continue
        break
       # 确定上架新品
       if if_sure == 'Y' or if_sure == 'y':
        while True:  # 输入单价
         price = input('\n请输入单价:')
         if not price.isdigit():
          print('\n输入有误,请重试...')
          continue
         break
        while True:  # 输入库存
         stock = input('\n请输入库存:')
         if not stock.isdigit():
          print('\n输入有误,请重试...')
          continue
         break
        new_line = '\n' + new_commodity + ', ' + price + ', ' + stock
        open('product_list.txt', 'a').writelines(new_line)
        print('\n成功上架新品 %s ,单价 %s 元,库存 %s 件' % (new_commodity, price, stock))

        while True:
         option = input('\n是否继续添加?(Y/N):')
         if not (option == 'Y' or option or option == 'N' or option == 'n'):
          print('\n输入有误,请重试...')
          continue
         break
        if option == 'Y' or option == 'y':
         if_add = True
         break # 跳出for循环
        else:
         break
       # 取消上架新品
       else:
        if_add = False
        break # 跳出for循环
     product_file.close()

     if if_add is True:
      continue
     else:
      break # 跳出while循环

   # 下架商品
   elif choice == '2':
    while True:
     del_num = input('\n请输入您想下架商品的序号:')
     if not (del_num.isdigit() or int(del_num) > 0 and int(del_num) <= len(commodity_list)):
      print('\n输入有误,请重试...')
      continue
     break

    del_num = int(del_num)
    del_commodity = commodity_list[del_num - 1][0]

    with open('product_list.txt', 'r') as old_file:
     with open('product_list.txt', 'r+') as new_file:

      current_line = 0

      # 定位到需要删除的行
      while current_line < (del_num - 1):
       old_file.readline()
       current_line += 1

      # 当前光标在被删除行的行首,记录该位置
      seek_point = old_file.tell()

      # 设置光标位置
      new_file.seek(seek_point, 0)

      # 读需要删除的行,光标移到下一行行首
      old_file.readline()
      
      # 被删除行的下一行读给 next_line
      next_line = old_file.readline()

      # 连续覆盖剩余行,后面所有行上移一行
      while next_line:
       new_file.write(next_line)
       next_line = old_file.readline()

      # 写完最后一行后截断文件,因为删除操作,文件整体少了一行,原文件最后一行需要去掉
      new_file.truncate()

    print('\n您已成功下架 %s !' % del_commodity)

   # 修改商品信息
   elif choice == '3':

    # 修改商品信息
    def mod_commodity_info(i, j):
     i = int(i)
     j = int(j)
     with open('product_list.txt', 'r+') as f:
      current_line = 0
      while current_line < i - 1:
       f.readline()
       current_line += 1
      seek_point = f.tell()
      f.seek(seek_point, 0)

      # 修改商品名
      if j == 1:
       update_line = mod_name() + ', ' + commodity_list[i-1][1] + ', ' + commodity_list[i-1][2] + '\n'
      # 修改商品价格
      elif j == 2:
       update_line = commodity_list[i-1][0] + ', ' + mod_price() + ', ' + commodity_list[i-1][2] + '\n'
      # 修改商品库存
      else:
       update_line = commodity_list[i-1][0] + ', ' + commodity_list[i-1][1] + ', ' + mod_stock() + '\n'
      
      f.write(update_line)
     return
    
    def mod_name():
     new_name = input("\n请输入新的商品名:")
     return new_name

    def mod_price():
     new_price = input("\n请输入新的商品单价:")
     return new_price

    def mod_stock():
     new_stock = input("\n请输入新的商品库存:")
     return new_stock

    # 修改商品单价
    def mod_commodity_price(i):
     i = int(i)
     with open('product_list.txt', 'r+') as f:
      current_line = 0
      while current_line < i -1:
       f.readline()
       current_line += 1
      seek_point = f.tell()
      f.seek(seek_point, 0)
      new_price = input()


    while True:
     i = input("\n请输入需要编辑的商品序号(输入 c 取消):")
     if not (i.isdigit or i == 'c' or int(i) > 0 and int(i) <= len(commodity_list)):
      print("\n输入有误,请重试...")
      continue
     elif i == 'c':
      break
     else:
      while True:
       j = input("\n请选择需要编辑的选项(输入 c 取消):\n\n1. 商品名\n\n2. 单价\n\n3. 库存\n\n>>>")
       if not (j == 'c' or j == '1' or j == '2' or j == '3'):
        print("\n输入有误,请重试...")
        continue
       break
      if j == 'c':
       break
      else:
       mod_commodity_info(i, j)

   else:
    exit('\n您已退出商城...')
 else:
  exit('\n您已退出商城...')

以上这篇Python 实现购物商城,含有用户入口和商家入口的示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python list使用示例 list中找连续的数字
Jan 27 Python
Python的Django框架下管理站点的基本方法
Jul 17 Python
Python进阶之递归函数的用法及其示例
Jan 31 Python
python在每个字符后添加空格的实例
May 07 Python
python绘制立方体的方法
Jul 02 Python
Python解决两个整数相除只得到整数部分的实例
Nov 10 Python
python3 http提交json参数并获取返回值的方法
Dec 19 Python
对python读取zip压缩文件里面的csv数据实例详解
Feb 08 Python
利用python numpy+matplotlib绘制股票k线图的方法
Jun 26 Python
Pycharm小白级简单使用教程
Jan 08 Python
python使用列表的最佳方案
Aug 12 Python
安装不同版本的tensorflow与models方法实现
Feb 20 Python
python中reload(module)的用法示例详解
Sep 15 #Python
Python 关于反射和类的特殊成员方法
Sep 14 #Python
在Python中执行系统命令的方法示例详解
Sep 14 #Python
关于Python如何避免循环导入问题详解
Sep 14 #Python
Python实现随机选择元素功能
Sep 14 #Python
python自动化脚本安装指定版本python环境详解
Sep 14 #Python
python实现八大排序算法(2)
Sep 14 #Python
You might like
ftp类(example.php)
2006/10/09 PHP
PHP中使用CURL模拟登录并获取数据实例
2014/07/01 PHP
thinkPHP5框架设置404、403等http状态页面的方法
2018/06/05 PHP
为radio类型的INPUT添加客户端脚本(附加实现JS来禁用onClick事件思路代码)
2010/11/11 Javascript
屏蔽IE弹出&quot;您查看的网页正在试图关闭窗口,是否关闭此窗口&quot;的方法
2013/12/31 Javascript
jquery 显示*天*时*分*秒实现时间计时器
2014/05/07 Javascript
jQuery滚动条插件nanoscroller使用指南
2015/04/21 Javascript
简述AngularJS的控制器的使用
2015/06/16 Javascript
JavaScript实现动态删除列表框值的方法
2015/08/12 Javascript
js改变css样式的三种方法推荐
2016/06/28 Javascript
String字符串截取的四种方式总结
2016/11/28 Javascript
浅谈js中function的参数默认值
2017/02/20 Javascript
原生JS仿QQ阅读点击展开、收起效果
2017/03/08 Javascript
Vue-cli@3.0 插件系统简析
2018/09/05 Javascript
详解Vue底部导航栏组件
2019/05/02 Javascript
nodejs环境使用Typeorm连接查询Oracle数据
2019/12/05 NodeJs
pycharm 使用心得(一)安装和首次使用
2014/06/05 Python
Python Sleep休眠函数使用简单实例
2015/02/02 Python
给Python入门者的一些编程建议
2015/06/15 Python
Python简单实现控制电脑的方法
2018/01/22 Python
Python基于lxml模块解析html获取页面内所有叶子节点xpath路径功能示例
2018/05/16 Python
python调用百度语音识别api
2018/08/30 Python
pytorch 可视化feature map的示例代码
2019/08/20 Python
关于keras中keras.layers.merge的用法说明
2020/05/23 Python
基于css3 animate制作绚丽的动画效果
2015/11/24 HTML / CSS
HTML5 canvas画矩形时出现边框样式不一致的解决方法
2013/10/14 HTML / CSS
屈臣氏俄罗斯在线商店:Watsons俄罗斯
2020/08/03 全球购物
高中毕业自我鉴定
2013/12/13 职场文书
化学教师教学反思
2014/01/17 职场文书
党员承诺书怎么写
2014/05/20 职场文书
项目经理任命书
2014/06/04 职场文书
个人合伙协议书范本
2014/10/14 职场文书
面试感谢信范文
2015/01/22 职场文书
文案策划岗位职责
2015/02/11 职场文书
高中语文教材(文学文化常识大全一)
2019/08/13 职场文书
解析高可用Redis服务架构分析与搭建方案
2021/06/20 Redis