购物车购物的例子

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

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

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

程序写了快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. 分享一下我进入IT行业的经历

    今天突然根想写博客,就注册了一个,分享一下我的成长经历. 我第一次接触编程的时候是在上大学的时候,我学的专业是工程测量接触的第一个语言是vb,我记得很清楚,我当时写出第一个小Demo是的心情,感觉到了 ...

  2. 【Android】[Problem]-"Waiting for target device to come online".

    环境: win10专业版(创意者),Android studio 2.3.1 问题描述: 安装玩Android studio之后创建一个项目,建立AVD之后,运行程序时一直不能启动AVD,具体描述为: ...

  3. 初读 c# IL中间语言

    对一段c#编写的代码,有一些疑问,想通过IL中间语言看看,编译后是怎么处理的.代码如下: static StringBuilder sb = new StringBuilder(); ; ; /// ...

  4. SDP(12): MongoDB-Engine - Streaming

    在akka-alpakka工具包里也提供了对MongoDB的stream-connector,能针对MongoDB数据库进行streaming操作.这个MongoDB-connector里包含了Mon ...

  5. Jenkins 部署 jmeter + Ant

    安装Jenkins: 到jenkins官网下载相应的jenkins版本: 双击jenkins.msi启动安装,安装目录选择D:\Progrom Files\Jenkins,然后启动成功. Jenkin ...

  6. 温故而知新-set

    set:同map一样,关联式容器.在插入时就会进行排序,主要特点如下: 1.记录元素即是key值又是value值 2.插入的时候严格排序,底层是红黑树 3.删除元素时只要操作指针节点,无需进行内存的拷 ...

  7. Object的方法

    1.Object.assign() 方法用于将所有可枚举属性的值从一个或多个源对象复制到目标对象.它将返回目标对象. ES2015引入的 ,且可用polyfilled.要支持旧浏览器的话,可用使用jQ ...

  8. Java过滤器Filter使用详解

    转载请注明原文地址:http://www.cnblogs.com/ygj0930/p/6374212.html 在我的项目中有具体应用:https://github.com/ygj0930/Coupl ...

  9. 微信APP长按图片禁止保存到本地

    项目遇到一个问题,在web页面中,禁止长按图片保存, 使用css属性:  img { pointer-events: none; } 或者  img { -webkit-user-select: no ...

  10. iOS scrollView中嵌套多个tabeleView处理方案

    项目中经常会有这样的需求,scrollView有个头部,当scrollView滚动的时候头部也跟着滚动,同时头部还有一个tab会锁定在某个位置,scrollView中可以放很多不同的view,这些vi ...