购物车购物的例子

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

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

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

程序写了快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. eclipse 精确查询

    ---恢复内容开始--- ctrl+H(一般都是这个,如果无效看你的自定义快捷键) 输入\b 查询的字符串 \b   后面的正则表达式选框必须选

  2. c# 多线程同步之Mutex

    说起Mutex,它的中文名字叫互斥体.它是WaitHandle家族成员之一,前面有一篇介绍过WaitHandle的家族成员构成.那么Mutex有什么作用呢?它是怎么使用的? 我们先来看看它的使用场景一 ...

  3. 利用EF Core的Join进行多表查询

    背景 话说有这么一家子,老公养了一条狗,老婆养了一只猫. 数据库的设计 人表 宠物表 通过表可以知道,宠物通过Owner指向主人的Id. 问题来了,我要和故事开头一样,老公-狗,老婆-猫,对应起来,怎 ...

  4. OV摄像头SCCB通信协议

    /*! * COPYRIGHT NOTICE * Copyright (c) 2013,山外科技 * All rights reserved. * 技术讨论:山外论坛 http://www.vcan1 ...

  5. Bootstrap 在手机页时,导航下拉自动回收

    $(".menu-main").collapse("hide"); //.menu-main就是下来导航的类名

  6. linux操作日志:远程登录设置

    想要远程linux服务器,首先需要在服务器上开通ssh服务,安装命令如下: sudo apt-get install openssh-server   在上图的提示中,输入“y”,继续等待安装,安装成 ...

  7. SDP(13): Scala.Future - far from completion,绝不能用来做甩手掌柜

    在前面几篇关于数据库引擎的讨论里很多的运算函数都返回了scala.Future类型的结果,因为我以为这样就可以很方便的实现了non-blocking效果.无论任何复杂的数据处理操作,只要把它们包在一个 ...

  8. Java设计模式-模板模式

    介绍:模板模式定义了一个模板抽象类,这个抽象类中定义了方法调用的形式,顺序.子类通过重写对方法进行实现,但是调用方式不能改变. 模板模式中的模板中定义了核心的代码骨架,一些有着不同方式实现的代码放在子 ...

  9. 一篇关于Maven项目的jar包Shell启动脚本

    使用Maven作为项目jar包依赖的管理,常常会遇到命令行启动,笔者也是哥菜鸟,在做微服务,以及服务器端开发的过程中,常常会遇到项目的启动需要使用main方法,笔者潜心的研究了很多博客,发现大多写的都 ...

  10. Java基础_Java概述

    Java_概述 特点: 平台的移植性 开源 面向对象 多线程 安全性 工作方式: 先编译再解释执行. 先通过Javac命令将Java源代码编译成字节码文件(bytecode,类文件,.class,中间 ...