购物车购物的例子

严格来讲,这个例子相对大一些

功能也稍完备一些,具有用户登录,商品上架,用户购物,放入购物车,展示每个用户的购物车里的商品的数量,用户账户余额,支持用户账户充值等

下面展示的代码有些不完善,需要继续修改

程序写了快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小练习之三---购物车程序的更多相关文章

  1. 使用python操作文件实现购物车程序

    使用python操作文件实现购物车程序 题目要求如下: 实现思路 始终维护一张字典,该字典里保存有用户账号密码,购物车记录等信息.在程序开始的时候读进来,程序结束的时候写回文件里去.在登录注册的部分, ...

  2. Python初学者第十二天 购物车程序小作业

    12day 作业题目: 购物车程序 作业需求: 数据结构: goods = [ {"name": "电脑", "price": 1999}, ...

  3. 浅谈自学Python之路(购物车程序练习)

    购物车程序练习 今天我们来做一个购物车的程序联系,首先要理清思路 购物车程序需要用到什么知识点 需要用到哪些循环 程序编写过程中考虑值的类型,是int型还是字符串 如果值为字符串该怎么转成int型 用 ...

  4. 五、python小功能记录——打包程序

    使用pyinstaller打包Python程序 安装工具 :pip3 install pyinstaller 在Python程序文件夹上(不点进去)按住shift并且右键,在弹出的选项中点击" ...

  5. Python小代码_3_购物车

    product_list = [ ('MacBook', 9000), ('kindle', 500), ('tesla', 900000), ('book', 100), ('bike', 2000 ...

  6. Python之路 day2 购物车小程序1

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

  7. python学习:购物车程序

    购物车程序 product_list = [ ('mac',9000), ('kindle',800), ('tesla',900000), ('python book',105), ('bike', ...

  8. python复习购物车程序

    个人学习总结: 无他,唯手熟尔!多敲多练才是王道 python 第三课 元组的灵活运用&字符串的诸多操作 Program01 '''时间 2018年2月12日12:15:28目的 购物车程序 ...

  9. 怎么样通过编写Python小程序来统计测试脚本的关键字

    怎么样通过编写Python小程序来统计测试脚本的关键字 通常自动化测试项目到了一定的程序,编写的测试代码自然就会很多,如果很早已经编写的测试脚本现在某些基础函数.业务函数需要修改,那么势必要找出那些引 ...

随机推荐

  1. oracle使用中的一些问题

    一.设置自增主键(假设表的主键名为:company_id) 1)创建序列(company_autoinc): maxvalue start increment nocache; 2)创建触发器(com ...

  2. java接口----继承(实现)方法

    文中"实现"一词特指接口的继承. 一个类实现多个接口时,不能出现同名的默认方法. 一个类既要实现接口又要继承抽象类,先继承后实现. 一个抽象类可以继承多个接口(implements ...

  3. Ubuntu14.04 设置wifi热点

    Ubuntu14.04 设置wifi热点 $ sudo add-apt-repository ppa:nilarimogard/webupd8 $ sudo apt-get update $ sudo ...

  4. centos7 升级 git(2.14.3) 版本

    下载  wget https://www.kernel.org/pub/software/scm/git/git-2.14.3.tar.gz 安装依赖包  yum install curl-devel ...

  5. Log4Net五部曲

    本文主要讲述如何构建封装一个日志工具类,以及在该过程中遇到的问题, 关于Log4Net的介绍,就不详细赘述了,更多详细的技术可参考http://www.cnblogs.com/kissazi2/p/3 ...

  6. 负载均衡,会话保持,session同步(转)

    转自:http://bbs.linuxtone.org/thread-18212-1-1.html 一,什么负载均衡一个新网站是不要做负载均衡的,因为访问量不大,流量也不大,所以没有必要搞这些东西.但 ...

  7. 忘记root密码---单用户模式进入及操作

    修改root密码----------------单用户模式操作 个人原创博客,转载请注明,否则追究法律责任 1,开机后,迅速按下任意键 2,选择第二个:内核,按e 3,在quient后面按空格 1 或 ...

  8. Java 小记 — Spring Boot 注解

    前言 本篇随笔将对 Spring Boot 中的常用注解做一个简单的整理归档,写作顺序将从启动类开始并逐步向内外扩展,目的即为了分享也为了方便自己日后的回顾与查阅. 1. Application 启动 ...

  9. ubuntu下ftp服务

    (1).首先用命令检查是否安装了vsftpd vsftpd -version 如果未安装用一下命令安装 sudo apt-get install vsftpd 安装完成后,再次输入vsftpd -ve ...

  10. IPFS如何挖矿<Filecoin系统>?(一)

    本来这篇文章应该晚一点写, 但是这几天一直有朋友在公众号留言, 迫切的想知道IPFS到底如何挖矿, 所以就提前写一篇关于IPFS挖矿的文章. 本文暂不涉及具体的技术细节, 只做大概的介绍. 首先, 好 ...