一、购物车实现:

购物车功能:

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

  -源码:

    db.txt

dylan|||
elaine|||
admin|||

    shopping_cart.py

 #!/usr/bin/env python
# -*- coding:utf-8 -*-
#----------------------------------------------
#@version: 3.6
#@author: Dylan_wu
#@software: PyCharm
#@file: shopping_cart.py
#@time: 2017/4/24 13:57
#----------------------------------------------
import prettytable
import sys def buy_goods(user_name,money,goods,total_goods,total_page_num):
goods_num = 0 # 初始化购买商品总数量
all_goods_price = 0 # 初始化商品总价
buy_list = [] # 初始化购物列表
print('\033[1;32mUser Name:[%s] Account Balance:[¥%s]\033[0m'%(user_name,money))
while True:
try:
print('\033[1;32mTotal_GOODS_Num:[%s] Total_Page_Num:[%s]\033[0m'%(total_goods,total_page_num))
page_num = input('\033[1;36mPlease choose the page number(Press[C]to Check_Out_List,[Q]to quit):\033[0m')
int_page_num = int(page_num)
start = (int_page_num - 1) * 5
end = int_page_num * 5
print('\033[1;35m+----+----+GOODS_LIST+-------+-------+\033[0m')
#########开始构建商品表(分页)#########
table = prettytable.PrettyTable()
table.field_names = ['ID','Name', 'Unit_Price','Stock']
for i in goods[start:end]:
table.add_row([i['id'],i['name'],i['price'],i['stock']])
print(table)
print('\033[1;35m+----+------Page-[%s]---------+-------+\033[0m' % page_num)
except:
if page_num == 'C': #跳出循环,进入checkout
break
elif page_num == 'Q': #结束程序
exit()
else:
print('\033[1;31mPlease enter a Page_num!\033[0m')
continue
#########开始购买程序###########
while True:
choose_ID = input("\033[1;36mWhich good do you want to buy?Please choose the ID(Press[B]to back,[Q]to quit):\033[0m")
try:
int_ID = int(choose_ID) # 输入商品序号转化为int类型,若不报错,向下执行
if int_ID in [i['id'] for i in goods]: # 判断商品序号是否存在
product_quantity = int(input("\033[1;36mWhat`s the quantity of products you want to buy:\033[0m"))
if product_quantity <= goods[int_ID-1]['stock'] and product_quantity != 0: #若购买数量<=库存
goods[int_ID - 1]['stock'] -= product_quantity #更改库存
goods_num += product_quantity #更新购买总数
all_goods_price += (goods[int_ID - 1]['price']*product_quantity) # 叠加商品价格
#########构造购物列表#########
buy_list.append({'ID': int_ID, 'name': goods[int_ID - 1]['name'], 'price': goods[int_ID - 1]['price'],'quantity':product_quantity})
elif product_quantity == 0:
print("\033[1;31mThe quantity of products can`t be[0]!!!!\033[0m")
continue
else:
print('\033[1;31mUnder stock!!!!\033[0m')
continue
else:
print('\033[1;31mYou choose wrong number or out of range!\033[0m')
continue
except : # 输入值不能转化为int,报错走这里
if choose_ID == 'B': #重新开始循环,回到分页界面
break
elif choose_ID == 'Q': #结束程序
exit()
else:
print('\033[1;31mPlease input a legal value!\033[0m') # 打印报错
print('\033[1;36mGoods_Num:[%s] Total_Price:[¥%s]\033[0m' % (goods_num, all_goods_price))
return goods_num, all_goods_price, buy_list def check_out_list(b_list):
#########开始构建购物表#########
while True:
cart_table = prettytable.PrettyTable()
cart_table.field_names = ['Product_ID', 'Product_Name', 'Unit_Price','Product_Quantity']
search_name = input('\033[1;36mEnter the product name you want to search in Check_out_list(Press[C]to Check_Out_List,[Q]to quit):\033[0m')
if search_name == 'C':
break
elif search_name == 'Q':
exit()
else: #输入字符串,得到相应的搜索结果,找不结果返回空表格,不输入返回所有
for i in b_list:
if i['name'].find(search_name) != -1:
cart_table.add_row([i['ID'], i['name'], i['price'],i['quantity']])
print(cart_table) def check_out(user_name,account_balance,num,all_price):
print('\033[1;36mTotal_Num:[%s] Total_Price:[¥%s] Account_Balance:[¥%s]\033[0m' % (num, all_price,account_balance))
while True:
choose_ID = input('\033[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:\033[0m')
if choose_ID == 'C': #选择C进行check_out
if all_price <= int(account_balance): #若总价少于余额
print('\033[1;32mThe consumption is ¥%s totally,thank You for Your Custom!\033[0m'%(all_price))
balance = int(account_balance) - all_price
mod_user(user_name,2,str(balance)) #对db里的用户余额进行更改
break
else:
print('\033[1;31mSorry,your balance has been insufficient,please recharge.\033[0m')
elif choose_ID == 'B': #选择B返回购物菜单(清空购物列表,刷新商品字典)
GOODS = [
{"id": 1, "name": "特斯拉", "price": 998, "stock": 10},
{"id": 2, "name": "玛莎拉蒂", "price": 898, "stock": 10},
{"id": 3, "name": "宾利", "price": 1998, "stock": 10},
{"id": 4, "name": "保时捷", "price": 1000, "stock": 10},
{"id": 5, "name": "丰田", "price": 298, "stock": 10},
{"id": 6, "name": "本田", "price": 398, "stock": 10},
{"id": 7, "name": "斯巴鲁", "price": 298, "stock": 10},
{"id": 8, "name": "奥拓", "price": 100, "stock": 10},
{"id": 9, "name": "尼桑", "price": 198, "stock": 10},
{"id": 10, "name": "奥迪", "price": 598, "stock": 10},
{"id": 11, "name": "奔驰", "price": 998, "stock": 10},
{"id": 12, "name": "宝马", "price": 1000, "stock": 10},
{"id": 13, "name": "兰博基尼", "price": 1998, "stock": 10},
{"id": 14, "name": "GMC", "price": 9898, "stock": 10},
{"id": 15, "name": "哈佛", "price": 398, "stock": 10},
{"id": 16, "name": "路虎", "price": 900, "stock": 10},
{"id": 17, "name": "悍马", "price": 998, "stock": 10},
{"id": 18, "name": "别克", "price": 198, "stock": 10},
{"id": 19, "name": "雪铁龙", "price": 198, "stock": 10},
{"id": 20, "name": "福特", "price": 300, "stock": 10},
{"id": 21, "name": "雪佛兰", "price": 398, "stock": 10},
]
num, all_price, b_list = buy_goods(user_name,account_balance,GOODS,total_goods,total_page_num)
check_out_list(b_list)
check_out(user_name,account_balance,num,all_price)
exit()
elif choose_ID == 'R': #选择R进行充值
account_balance = user_recharge(user_name,account_balance) #执行充值函数
elif choose_ID == 'Q': #选择Q退出程序
exit()
else:
print('\033[1;31mPlease press[R],[C]or[B],[Q]!\033[0m') def user_recharge(user_name,balance):
while True:
print('\033[1;36mDear %s!Your Account_Balance is:[¥%s]\033[0m' % (user_name, balance))
recharge_num = input('\033[1;36mPlease enter the amount you want to charge,press[B]to back,press[Q]to quit:\033[0m')
try:
int_amount = int(recharge_num) #int所输入余额,不报错走这里
now_balance = str(int_amount + int(balance)) #计算并str充值后余额
mod_user(user_name,2,now_balance) #调用mod_user函数修改db里的账户余额
print('\033[1;32mRecharge success!\033[0m')
return now_balance #返回充值后余额 except ValueError as e: #报错走这里(输入值不能int)
if recharge_num == 'B':
return balance
elif recharge_num == 'Q':
exit()
else:
print('\033[1;31mPlease enter a valid value!\033[0m') #============================主程序=============================#
GOODS = [
{"id":1,"name": "特斯拉", "price": 998,"stock":10},
{"id":2,"name": "玛莎拉蒂", "price": 898,"stock":10},
{"id":3,"name": "宾利", "price": 1998,"stock":10},
{"id":4,"name": "保时捷", "price": 1000,"stock":10},
{"id":5, "name": "丰田", "price": 298,"stock":10},
{"id":6, "name": "本田", "price": 398,"stock":10},
{"id":7, "name": "斯巴鲁", "price": 298,"stock":10},
{"id":8, "name": "奥拓", "price": 100,"stock":10},
{"id":9, "name": "尼桑", "price": 198,"stock":10},
{"id":10, "name": "奥迪", "price": 598,"stock":10},
{"id":11, "name": "奔驰", "price": 998,"stock":10},
{"id":12, "name": "宝马", "price": 1000,"stock":10},
{"id":13, "name": "兰博基尼", "price": 1998,"stock":10},
{"id":14, "name": "GMC", "price": 9898,"stock":10},
{"id":15, "name": "哈佛", "price": 398,"stock":10},
{"id":16, "name": "路虎", "price": 900,"stock":10},
{"id":17, "name": "悍马", "price": 998,"stock":10},
{"id":18, "name": "别克", "price": 198,"stock":10},
{"id":19, "name": "雪铁龙", "price": 198,"stock":10},
{"id":20, "name": "福特", "price": 300,"stock":10},
{"id":21, "name": "雪佛兰", "price": 398,"stock":10},
] f = open('db.txt','r')
user_line = f.readlines()
f.close()
total_goods = len(GOODS) #获取商品总数
if len(GOODS)%5 == 0: #获取商品总页数
total_page_num = len(GOODS)//5
else:
total_page_num = len(GOODS)//5 + 1
#========================修改数据库函数===========================#
#=============='''以用户名为标识,修改相应位置的值'''==============#
def mod_user(username,key_num,key_values):
for i in range(len(user_line)):
new_list = user_line[i].strip('\n').split('|')
if username == new_list[0]:
new_list[key_num] = key_values
user_line[i] = '|'.join(new_list)+'\n' #构成新user_line
f1 = open('db.txt', 'w')
f1.writelines(user_line) #新user_line保存到db
f1.close() while True:
username = input('\033[1mPlease input your username:\033[0m')
password = input('\033[1mPlease input your password:\033[0m')
for user_info in user_line:
user_name,pass_word,balance,locked = user_info.strip('\n').split('|') if username == user_name and password == pass_word and int(locked) != 0: #登录成功条件判断
print('\033[1;32mLogin Successful!!\033[0m')
num, all_price, b_list = buy_goods(user_name,balance, GOODS,total_goods,total_page_num)
check_out_list(b_list)
check_out(username,balance,num,all_price)
exit() elif username == user_name and int(locked) == 0: #登录被锁定用户条件判断
print('\033[1;31mThe username:[%s]has been locked!Please contact the system administrator!\033[0m'%(user_name))
sys.exit('\033[1;32mGood Bye!\033[0m') elif username == user_name and int(locked) != 0: #登录用户密码错误,锁定数-1条件判断
locked_count = int(locked) #获取user_info中的locked
print('\033[1;31mYou password is incorrect!You have %s attempts left before you will be locked out of your account.\033[0m'%(locked_count-1))
locked_count-=1
mod_user(username,3,str(locked_count)) #修改用户的locked if locked_count == 0: #锁定数=0时,退出程序
print('\033[1;31mYou account has been locked!!!Please contact the system administrator!\033[0m')
sys.exit('\033[1;32mGood Bye!\033[0m')
else:
break
print('\033[1;31mYou username or password is wrong!!!\033[0m')

二、部分功能展示:

用户登录:

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

再次无法登陆:

购买商品:

购买数量不能为0报错:

商品分页:

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

  -输入值进行模糊查询:

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

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

充值功能:

结账:

python3.5实现购物车的更多相关文章

  1. python3.x Day2 购物车程序练习

    购物车程序: 1.启动程序后,输入用户名密码后,如果是第一次登录,让用户输入工资,然后打印商品列表 2.允许用户根据商品编号购买商品 3.用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒 4. ...

  2. Python3 list与循环练习(购物车)

    #!/usr/bin/env python3 # -*- coding: utf-8 -*- # Author;Tsukasa product_list = [ ('Iphone',5800), (' ...

  3. python3 购物车小程序,余额写入文件保存

    python3 购物车小程序,余额写入文件保存 #!/usr/bin/env python # -*- coding:utf-8 -*- # Author:Hiuhung Wan goods = ( ...

  4. python3购物车

    python3实现购物车小程序,优化后将程序分成函数,用文件注册和验证用户名密码. #!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 20 ...

  5. Python3.5 Day2作业:购物车程序

    需求: 1. 启动程序后,用户通过账号密码登录,然后打印商品列表. 2. 允许用户根据商品编号购买商品. 3. 用户选择商品后,检测余额是否足够,够就直接扣款,不够就提醒充值. 4. 可随时退出,退出 ...

  6. python3 购物车 增改查终极版~

    还是先来条NLP再说,快没了,以后想抄还没有... 十一,没有挫败,只有回应讯息 “挫败”只是指出过去的做法得不到预期的效果,是给我们需要改变的信号. “挫败”只是在事情画上句号时才能用上,欲想事情解 ...

  7. python3 练习题(用函数完成登录注册以及购物车的功能)

    ''' 用函数完成登录注册以及购物车的功能 作业需求: 1,启动程序,用户可选择四个选项:登录,注册,购物,退出. 2,用户注册,用户名不能重复,注册成功之后,用户名密码记录到文件中. 3,用户登录, ...

  8. python3 练习题(购物车)

    '''购物车程序需求:1.启动程序后,让用户输入工资,然后打印商品列表2.允许用户根据商品编号购买商品3.用户选择商品后,检查余额是否够,够就直接扣款,不够就提醒4.用户可一直购买商品,也可随时退出, ...

  9. Python3学习之路~2.2 简单的购物车程序

    程序:购物车程序 需求:启动程序后,让用户输入工资,然后打印商品列表允许用户根据商品编号购买商品用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒 可随时退出,退出时,打印已购买商品和余额 代码 ...

随机推荐

  1. UIView 坐标转换

    例子1 Controller的view中有一个tableView,tableView的cell上有一个button,现在需要将button的frame转为在Controller的view中的frame ...

  2. freemarker0

    assign  用于为该模板页面 创建或替换一个顶层变量 或创建或替换多个顶层变量 列子如下 <#assign name=value [in namespacehash]>,指定一个名为n ...

  3. hdu 3899(树形dp)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3899 思路:num[u]表示u以及u的子树的队伍数的总和,dist[u]表示u到根节点的距离,dp[u ...

  4. Python闲谈(一)mgrid慢放

    不论是利用Mayavi还是matplotlib绘制三维图表,里面都用到了numpy中的一个函数叫mgrid.本次博客我简单地讲一下mgrid是干什么用的,以及一个三维曲面是如何绘制出来的. 首先说明一 ...

  5. python裁剪base64编码的图片

    简介 今天遇到需要裁剪base64字符串的PNG图片,并返回base64格式字符串的任务,捣鼓半天. 裁剪代码如下: def deal_inspect_img(base64_str): "& ...

  6. jenkins 配置 ssh插件

    一.安装SSH插件 系统管理->插件管理,在可选插件下,过滤SSH,找到publish over ssh插件,直接安装(我这里已经安装过了,在已安装选项下可以找到publish over ssh ...

  7. C语言实现双链表(带头节点)

    双链表和单链表性质相似只是在多加了一个前指针 1.定义结构体 typedef struct Node{ int data; struct Node *prior; struct Node *next; ...

  8. fidder教程

    Fiddler是最强大最好用的Web调试工具之一,它能记录所有客户端和服务器的http和https请求,允许你监视,设置断点,甚至修改输入输出数据. 使用Fiddler无论对开发还是测试来说,都有很大 ...

  9. HDU3306—Another kind of Fibonacci

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3306 题目意思:一个斐波那契数列的变式,本来是A[n]=A[n-1]+A[n-2],现在变成A[n]= ...

  10. c# winfrom实时获取斗鱼房间弹幕

    效果图如下: 通过webBrowser获取,时钟控件刷新弹幕,正则匹配数据,用第二个webBrowser显示弹幕内容.老话,并没完善.请自行完善.有个dll是用来屏蔽webBrowser的声音的,可能 ...