3_python之路之商城购物车

python之路之商城购物车

 

1.程序说明:Readme.txt

 

1.程序文件:storeapp_new.py userinfo.py

2.程序文件说明:storeapp_new.py-主程序    userinfo.py-存放字典数据

3.python版本:python-3.5.3

4.程序使用:将storeapp_new.py和userinfo.py放到同一目录下, python storeapp_new.py

5.程序解析:

    (1)允许用户注册登陆认证
    (2)允许用户初始化自己拥有的金钱
    (3)允许用户使用序号购买商品
    (4)用户结束购买时自动结算余额及打印这次购买的商品列表
    (5)允许用户再次登陆并打印历史购买商品列表及余额
    (6)允许用户再次购买商品,直到余额小于选择的商品价格
    (7)不允许退货,购买前请三思和掂量一下自己的钱包

6.程序执行结果:请亲自动手执行或者查看我的博客

7.程序博客地址:http://www.cnblogs.com/chenjw-note/p/7724580.html

8.优化打印输出效果

 

2.程序代码:storeapp_new.py

 

#!/usr/bin/env python
# _*_ coding: utf-8 _*_
# author:chenjianwen
# email:1071179133@qq.com
# update_time:2017-10-17 19:47
# blog_address:www.cnblogs.com/chenjw-note
# If this runs wrong, don't ask me, I don't know why;
# If this runs right, thank god, and I don't know why.
# Maybe the answer, my friend, is blowing in the wind.
def print_red(messages):
    print('33[1;35m %s 33[0m' %messages)
##绿色
def print_green(messages):
    print('33[1;32m %s 33[0m' %messages)
##黄色
def print_yellow(messages):
    print('33[1;33m %s 33[0m' %messages)

import os,sys,time,json,getpass
#import Login_api_new as LA
import userinfo as UF


commodity_list = [
    ['华为meta 10',6999],
    ['iphone X',9999],
    ['游戏主机',19999],
    ['曲面显示屏',2999],
    ['游戏本',7999],
    ['机械键盘',599]
]

##定义写入文件函数,下面函数2次调用
def write_into():
    f = open('./userinfo.py', 'w', encoding='utf-8')
    f.write('UserInfo = ')
    json.dump(UF.UserInfo, f)
    f.close()
    '''如果字典是汉字,存到文本就是二进制字符,这种字符计算机认识就可以了
       如果字典是英文,存到文件就是英文了
    '''

##登陆程序函数
def LoginApi():
    count = 0
    while True:
        select_info = input("你是否有注册过账号了? Please select Y/N:")
        ##用户注册信息
        if select_info == 'N' or select_info == 'n':
            print("开始注册用户信息:")
            username = input("Please enter your username:")
            password = input("Please enter your password:")  ##此处暂时用明文密码,方便在pycharm调试
            phone_number = input("Please enter your phon_number:")
            UF.UserInfo[username] = {
                    "info":[
                        {
                            "username":"%s" %username,
                            "password":"%s" %password,
                            "phon_number":"%s" %phone_number,
                            "login_count":0
                        }
                    ],
                    "money":[
                        {}
                    ],
                    "already_get_commodity":[
                        {}
                    ],
            }
            #print(UF.UserInfo)
            write_into()

        ##用户登陆验证信息
        elif select_info == 'Y' or select_info == 'y':
            #count = 0
            while True:
                #print(userinfo)
                print("开始登录验证信息:")
                username = input("Please enter your username:")
                password = input("Please enter your password:")
                ##第一次判断输入用户是否存在
                if not username in UF.UserInfo:
                    print("没有该用户,请确认你的用户名!")
                    continue
                #判断用户登陆失败的次数是否小于3
                if UF.UserInfo[username]['info'][0]['login_count'] < 3:
                    ##判断用户账号密码是否吻合
                    if username in UF.UserInfo and password == UF.UserInfo[username]['info'][0]['password']:       ##【优化2次】用户及密码已经一一对应
                        print("welcom login {_username}".format(_username=username))
                        ##登陆成功后将失败次数清零,便于下一次统计
                        UF.UserInfo[username]['info'][0]['login_count'] = 0
                        ##返回username给后面函数调用
                        return username
                        #break
                    else:
                        #count += 1
                        ##修改用户登陆失败的次数
                        UF.UserInfo[username]['info'][0]['login_count'] = UF.UserInfo[username]['info'][0]['login_count'] + 1
                        print('Check fail...Check again...')
                        print("您还有%s次登录机会" % (3 - UF.UserInfo[username]['info'][0]['login_count']))
                        continue
                else:
                    print("重复登陆多次失败,请15分钟后再尝试登陆...")
                    time.sleep(15)
                    count = 0
                    continue
        else:
            print("您输入的内容错误! Please enter again...")
            continue


##商城购物函数
def Get_commodity(username):
    already_get_commodity = []
    if UF.UserInfo[username]['money'][0]:
        print("你的余额为:33[1;32m %s元 33[0m,你的购买历史如下:" % UF.UserInfo[username]['money'][0]['money'])
        for i in UF.UserInfo[username]['already_get_commodity']:
            if i:
                print('#   ',i['ID'], i['商品'], i['价格'])
        print_yellow('购物历史清单End'.center(25,'#'))
    while True:
        if not UF.UserInfo[username]['money'][0]:
            money = input("请输入你拥有的金额:")
            if money.isdigit():
                money = int(money)
                UF.UserInfo[username]['money'][0]['money'] = '%s' % money
                break
            else:
                print("请输入数字金额!")
                continue
        else:
            break

    while True:
        while True:
            print(' ')
            print_red('商品列表'.center(25,'#'))
            print("#   序号 商品  价格")
            ##获取商品列表
            for key,commodity in enumerate(commodity_list):
                print('#   ',key,commodity[0],commodity[1])
            print(' ')
            get_commodity = input("33[1;35m请选择你购买商品的序号:33[0m")
            ##得到商品序号
            if get_commodity.isdigit() and int(get_commodity) < len(commodity_list):
                get_commodity = int(get_commodity)
                ##判断商品价格是否大于用户金钱数
                if commodity_list[get_commodity][1] <= int(UF.UserInfo[username]['money'][0]['money']):
                    ##计算用户金钱数
                    real_money = int(UF.UserInfo[username]['money'][0]['money']) - int(commodity_list[get_commodity][1])
                    money = real_money
                    ##把当前购买的商品信息写到已购买商品的信息字典
                    already_get_commodity.append(['%s' %get_commodity,'%s' %commodity_list[get_commodity][0],'%s' %commodity_list[get_commodity][1]])
                    #print(already_get_commodity)
                    print("购买商品33[1;32m %s 33[0m成功,你余额为33[1;32m %s元 33[0m" %(commodity_list[get_commodity][0],money))
                    ##追加总商品信息到字典
                    UF.UserInfo[username]['already_get_commodity'].append({"ID": "%s" %get_commodity, "商品": "%s" %commodity_list[get_commodity][0], "价格": "%s" %commodity_list[get_commodity][1]})
                    ##修改用户信息剩余金钱
                    UF.UserInfo[username]['money'][0]['money'] = '%s' %money
                    #print(UF.UserInfo)
                else:
                    print("你没有足够的金钱去购买33[1;35m %s 33[0m,它的价格为33[1;35m %s元 33[0m,而你的余额为33[1;35m %s元 33[0m" %(commodity_list[get_commodity][0],commodity_list[get_commodity][1],UF.UserInfo[username]['money'][0]['money']))
                print(' ')
                per_select = input("请问是否继续购买商品33[1;35my/n33[0m:")
                if per_select.startswith('y'):
                    continue
                elif per_select.startswith('n'):
                    print(' ')
                    print("33[1;32m你本次购买的商品如下:33[0m")
                    print_red('商品列表'.center(25, '#'))
                    print("#   序号 商品  价格")
                    for already_getp in already_get_commodity:
                        print('#   ',already_getp[0],already_getp[1],already_getp[2])
                    print("你的余额为:33[1;32m %s元 33[0m" %UF.UserInfo[username]['money'][0]['money'])
                    print_red('结算结束'.center(25, '#'))
                    ##退出程序前,把所有信息写进json信息记录文件,以便下一次登陆提取
                    write_into()
                    return
            else:
                print("输入有错,请重新输入!")
                continue

if __name__ == '__main__':
    username = LoginApi()
    if True:
        Get_commodity(username)

 

3.程序附件-数据库:userinfo.py

UserInfo = {"chenjianwen01": {"info": [{"phon_number": "123", "password": "123", "login_count": 0, "username": "chenjianwen01"}], "money": [{"money": "848892"}], "already_get_commodity": [{}, {"u5546u54c1": "iphone X", "u4ef7u683c": "9999", "ID": "1"}, {"u5546u54c1": "u6e38u620fu4e3bu673a", "u4ef7u683c": "19999", "ID": "2"}, {"u5546u54c1": "u534eu4e3ameta 10", "u4ef7u683c": "6999", "ID": "0"}, {"u5546u54c1": "u66f2u9762u663eu793au5c4f", "u4ef7u683c": "2999", "ID": "3"}]}, "chenjianwen03": {"info": [{"phon_number": "12345678", "password": "root123456.", "login_count": 0, "username": "chenjianwen03"}], "money": [{"money": "77001"}], "already_get_commodity": [{}, {"ID": "3", "u4ef7u683c": "2999", "u5546u54c1": "u66f2u9762u663eu793au5c4f"}, {"ID": "2", "u4ef7u683c": "19999", "u5546u54c1": "u6e38u620fu4e3bu673a"}]}, "chenjianwen02": {"info": [{"phon_number": "123", "password": "123", "login_count": 0, "username": "chenjianwen02"}], "money": [{}], "already_get_commodity": [{}]}}

4.程序执行输出

old:

原文地址:https://www.cnblogs.com/chenjw-note/p/7724580.html