python学习之购物车程序

最近在学习python全栈开发,这是第一个模块的作业:购物车程序。

数据结构

goods = [
{"name": "电脑", "price": 1999},
{"name": "鼠标", "price": 10},
{"name": "游艇", "price": 20},
{"name": "美女", "price": 998},
......
]

功能要求

  • 启动程序后,输入用户名密码后,让用户输入工资,然后打印商品列表
  • 允许用户根据商品编号购买商品
  • 用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒
  • 可随时退出,退出时,打印已购买商品和余额
  • 在用户使用过程中, 关键输出,如余额,商品已加入购物车等消息,需高亮显示

扩展需求

  • 用户下一次登录后,输入用户名密码,直接回到上次的状态,即上次消费的余额什么的还是那些,再次登录可继续购买
  • 允许查询之前的消费记录

代码实现

#/usr/bin/env python
#-*- coding:utf8 -*-
__author__ = 'shunzi'
"""
使用方法:
    通过user_info列表里的用户名密码登录系统,然后购买相关商品
    1,如果第一次登录,提示输入工资 购买完退出程序保存相关购买信息到cart_info_file文件
    2,第二次登录后,可以查看上次消费记录及余额
    3,购买商品及余额 高亮显示
    。。。
"""
#用户消费明细存放文件
cart_info_file = 'cart_info.txt'

#登录用户列表
user_info = [('shunzi','123456'),('ss','123')]

# 商品列表
goods = [
    {"name": "电脑", "price": 1999},
    {"name": "鼠标", "price": 10},
    {"name": "游艇", "price": 20},
    {"name": "美女", "price": 998},
]

with open(cart_info_file,'r',encoding='utf-8') as f:
    cart_info = f.readlines()

pay_list = []
u_info = []
u_infos = []
data = []
datas = []
read_str = []
status = False
while not status:
    username = input('please enter username:').strip()
    password = input('please enter password:').strip()

    if len(cart_info) > 0:
        for item in cart_info: #提取登录用户历史购物信息
            if len(item.strip()) > 0:
                data = eval(item)
                if  data.get(username) != 'None':
                    u_info.append(username)
                    datas = data[username]

    if (username,password) not in user_info:
        print('你输入的用户名或密码错误,程序退出')
        break
    elif len(u_info) == 0 and (username,password) in user_info:  #如果没有登录信息则为第一次登录,要求输入工资
        salary = int(input('请输入你的工资:').strip())
        s_mun = salary
    elif username == u_info[0]  and (username,password) in user_info: #找到历史登录信息后,直接读取历史信息并打印余额
        print('welcome %s to loging...' % username)
        salary = datas['salary']
        s_mun = salary
        print('你的余额为 %s ' % datas['salary'])

    while not status:
        print('商品列表如下:')
        for index, item in enumerate(goods): #显示商品列表
            print(index, item)
        user_choise = input('请选着序号购买,按q退出,按t查看之前的消费记录,:').strip()
        if user_choise.isdigit():
            user_choise = int(user_choise)
            if user_choise = 0: #购买商品操作
                p_item = goods[user_choise]
                if p_item['price']  0:
                with open(cart_info_file, 'r+', encoding='utf8') as f:
                    f_list = f.readlines()
                    for p in list(set(pay_list)):
                        u_infos.append('('+p+':'+str(pay_list.count(p))+')')
                    if len(f_list) >0:
                        for line in f_list:
                            line1 = line
                            if '\''+username+'\'' in line: #替换历史消费信息
                                line = line.replace(line, '{\''+username+'\':{'+'\'pay_list'+'\':'+str(u_infos)+','+'\'password\''+':'+password+','+'\'salary'+'\':'+str(salary)+'}}\n')
                                read_str.append(line)
                            else:
                                read_str.append(line1)
                                line2 = '{\''+username+'\':{'+'\'pay_list'+'\':'+str(u_infos)+','+'\'password\''+':'+password+','+'\'salary'+'\':'+str(salary)+'}}\n'
                                read_str.append(line2)
                        f.seek(0)
                        f.truncate(0)
                        f.writelines(list(set(read_str)))
                    else:
                        f.write('{\''+username+'\':{'+'\'pay_list'+'\':'+str(u_infos)+','+'\'password\''+':'+password+','+'\'salary'+'\':'+str(salary)+'}}')
                print("\033[1m购买记录\033[0m".center(40, "-"))
                print('商品名称:'.center(20, " "), '数量:'.center(20, " "))
                for p in list(set(pay_list)):
                    print(p.center(20, " "), '*', str(pay_list.count(p)).center(20, " "))
                print("\033[1m购物总共花费{s_mun},余额还有:{_salary}\033[0m".format(s_mun=s_mun - salary, _salary=salary))
            status = True
        elif user_choise == 't': #查看历史消费记录
            if len(datas)>0:
                print('历史消费记录'.center(40,'-'))
                print('商品名称:'.center(20, " "), '数量:'.center(20, " "))
                for i in datas['pay_list']:
                    print(i.lstrip('(').rstrip(')').split(':')[0].center(20," "),'*',i.lstrip('(').rstrip(')').split(':')[1].center(20," "))
            else:
                print('你还没有历史消费记录!')
        else:
            print('你的选择有误,请重新输入!')

小结

本次主要考察了对python的基础知识的运用,当初认为是亮点的操作文件那段,现在看了写的真的是很low。 哈哈哈,毕竟是自己当时熬夜写出来的,记录一下。

继续阅读
shunzi
  • 本文由 发表于 2018-03-0815:52:58
  • 除非特殊声明,本站文章均为原创,转载请务必保留本文链接
deepin linux 15.11系统安装 BLOG

deepin linux 15.11系统安装

Deepin 15.11系统安装 window系统实在是太难用了,用了那么多linux系统,发现deepin系统真的是太好用了!特别推荐一下!!! 首先下载deepin系统ISO镜像,https://...
Python中字典的value是列表的运用 BLOG

Python中字典的value是列表的运用

今天群里一个朋友问了一个python问题,将列表a里的内容 转换成列表b那种格式,示例如下 a= 转换成: b= 简单来说 就是统计相同schema跟table的内容合并到一个list里面 一开始一直...
匿名

发表评论

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: