python小练习之三---购物车程序
购物车购物的例子
严格来讲,这个例子相对大一些
功能也稍完备一些,具有用户登录,商品上架,用户购物,放入购物车,展示每个用户的购物车里的商品的数量,用户账户余额,支持用户账户充值等
下面展示的代码有些不完善,需要继续修改
程序写了快300行了,是不是可以优化一下
'''
购物车
1. 商品信息- 数量、单价、名称
2. 用户信息- 帐号、密码、余额
3. 用户可充值
4. 购物历史信息
5. 允许用户多次购买,每次可购买多件
6. 余额不足时进行提醒
7. 用户退出时,输出档次购物信息
8. 用户下次登陆时可查看购物历史
9. 商品列表分级
'''
import json
class Article(object):
def __init__(self, **kwargs):
self.attr = kwargs
# article_list.append(kwargs)
class User(object):
def __init__(self):
self.userchoice = 0
self.userlist = list()
self.username = str()
self.password = str()
self.balance = int()
# 用户名是否被使用了
self.nameused = 0
# 用户的用户名+密码是否能匹配
self.user_correct = 0
# 用户是否存在
self.user_exist = 0
# 用户登录尝试次数
self.login_try_count = 0
# 用户登录允许最大尝试次数为3次
self.login_limit_count = 3
# 用户是否已经登录
self.login_status = 0
def GenUserList(self):
self.userlist = list()
with open("userlist", "a+") as fd_userlist:
for line in fd_userlist:
if line.rstrip("\n"):
self.userlist.append(line.rstrip("\n"))
def WriteUserList(self, username):
username = self.username
with open("userlist", "a+") as fd_userlist:
fd_userlist.write(self.username)
fd_userlist.write("\n")
def UsernameCheck(self, username):
self.GenUserList()
self.nameused = 0
username = self.username
if self.username in self.userlist:
print '%s 用户名已经使用过了,请重新选择用户名' %(self.username)
self.nameused = 1
elif self.UserExist(self.username) == 1:
self.nameused = 0
return self.nameused
def UserExist(self, username):
with open("userprofile", "a+") as fd:
for line in fd:
if line.find(username) == 0:
self.user_exist = 1
return self.user_exist
else:
self.user_exist = 0
return self.user_exist
def UserRegister(self):
input_username = raw_input("请输入用户名:")
self.username = input_username.strip()
if self.UsernameCheck(self.username) == 0:
input_password = raw_input('请输入密码:').strip()
int_balance = 100
self.password = input_password
self.balance = self.UserCalBalance(int_balance)
print "self.balance" , self.balance
with open('userprofile', 'a+') as fd_userprofile:
# fd_userprofile.write('username:' + self.username + '|')
# fd_userprofile.write('password:' + self.password)
fd_userprofile.write(self.username + '|')
fd_userprofile.write(self.password + '|')
fd_userprofile.write(str(self.balance))
fd_userprofile.write("\n")
self.WriteUserList(self.username)
else:
self.UserRegister()
def UserCorrect(self, username, password):
userProfile_dict_list = list()
with open("userprofile", "a+") as fd:
for line in fd:
u, temp_p, initbalance = line.split("|")
p = temp_p.strip()
userProfile_dict_list.append({'username': u, 'password':
p})
length = len(userProfile_dict_list)
for i in xrange(length):
if username == userProfile_dict_list[i]['username']:
if password == userProfile_dict_list[i]['password']:
self.user_correct = 1
return self.user_correct
else:
self.user_correct = 0
return self.user_correct
# return self.user_correct
def UserCalBalance(self, balance):
self.balance += balance
return self.balance
def UserLogin(self):
userProfile_dict_list = list()
input_username = raw_input("登录用户名:").strip()
input_password = raw_input("登录密码:").strip()
self.user_correct = self.UserCorrect(input_username, input_password)
self.user_exist = self.UserExist(input_username)
if self.user_correct == 1:
print "欢迎登录:", input_username
self.login_status = 1
elif self.user_exist == 1:
print "密码错误"
self.login_try_count += 1
print "%s 还有 %d 次尝试机会" %(input_username,\
self.login_limit_count - self.login_try_count)
if self.login_try_count < 3:
self.UserLogin()
else:
print "%s 已经尝试3次登录失败" %(input_username)
self.login_status = 0
self.UserExit()
elif self.user_exist == 0:
print "%s 用户不存在" %(input_username)
print "请去注册"
self.UserRegister()
def UserCharge(self):
charge = int(raw_input("请输入充值金额:")).strip()
self.balance += charge
def UserExit(self):
print "Bye Bye"
exit(0)
def ProcessUserChoice(self):
if self.userchoice == 1:
self.UserRegister()
elif self.userchoice == 2:
self.UserLogin()
elif self.userchoice == 3:
self.UserCharge()
elif self.userchoice == 4:
CMain()
elif self.userchoice == 5:
self.UserExit()
else:
self.userchoice = int(raw_input("请输入正确的选择,\
1或者2或者3或者4或者5:"))
self.ProcessUserChoice()
def InitInterface(self):
failedCount = 0
login_status = dict()
u_profile_dict_list = list()
while True:
try:
self.userchoice = int(raw_input("----------------\n"
"用户操作菜单\n"
"----------------\n"
"1:注册\n"
"2:登录\n"
"3:充值\n"
"4:购物\n"
"5:退出\n"
"----------------\n"
"请选择:").strip())
self.ProcessUserChoice()
except Exception as e:
print e
self.InitInterface()
class Cart(object):
def __init__(self, kwargs):
self.cart_attr = kwargs
def userMain():
user = User()
user.InitInterface()
def addArticle():
while True:
choice = int(raw_input("----------------\n"
"商品操作菜单\n"
"----------------\n"
"请输入你的选择\n"
"1:添加商品\n"
"2:继续\n"
"3:退出商品操作,进入用户操作\n"))
if choice == 3:
print('bye bye!')
userMain()
elif choice == 1 or choice == 2:
article_name = raw_input("请输入商品名:")
article_price = raw_input("请输入商品价格:")
article_amount = raw_input("请输入商名数量:")
article = Article(**{'article_name': article_name,
'article_pricie': article_price, 'article_amount':
article_amount})
article_lst.append(article.attr)
# print article_lst
with open('article', 'a+') as fd_article:
for item in article_lst:
print item
fd_article.write(json.dumps(item))
fd_article.write(',')
def addCart():
user = User()
if user.UserLogin() == 1:
while True:
choice = int(raw_input("----------------\n"
"商品操作菜单\n"
"----------------\n"
"请输入你的选择\n"
"1:购买商品\n"
"2:退出购买商品操作,显示用户本次购买记录\n"))
if choice == 3:
print('bye bye!')
userMain()
elif choice == 1 or choice == 2:
user_article_name = raw_input("请输入商品名:")
user_article_price = raw_input("请输入商品价格:")
user_article_amount = raw_input("请输入商名数量:")
user_article = Article(**{input_username,\
{'article_name': article_name,\
'article_pricie': article_price, \
'article_amount': article_amount}})
user_cart_lst.append(article.attr)
# print article_lst
with open('article', 'a+') as fd_article:
for item in user_cart_lst:
print item
fd_article.write(json.dumps(item))
fd_article.write(',')
def UMain():
addArticle()
def CMain():
addCart()
if __name__ == '__main__':
article_lst = list()
user_cart_lst = list()
UMain()
CMain()
```
python小练习之三---购物车程序的更多相关文章
- 使用python操作文件实现购物车程序
使用python操作文件实现购物车程序 题目要求如下: 实现思路 始终维护一张字典,该字典里保存有用户账号密码,购物车记录等信息.在程序开始的时候读进来,程序结束的时候写回文件里去.在登录注册的部分, ...
- Python初学者第十二天 购物车程序小作业
12day 作业题目: 购物车程序 作业需求: 数据结构: goods = [ {"name": "电脑", "price": 1999}, ...
- 浅谈自学Python之路(购物车程序练习)
购物车程序练习 今天我们来做一个购物车的程序联系,首先要理清思路 购物车程序需要用到什么知识点 需要用到哪些循环 程序编写过程中考虑值的类型,是int型还是字符串 如果值为字符串该怎么转成int型 用 ...
- 五、python小功能记录——打包程序
使用pyinstaller打包Python程序 安装工具 :pip3 install pyinstaller 在Python程序文件夹上(不点进去)按住shift并且右键,在弹出的选项中点击" ...
- Python小代码_3_购物车
product_list = [ ('MacBook', 9000), ('kindle', 500), ('tesla', 900000), ('book', 100), ('bike', 2000 ...
- Python之路 day2 购物车小程序1
#Author:ersa ''' 程序:购物车程序 需求: 启动程序后,让用户输入工资,然后打印商品列表 允许用户根据商品编号购买商品 用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒 可随时 ...
- python学习:购物车程序
购物车程序 product_list = [ ('mac',9000), ('kindle',800), ('tesla',900000), ('python book',105), ('bike', ...
- python复习购物车程序
个人学习总结: 无他,唯手熟尔!多敲多练才是王道 python 第三课 元组的灵活运用&字符串的诸多操作 Program01 '''时间 2018年2月12日12:15:28目的 购物车程序 ...
- 怎么样通过编写Python小程序来统计测试脚本的关键字
怎么样通过编写Python小程序来统计测试脚本的关键字 通常自动化测试项目到了一定的程序,编写的测试代码自然就会很多,如果很早已经编写的测试脚本现在某些基础函数.业务函数需要修改,那么势必要找出那些引 ...
随机推荐
- Java中高级面试题
一.基础知识: 1)集合类:List和Set比较,各自的子类比较(ArrayList,Vector,LinkedList:HashSet,TreeSet): 2)HashMap的底层实现,之后会问Co ...
- angular中$q.all用法
$q.all是用于执行多个异步任务进行回调,它可以接受一个promise的数组,或是promise的hash(object).任何一个promise失败,都会导致整个任务的失败. 例1:接受一个pro ...
- javaweb代码生成器,专注于javaweb项通用目的代码生成器
该项目为javaWEB项目通用代码生成器,根据数据库表和自定义代码模板生成相应的jsp,js,java文件,生成到指定路径下,javaweb项目开发利器: 项目开源地址:https://gitee.c ...
- Java接口-----代理模式(Proxy)
public static void main(String[] args) { // TODO Auto-generated method stub ProxySubject a = new Pro ...
- 【python学习笔记】8.异常
[python学习笔记]8.异常 raise Exception: 抛出指定异常 try/except: 捕捉异常 except: 第一个参数是需要捕获的异常类型,可以是多个类型组成元组,第二个参数是 ...
- Java基础知识回顾之一 ----- 基本数据类型
前言 在开始工作至今,学习各种各样的技术之中发现自己的很多Java的基础知识都忘了⊙﹏⊙b汗... 而且越是学习越是发现Java基础的重要性,所以准备单独抽一下时间进行Java基础的重新学习.在重新学 ...
- [ETL] Flume 理论与demo(Taildir Source & Hdfs Sink)
一.Flume简介 1. Flume概述 Flume是Cloudera提供的一个高可用的,高可靠的,分布式的海量日志采集.聚合和传输的系统,Flume支持在日志系统中定制各类数据发送方,用于收集数据: ...
- C#将.spl剥离成.emf文件格式
本文转载自 星战紫辉 http://www.cppblog.com/rawdata/archive/2009/02/23/74653.html 但C#代码实现为本人原创.https://github. ...
- 处理win7任务栏通知区域图标异常问题
故障现象:安装的某软件比如QQ,应用程序运行图标始终没有在win7任务栏通知区域显示出来,经观查发现win7任务栏通知区域有几个已删除应用的图标出现,应该是有故障了. 故障现象一:已经卸载的程序,还在 ...
- Junit test使用
1.导入maven依赖 <dependency> <groupId>junit</groupId> <artifactId>junit</arti ...