python3.5实现购物车
一、购物车实现:
购物车功能:
- 用户登录:密码错误三次锁定账户。
- 商品列表分页显示:输入页码查看指定页数商品信息。
- 已购买商品列表:显示已购买的物品列表;可以模糊查询已购买的商品并在终端打印。
- 充值:输入充值金额,对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实现购物车的更多相关文章
- python3.x Day2 购物车程序练习
购物车程序: 1.启动程序后,输入用户名密码后,如果是第一次登录,让用户输入工资,然后打印商品列表 2.允许用户根据商品编号购买商品 3.用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒 4. ...
- Python3 list与循环练习(购物车)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Author;Tsukasa product_list = [ ('Iphone',5800), (' ...
- python3 购物车小程序,余额写入文件保存
python3 购物车小程序,余额写入文件保存 #!/usr/bin/env python # -*- coding:utf-8 -*- # Author:Hiuhung Wan goods = ( ...
- python3购物车
python3实现购物车小程序,优化后将程序分成函数,用文件注册和验证用户名密码. #!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 20 ...
- Python3.5 Day2作业:购物车程序
需求: 1. 启动程序后,用户通过账号密码登录,然后打印商品列表. 2. 允许用户根据商品编号购买商品. 3. 用户选择商品后,检测余额是否足够,够就直接扣款,不够就提醒充值. 4. 可随时退出,退出 ...
- python3 购物车 增改查终极版~
还是先来条NLP再说,快没了,以后想抄还没有... 十一,没有挫败,只有回应讯息 “挫败”只是指出过去的做法得不到预期的效果,是给我们需要改变的信号. “挫败”只是在事情画上句号时才能用上,欲想事情解 ...
- python3 练习题(用函数完成登录注册以及购物车的功能)
''' 用函数完成登录注册以及购物车的功能 作业需求: 1,启动程序,用户可选择四个选项:登录,注册,购物,退出. 2,用户注册,用户名不能重复,注册成功之后,用户名密码记录到文件中. 3,用户登录, ...
- python3 练习题(购物车)
'''购物车程序需求:1.启动程序后,让用户输入工资,然后打印商品列表2.允许用户根据商品编号购买商品3.用户选择商品后,检查余额是否够,够就直接扣款,不够就提醒4.用户可一直购买商品,也可随时退出, ...
- Python3学习之路~2.2 简单的购物车程序
程序:购物车程序 需求:启动程序后,让用户输入工资,然后打印商品列表允许用户根据商品编号购买商品用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒 可随时退出,退出时,打印已购买商品和余额 代码 ...
随机推荐
- Windows远程桌面没有密码的电脑
你如果想远程一个密码为空的机器,默认情况下是不可以的,需要进行以下设置 1.windows家庭版不支持远程桌面 2. 3.搜索“本地安全策略”
- php做图片上传功能
今天来做一个图片上传功能的插件,首先做一个html文件:text.php <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transition ...
- 后Hadoop时代的大数据架构
提到大数据分析平台,不得不说Hadoop系统,Hadoop到现在也超过10年的历史了,很多东西发生了变化,版本也从0.x进化到目前的2.6版本.我把2012年后定义成后Hadoop平台时代,这不是说不 ...
- Django学习笔记第六篇--实战练习二--简易实现登录注册功能demo
一.绪论: 简易实现登录功能demo,并没有使用默认身份验证模块,所以做的也很差,关闭了csrf保护,没有认证处理cookie和session,只是简单实现了功能.另外所谓的验证码功能是伪的. 二. ...
- sssssss
1dispatcherServlet—拦截到spring mvc的请求 2dispatchServlet调用HandlerMapping( DefaultAnnoationHandlerMapping ...
- 购物车 cookie session
0-服务器识别用户的目的:服务器存有不同用户的信息,而对这些信息,服务器自身.网站开发管理者.网站访问者会对其读写: 1-暂且存入服务器数据库,购物车分为2种表:购物车入车表和购物车下单表: 2-单个 ...
- readAsDataURL
w http://stackoverflow.com/questions/14069421/show-an-image-preview-before-upload <input type=&qu ...
- [LeetCode] 7.Reverse Integer - Swift
Reverse digits of an integer. Example1: x = , return Example2: x = -, return - 题目意思:对一个整型进行反转 实现代码: ...
- Exception in thread "main" java.lang.UnsupportedClassVersionError: * : Unsupported major.minor version 52.0 解决办法
Exception in thread "main" java.lang.UnsupportedClassVersionError: * : Unsupported major.m ...
- 剑指Offer——按之字形顺序打印二叉树
题目描述: 请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推. 分析: 我们都知道二叉树的层次遍历用的是队 ...