zoukankan      html  css  js  c++  java
  • python3.5实现购物车

    一、购物车实现:

    购物车功能:

    • 用户登录:密码错误三次锁定账户。
    • 商品列表分页显示:输入页码查看指定页数商品信息。
    • 已购买商品列表:显示已购买的物品列表;可以模糊查询已购买的商品并在终端打印。
    • 充值:输入充值金额,对db.txt里的对应账户余额进行更改。

      -源码:

        db.txt

    dylan|123|19840|3
    elaine|123|10000000000064255|3
    admin|123|99999999761000|3

        shopping_cart.py

      1 #!/usr/bin/env python
      2 # -*- coding:utf-8 -*-
      3 #----------------------------------------------
      4 #@version:    3.6
      5 #@author:   Dylan_wu
      6 #@software:    PyCharm
      7 #@file:    shopping_cart.py
      8 #@time:    2017/4/24 13:57
      9 #----------------------------------------------
     10 import prettytable
     11 import sys
     12 
     13 def buy_goods(user_name,money,goods,total_goods,total_page_num):
     14     goods_num = 0  # 初始化购买商品总数量
     15     all_goods_price = 0  # 初始化商品总价
     16     buy_list = []  # 初始化购物列表
     17     print('33[1;32mUser Name:[%s]  Account Balance:[¥%s]33[0m'%(user_name,money))
     18     while True:
     19         try:
     20             print('33[1;32mTotal_GOODS_Num:[%s] Total_Page_Num:[%s]33[0m'%(total_goods,total_page_num))
     21             page_num = input('33[1;36mPlease choose the page number(Press[C]to Check_Out_List,[Q]to quit):33[0m')
     22             int_page_num = int(page_num)
     23             start = (int_page_num - 1) * 5
     24             end = int_page_num * 5
     25             print('33[1;35m+----+----+GOODS_LIST+-------+-------+33[0m')
     26             #########开始构建商品表(分页)#########
     27             table = prettytable.PrettyTable()
     28             table.field_names = ['ID','Name', 'Unit_Price','Stock']
     29             for i in goods[start:end]:
     30                 table.add_row([i['id'],i['name'],i['price'],i['stock']])
     31             print(table)
     32             print('33[1;35m+----+------Page-[%s]---------+-------+33[0m' % page_num)
     33         except:
     34             if page_num == 'C':    #跳出循环,进入checkout
     35                 break
     36             elif page_num == 'Q':    #结束程序
     37                 exit()
     38             else:
     39                 print('33[1;31mPlease enter a Page_num!33[0m')
     40                 continue
     41         #########开始购买程序###########
     42         while True:
     43             choose_ID = input("33[1;36mWhich good do you want to buy?Please choose the ID(Press[B]to back,[Q]to quit):33[0m")
     44             try:
     45                 int_ID = int(choose_ID)  # 输入商品序号转化为int类型,若不报错,向下执行
     46                 if int_ID in [i['id'] for i in goods]:  # 判断商品序号是否存在
     47                     product_quantity = int(input("33[1;36mWhat`s the quantity of products you want to buy:33[0m"))
     48                     if product_quantity <= goods[int_ID-1]['stock'] and product_quantity != 0:    #若购买数量<=库存
     49                         goods[int_ID - 1]['stock'] -= product_quantity    #更改库存
     50                         goods_num += product_quantity    #更新购买总数
     51                         all_goods_price += (goods[int_ID - 1]['price']*product_quantity)  # 叠加商品价格
     52                         #########构造购物列表#########
     53                         buy_list.append({'ID': int_ID, 'name': goods[int_ID - 1]['name'], 'price': goods[int_ID - 1]['price'],'quantity':product_quantity})
     54                     elif product_quantity == 0:
     55                         print("33[1;31mThe quantity of products can`t be[0]!!!!33[0m")
     56                         continue
     57                     else:
     58                         print('33[1;31mUnder stock!!!!33[0m')
     59                         continue
     60                 else:
     61                     print('33[1;31mYou choose wrong number or out of range!33[0m')
     62                     continue
     63             except :    # 输入值不能转化为int,报错走这里
     64                 if choose_ID == 'B':    #重新开始循环,回到分页界面
     65                     break
     66                 elif choose_ID == 'Q':    #结束程序
     67                     exit()
     68                 else:
     69                     print('33[1;31mPlease input a legal value!33[0m')  # 打印报错
     70     print('33[1;36mGoods_Num:[%s] Total_Price:[¥%s]33[0m' % (goods_num, all_goods_price))
     71     return goods_num, all_goods_price, buy_list
     72 
     73 
     74 def check_out_list(b_list):
     75     #########开始构建购物表#########
     76     while True:
     77         cart_table = prettytable.PrettyTable()
     78         cart_table.field_names = ['Product_ID', 'Product_Name', 'Unit_Price','Product_Quantity']
     79         search_name = input('33[1;36mEnter the product name you want to search in Check_out_list(Press[C]to Check_Out_List,[Q]to quit):33[0m')
     80         if search_name == 'C':
     81             break
     82         elif search_name == 'Q':
     83             exit()
     84         else:    #输入字符串,得到相应的搜索结果,找不结果返回空表格,不输入返回所有
     85             for i in b_list:
     86                 if i['name'].find(search_name) != -1:
     87                     cart_table.add_row([i['ID'], i['name'], i['price'],i['quantity']])
     88             print(cart_table)
     89 
     90 
     91 def check_out(user_name,account_balance,num,all_price):
     92     print('33[1;36mTotal_Num:[%s] Total_Price:[¥%s] Account_Balance:[¥%s]33[0m' % (num, all_price,account_balance))
     93     while True:
     94         choose_ID = input('33[1;36mDo you want to check out?Press[R]to recharge,[C]to check out,press[B]to back and clear the check_out_list[Q]to quit:33[0m')
     95         if choose_ID == 'C':    #选择C进行check_out
     96             if all_price <= int(account_balance):    #若总价少于余额
     97                 print('33[1;32mThe consumption is ¥%s totally,thank You for Your Custom!33[0m'%(all_price))
     98                 balance = int(account_balance) - all_price
     99                 mod_user(user_name,2,str(balance))    #对db里的用户余额进行更改
    100                 break
    101             else:
    102                 print('33[1;31mSorry,your balance has been insufficient,please recharge.33[0m')
    103         elif choose_ID == 'B':    #选择B返回购物菜单(清空购物列表,刷新商品字典)
    104             GOODS = [
    105                 {"id": 1, "name": "特斯拉", "price": 998, "stock": 10},
    106                 {"id": 2, "name": "玛莎拉蒂", "price": 898, "stock": 10},
    107                 {"id": 3, "name": "宾利", "price": 1998, "stock": 10},
    108                 {"id": 4, "name": "保时捷", "price": 1000, "stock": 10},
    109                 {"id": 5, "name": "丰田", "price": 298, "stock": 10},
    110                 {"id": 6, "name": "本田", "price": 398, "stock": 10},
    111                 {"id": 7, "name": "斯巴鲁", "price": 298, "stock": 10},
    112                 {"id": 8, "name": "奥拓", "price": 100, "stock": 10},
    113                 {"id": 9, "name": "尼桑", "price": 198, "stock": 10},
    114                 {"id": 10, "name": "奥迪", "price": 598, "stock": 10},
    115                 {"id": 11, "name": "奔驰", "price": 998, "stock": 10},
    116                 {"id": 12, "name": "宝马", "price": 1000, "stock": 10},
    117                 {"id": 13, "name": "兰博基尼", "price": 1998, "stock": 10},
    118                 {"id": 14, "name": "GMC", "price": 9898, "stock": 10},
    119                 {"id": 15, "name": "哈佛", "price": 398, "stock": 10},
    120                 {"id": 16, "name": "路虎", "price": 900, "stock": 10},
    121                 {"id": 17, "name": "悍马", "price": 998, "stock": 10},
    122                 {"id": 18, "name": "别克", "price": 198, "stock": 10},
    123                 {"id": 19, "name": "雪铁龙", "price": 198, "stock": 10},
    124                 {"id": 20, "name": "福特", "price": 300, "stock": 10},
    125                 {"id": 21, "name": "雪佛兰", "price": 398, "stock": 10},
    126             ]
    127             num, all_price, b_list = buy_goods(user_name,account_balance,GOODS,total_goods,total_page_num)
    128             check_out_list(b_list)
    129             check_out(user_name,account_balance,num,all_price)
    130             exit()
    131         elif choose_ID == 'R':    #选择R进行充值
    132             account_balance = user_recharge(user_name,account_balance)    #执行充值函数
    133         elif choose_ID == 'Q':    #选择Q退出程序
    134             exit()
    135         else:
    136             print('33[1;31mPlease press[R],[C]or[B],[Q]!33[0m')
    137 
    138 def user_recharge(user_name,balance):
    139     while True:
    140         print('33[1;36mDear %s!Your Account_Balance is:[¥%s]33[0m' % (user_name, balance))
    141         recharge_num = input('33[1;36mPlease enter the amount you want to charge,press[B]to back,press[Q]to quit:33[0m')
    142         try:
    143             int_amount = int(recharge_num)    #int所输入余额,不报错走这里
    144             now_balance = str(int_amount + int(balance))    #计算并str充值后余额
    145             mod_user(user_name,2,now_balance)    #调用mod_user函数修改db里的账户余额
    146             print('33[1;32mRecharge success!33[0m')
    147             return now_balance    #返回充值后余额
    148 
    149         except ValueError as e:    #报错走这里(输入值不能int)
    150             if recharge_num == 'B':
    151                 return balance
    152             elif recharge_num == 'Q':
    153                 exit()
    154             else:
    155                 print('33[1;31mPlease enter a valid value!33[0m')
    156 
    157 #============================主程序=============================#
    158 GOODS = [
    159     {"id":1,"name": "特斯拉", "price": 998,"stock":10},
    160     {"id":2,"name": "玛莎拉蒂", "price": 898,"stock":10},
    161     {"id":3,"name": "宾利", "price": 1998,"stock":10},
    162     {"id":4,"name": "保时捷", "price": 1000,"stock":10},
    163     {"id":5, "name": "丰田", "price": 298,"stock":10},
    164     {"id":6, "name": "本田", "price": 398,"stock":10},
    165     {"id":7, "name": "斯巴鲁", "price": 298,"stock":10},
    166     {"id":8, "name": "奥拓", "price": 100,"stock":10},
    167     {"id":9, "name": "尼桑", "price": 198,"stock":10},
    168     {"id":10, "name": "奥迪", "price": 598,"stock":10},
    169     {"id":11, "name": "奔驰", "price": 998,"stock":10},
    170     {"id":12, "name": "宝马", "price": 1000,"stock":10},
    171     {"id":13, "name": "兰博基尼", "price": 1998,"stock":10},
    172     {"id":14, "name": "GMC", "price": 9898,"stock":10},
    173     {"id":15, "name": "哈佛", "price": 398,"stock":10},
    174     {"id":16, "name": "路虎", "price": 900,"stock":10},
    175     {"id":17, "name": "悍马", "price": 998,"stock":10},
    176     {"id":18, "name": "别克", "price": 198,"stock":10},
    177     {"id":19, "name": "雪铁龙", "price": 198,"stock":10},
    178     {"id":20, "name": "福特", "price": 300,"stock":10},
    179     {"id":21, "name": "雪佛兰", "price": 398,"stock":10},
    180 ]
    181 
    182 f = open('db.txt','r')
    183 user_line = f.readlines()
    184 f.close()
    185 total_goods = len(GOODS)    #获取商品总数
    186 if len(GOODS)%5 == 0:    #获取商品总页数
    187     total_page_num = len(GOODS)//5
    188 else:
    189     total_page_num = len(GOODS)//5 + 1
    190 #========================修改数据库函数===========================#
    191 #=============='''以用户名为标识,修改相应位置的值'''==============#
    192 def mod_user(username,key_num,key_values):
    193     for i in range(len(user_line)):
    194         new_list = user_line[i].strip('
    ').split('|')
    195         if username == new_list[0]:
    196             new_list[key_num] = key_values
    197             user_line[i] = '|'.join(new_list)+'
    '    #构成新user_line
    198     f1 = open('db.txt', 'w')
    199     f1.writelines(user_line)    #新user_line保存到db
    200     f1.close()
    201 
    202 while True:
    203     username = input('33[1mPlease input your username:33[0m')
    204     password = input('33[1mPlease input your password:33[0m')
    205     for user_info in user_line:
    206         user_name,pass_word,balance,locked = user_info.strip('
    ').split('|')
    207 
    208         if username == user_name and password == pass_word and int(locked) != 0:    #登录成功条件判断
    209             print('33[1;32mLogin Successful!!33[0m')
    210             num, all_price, b_list = buy_goods(user_name,balance, GOODS,total_goods,total_page_num)
    211             check_out_list(b_list)
    212             check_out(username,balance,num,all_price)
    213             exit()
    214 
    215         elif username == user_name and int(locked) == 0:    #登录被锁定用户条件判断
    216             print('33[1;31mThe username:[%s]has been locked!Please contact the system administrator!33[0m'%(user_name))
    217             sys.exit('33[1;32mGood Bye!33[0m')
    218 
    219         elif username == user_name and int(locked) != 0:    #登录用户密码错误,锁定数-1条件判断
    220             locked_count = int(locked)    #获取user_info中的locked
    221             print('33[1;31mYou password is incorrect!You have %s attempts left before you will be locked out of your account.33[0m'%(locked_count-1))
    222             locked_count-=1
    223             mod_user(username,3,str(locked_count))    #修改用户的locked
    224 
    225             if locked_count == 0:    #锁定数=0时,退出程序
    226                 print('33[1;31mYou account has been locked!!!Please contact the system administrator!33[0m')
    227                 sys.exit('33[1;32mGood Bye!33[0m')
    228             else:
    229                 break
    230     print('33[1;31mYou username or password is wrong!!!33[0m')
    View Code

    二、部分功能展示:

    用户登录:

         

    登录失败三次,账户锁定:

    再次无法登陆:

    购买商品:

    购买数量不能为0报错:

    商品分页:

    已购买商品列表查询功能:

      -输入值进行模糊查询:

      -不输入值显示所有已购买商品:

      -输入不存在的值显示空列表:

    充值功能:

    结账:

  • 相关阅读:
    TCP/IP——何时用UDP代替TCP
    网络编程——客户/服务器程序设计范式
    各种常见英特网应用协议的使用情况和传输层三大协议的异同
    linux dd使用记录
    杂谈-为什么我们不要去外包公司
    小雪的成都
    哪个的情感
    mac上的git completion
    ue4 UE4Editor.lib找不到
    ue4 重新生成ide project文件的命令行
  • 原文地址:https://www.cnblogs.com/dylan-wu/p/6837145.html
Copyright © 2011-2022 走看看