一、购物车实现:

购物车功能:

  • 用户登录:密码错误三次锁定账户。
  • 商品列表分页显示:输入页码查看指定页数商品信息。
  • 已购买商品列表:显示已购买的物品列表;可以模糊查询已购买的商品并在终端打印。
  • 充值:输入充值金额,对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. print多重打印

    遇见有趣的问题必须记录下来,当时的想法思路也要记下来 以下两行代码打印出来的结果会是什么 print('2 * 3 = %d' % (2 * 3)) print('2 * 3 = %d' % 2 * ...

  2. Eclipse导入MyEclipseproject(web项目显示为java项目解决的方法)

    在直接Import MyEclipse的项目文件导入到Eclipse之后,须要在项目所放的workspace内改动引入项目文件夹下的.project文件,改动例如以下: 1.在eclipse中新建一个 ...

  3. 说说M451例程之PWM的寄存器讲解

    M451提供了两路PWM发生器.每路PWM支持6通道PWM输出或输入捕捉.有一个12位的预分频器把时钟源分频后输入给16位的计数器,另外还有一个16位的比较器.PWM计数器支持向上,向下,上下计数方式 ...

  4. 一、Android Studio入门——Eclipse快捷键配置

    [Studio总体介绍] 第一个是运行. 第二个是Debug.  是Studio的设置界面.   工程的配置.   Sync,更改配置.导入JAR包,都会去Sync一次.   SDK Manager. ...

  5. org.apache.hadoop.yarn.exceptions.InvalidAuxServiceException: The auxService: mapreduce_shuffle do

    在yarn-site.xml 配置文件中增加: <property> <name>yarn.nodemanager.aux-services</name> < ...

  6. Erstudio8.0怎么用?Erstudio8.0汉化版详细使用教程

    Erstudio8.0使用教程 打开ERstudio,点击新建出现如图对话框: 选择第一个,表示创建一个新的关系型 数据库模型 这里提一点数据库模型分为relational(关系)和dimension ...

  7. ios iphone、ipad启动画面尺寸

    以下是iphone.ipad启动画面的尺寸 iphone4(纵):320 x 480 iphone4 Retina(纵):640 x 960   iphone5(纵):320 x 568 iphone ...

  8. mysql支持跨表删除多条记录

    在Mysql4.0之后,mysql开始支持跨表delete. Mysql可以在一个sql语句中同时删除多表记录,也可以根据多个表之间的关系来删除某一个表中的记录. 假定我们有两张表:Product表和 ...

  9. SSM框架---搭建

    SSM框架简介 SSM框架,是spring + spring MVC + MyBatis的缩写,这个是继SSH之后,目前比较主流的Java EE企业级框架,适用于搭建各种大型的企业级应用系统. Spr ...

  10. Code Forces 650 C Table Compression(并查集)

    C. Table Compression time limit per test4 seconds memory limit per test256 megabytes inputstandard i ...