购物车程序

2018-07-18 01:15:59来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

本人在自学python编程,下面的程序是利用两天时间完成的,有错误或者不足的地方,请指出!

购物车程序分为三个部分
#1,下面代码是程序开始部分,用于读取用户信息
 1 # -*- coding:utf-8 -*-
 2 user_info = 'shopping_cart'
 3 user_info_dict={}#读取数据库信息,并存成字典
 4 uname_info = [] #存入用户登录信息,用于购物
 5 while True:
 6     with open(user_info,'r',encoding='utf-8') as f:#先读取数据库信息
 7         for line in f:
 8             shopping_cart = {}
 9             line = line.strip().split(',')
10             if len(line) > 3:
11                 goods_list_temp = line[3::]
12                 for i in range(0,len(goods_list_temp),5):
13                     shopping_cart[goods_list_temp[i]]={}
14                     for j in range(i+1,i+5,2):
15                         shopping_cart[goods_list_temp[i]][goods_list_temp[j]] = goods_list_temp[j+1]
16             user_info_dict[line[0]] = {
17                 'password':line[1],
18                 'lock_status':0,
19                 'balance':line[2],
20                 'shopping_car':shopping_cart,
21             }
22 
23     msg = '''
24     1 登录
25     2 注册
26     3 购物
27     '''
28     print(msg)
29     choice = input('\033[32;1m输入服务编号>>:\033[0m').strip()
View Code

#2,第一块功能,用户注册

 1 #第一步注册
 2     if choice == '2':
 3         print('------正在注册------')
 4         user_list_record = []  #临时存放注册用户信息
 5         while True:
 6             choice_name = input('\033[33;1m请输入用户名>>:\033[0m').strip()
 7             if choice_name in user_info_dict:#判断用户是否已存在
 8                 print('\033[31;1m用户已存在,请重新输入...>>:\033[0m')
 9                 continue
10             choice_pwd_f = input('\033[33;1m请输入密码>>:\033[0m').strip()
11             choice_passwd_s = input('\033[33;1m请再次输入密码>>:\033[0m').strip()
12             if choice_pwd_f != choice_passwd_s: #判断密码是否一致
13                 print('\033[31;1m密码不一致!请重新输入....\033[0m')
14                 continue
15             else:
16                 choice_labary = input('\033[33;1m注册成功!\n请输入额度>>:\033[0m')
17                 user_list_record=[choice_name,choice_pwd_f,choice_labary]
18                 break
19         user_list_record_write = ','.join(user_list_record)#把注册信息写入到文本
20         with open(user_info,'a',encoding='utf-8') as f:
21             f.write(user_list_record_write+'\n')
View Code

#3,第二块功能,用户登录

 1  #第二步登录
 2     elif choice == '1':
 3         if len(user_info_dict) == 0:
 4             print('无用户信息,请注册!')
 5             continue
 6         print('------欢迎登录------')
 7         while True:
 8             name_inp = input('\033[35;1m用户名>>:\033[0m')
 9             if name_inp not in user_info_dict:
10                 print('\033[31;1m用户不存在!\033[0m')
11                 continue
12 
13             with open('db','r',encoding='utf-8') as f:#读取锁定账户信息
14                 line = f.read().strip()
15                 if name_inp in line:
16                     print('%s账户已被锁定'%name_inp)
17                     break
18 
19             if user_info_dict[name_inp]['lock_status'] > 2:
20                 print('\033[31;1m尝试次数过多,账户已被锁定!:\033[0m')
21                 with open('db','a',encoding='utf-8') as f:
22                     f.write('%s |'%name_inp)
23                 break
24 
25 
26             pwd_inp = input('\033[35;1m密码>>:\033[0m')
27             if pwd_inp == user_info_dict[name_inp]['password']:
28                 uname_info=[name_inp,user_info_dict[name_inp]['balance']]
29                 print('\033[36;1m登录成功!用户名:%s ;余额: %s \033[0m'%(uname_info[0],uname_info[1]))
30                 break
31             else:
32                 print('\033[31;1m密码错误!重新输入!:\033[0m')
33                 user_info_dict[name_inp]['lock_status'] += 1
View Code

#4,第三块功能,购物

 1  elif choice == '3':
 2         if len(uname_info) == 0:
 3             print('请先登录')
 4             continue
 5         print('欢迎进入购物商城,祝您购物愉快!')
 6         print('\033[36;1m用户信息>>>   用户名:%s ;余额: %s \033[0m'%(uname_info[0],user_info_dict[uname_info[0]]['balance']))
 7         goods_cart = []  #存放购物信息
 8         while True:
 9             price_sum = 0 #定义购买商品总价格
10             balance_m = int(user_info_dict[uname_info[0]]['balance'])#把字典内商品价格转换为整型,进行价格运算
11             goods = [
12                 {"name":"电脑","price":'2000'},
13                 {"name":"鼠标","price":'10'},
14                 {"name":"游艇","price":'20'},
15                 {"name":"美女","price":'100'},
16             ]
17             print('-------商品列表-------'+'\n','编号   名称   价格')
18             for index,line in enumerate(goods):
19                 print(' %s     %s     %s'%(index,line['name'],line['price']))
20             choice_g = input('请输入购买物品编号>>:').strip()
21             if choice_g.isdigit():
22                 choice_g = int(choice_g)
23                 if choice_g >=0 or choice_g < len(goods):
24                     buy_num = int(input('请输入购买件数>>:').strip()) #购买商品的个数
25                     goods[choice_g]['count'] = 0
26                     goods[choice_g]['count'] += buy_num
27                     goods[choice_g]['count'] =str(goods[choice_g]['count'])
28 
29                     goods_cart.append(goods[choice_g]) #购买的商品添加到购物车
30                     print('商品%s成功加入购物车,退出结算请输入q'%goods[choice_g])
31                 else:
32                     print('没有此商品!')
33             if choice_g == 'q':
34                 goods_list = '''
35                 ---------------------已购买商品列表-------------------
36                     商品编号       商品名称      商品价格     商品个数
37                 '''
38                 print(goods_list)
39                 for index,line in enumerate(goods_cart):
40                     print('                         %s              %s          %s         %s'%(index,line['name'],line['price'],line['count']))
41                     price_sum += int(line['price'])*int(line['count'])
42                 print('账户余额:%s'%user_info_dict[uname_info[0]]['balance'],''.center(60),'价格总计: %s'%price_sum)
43                 choice_goods_math = input('               商品结算或退出请输入yes/no:').strip()
44                 if choice_goods_math == 'no':break
45                 if choice_goods_math == 'yes':
46                     if balance_m >= price_sum:
47                         user_info_to_write = []
48                         price_inp = balance_m - price_sum
49                         price_inp = str(price_inp)
50                         user_info_dict[uname_info[0]]['balance']=price_inp #把结算后的价格存入字典内
51                         for line in goods_cart:#把购物信息存入购物字典内
52                             user_info_dict[uname_info[0]]['shopping_car'][line['name']] = {
53                                 'count':line['count'],
54                                 'price':line['price']
55                             }
56                         for username in user_info_dict.keys():#读取内存中的用户信息,并写入到数据库中
57                             user_info_list = [username]
58                             user_temp_list = []
59                             for item in user_info_dict[username].keys():
60                                 if item == 'shopping_car' and user_info_dict[username].get('shopping_car'):
61                                     for name in user_info_dict[username][item].keys():
62                                         user_temp_list.append(name)
63                                         for i in [list(i)for i in user_info_dict[username][item][name].items()]:
64                                             user_temp_list.extend(i)
65                                     user_info_list.extend(user_temp_list)
66                                 else:
67                                     good_s = user_info_dict[username][item]
68                                     if good_s:
69                                         user_info_list.append(good_s)
70                             user_info_to_write = user_info_list
71                         goods_to_write = ','.join(user_info_to_write)
72                         with open(user_info,'w',encoding='utf-8') as f:#把购物信息写入数据库中(文本文件)
73                             f.write(goods_to_write+'\n')
74                         print('购物总消费: %s   余额: %s'%(price_sum,price_inp))
75                         break
76                     else:
77                         print('余额不足请充值! 余额:%s'%user_info_dict[uname_info[0]]['balance'])
78                         inp_money = int(input('请输入充值金额:').strip())
79                         money = inp_money + int(user_info_dict[uname_info[0]]['balance'])
80                         user_info_dict[uname_info[0]]['balance'] =str(money)
View Code

#剩下的代码

1     elif choice == 'q':
2         print('已退出购物商城')
3         break
4     else:
5         print('输入字符非法!')

 

整体代码如下:
# -*- coding:utf-8 -*-
user_info = 'shopping_cart'
user_info_dict={}#读取数据库信息,并存成字典
uname_info = [] #存入用户登录信息,用于购物
while True:
    with open(user_info,'r',encoding='utf-8') as f:#先读取数据库信息
        for line in f:
            shopping_cart = {}
            line = line.strip().split(',')
            if len(line) > 3:
                goods_list_temp = line[3::]
                for i in range(0,len(goods_list_temp),5):
                    shopping_cart[goods_list_temp[i]]={}
                    for j in range(i+1,i+5,2):
                        shopping_cart[goods_list_temp[i]][goods_list_temp[j]] = goods_list_temp[j+1]
            user_info_dict[line[0]] = {
                'password':line[1],
                'lock_status':0,
                'balance':line[2],
                'shopping_car':shopping_cart,
            }

    msg = '''
    1 登录
    2 注册
    3 购物
    '''
    print(msg)
    choice = input('\033[32;1m输入服务编号>>:\033[0m').strip()

    #第一步注册
    if choice == '2':
        print('------正在注册------')
        user_list_record = []  #临时存放注册用户信息
        while True:
            choice_name = input('\033[33;1m请输入用户名>>:\033[0m').strip()
            if choice_name in user_info_dict:#判断用户是否已存在
                print('\033[31;1m用户已存在,请重新输入...>>:\033[0m')
                continue
            choice_pwd_f = input('\033[33;1m请输入密码>>:\033[0m').strip()
            choice_passwd_s = input('\033[33;1m请再次输入密码>>:\033[0m').strip()
            if choice_pwd_f != choice_passwd_s: #判断密码是否一致
                print('\033[31;1m密码不一致!请重新输入....\033[0m')
                continue
            else:
                choice_labary = input('\033[33;1m注册成功!\n请输入额度>>:\033[0m')
                user_list_record=[choice_name,choice_pwd_f,choice_labary]
                break
        user_list_record_write = ','.join(user_list_record)#把注册信息写入到文本
        with open(user_info,'a',encoding='utf-8') as f:
            f.write(user_list_record_write+'\n')

    #第二步登录
    elif choice == '1':
        if len(user_info_dict) == 0:
            print('无用户信息,请注册!')
            continue
        print('------欢迎登录------')
        while True:
            name_inp = input('\033[35;1m用户名>>:\033[0m')
            if name_inp not in user_info_dict:
                print('\033[31;1m用户不存在!\033[0m')
                continue

            with open('db','r',encoding='utf-8') as f:#读取锁定账户信息
                line = f.read().strip()
                if name_inp in line:
                    print('%s账户已被锁定'%name_inp)
                    break

            if user_info_dict[name_inp]['lock_status'] > 2:
                print('\033[31;1m尝试次数过多,账户已被锁定!:\033[0m')
                with open('db','a',encoding='utf-8') as f:
                    f.write('%s |'%name_inp)
                break


            pwd_inp = input('\033[35;1m密码>>:\033[0m')
            if pwd_inp == user_info_dict[name_inp]['password']:
                uname_info=[name_inp,user_info_dict[name_inp]['balance']]
                print('\033[36;1m登录成功!用户名:%s ;余额: %s \033[0m'%(uname_info[0],uname_info[1]))
                break
            else:
                print('\033[31;1m密码错误!重新输入!:\033[0m')
                user_info_dict[name_inp]['lock_status'] += 1

    #第三步购物
    elif choice == '3':
        if len(uname_info) == 0:
            print('请先登录')
            continue
        print('欢迎进入购物商城,祝您购物愉快!')
        print('\033[36;1m用户信息>>>   用户名:%s ;余额: %s \033[0m'%(uname_info[0],user_info_dict[uname_info[0]]['balance']))
        goods_cart = []  #存放购物信息
        while True:
            price_sum = 0 #定义购买商品总价格
            balance_m = int(user_info_dict[uname_info[0]]['balance'])#把字典内商品价格转换为整型,进行价格运算
            goods = [
                {"name":"电脑","price":'2000'},
                {"name":"鼠标","price":'10'},
                {"name":"游艇","price":'20'},
                {"name":"美女","price":'100'},
            ]
            print('-------商品列表-------'+'\n','编号   名称   价格')
            for index,line in enumerate(goods):
                print(' %s     %s     %s'%(index,line['name'],line['price']))
            choice_g = input('请输入购买物品编号>>:').strip()
            if choice_g.isdigit():
                choice_g = int(choice_g)
                if choice_g >=0 or choice_g < len(goods):
                    buy_num = int(input('请输入购买件数>>:').strip()) #购买商品的个数
                    goods[choice_g]['count'] = 0
                    goods[choice_g]['count'] += buy_num
                    goods[choice_g]['count'] =str(goods[choice_g]['count'])

                    goods_cart.append(goods[choice_g]) #购买的商品添加到购物车
                    print('商品%s成功加入购物车,退出结算请输入q'%goods[choice_g])
                else:
                    print('没有此商品!')
            if choice_g == 'q':
                goods_list = '''
                ---------------------已购买商品列表-------------------
                    商品编号       商品名称      商品价格     商品个数
                '''
                print(goods_list)
                for index,line in enumerate(goods_cart):
                    print('                         %s              %s          %s         %s'%(index,line['name'],line['price'],line['count']))
                    price_sum += int(line['price'])*int(line['count'])
                print('账户余额:%s'%user_info_dict[uname_info[0]]['balance'],''.center(60),'价格总计: %s'%price_sum)
                choice_goods_math = input('               商品结算或退出请输入yes/no:').strip()
                if choice_goods_math == 'no':break
                if choice_goods_math == 'yes':
                    if balance_m >= price_sum:
                        user_info_to_write = []
                        price_inp = balance_m - price_sum
                        price_inp = str(price_inp)
                        user_info_dict[uname_info[0]]['balance']=price_inp #把结算后的价格存入字典内
                        for line in goods_cart:#把购物信息存入购物字典内
                            user_info_dict[uname_info[0]]['shopping_car'][line['name']] = {
                                'count':line['count'],
                                'price':line['price']
                            }
                        for username in user_info_dict.keys():#读取内存中的用户信息,并写入到数据库中
                            user_info_list = [username]
                            user_temp_list = []
                            for item in user_info_dict[username].keys():
                                if item == 'shopping_car' and user_info_dict[username].get('shopping_car'):
                                    for name in user_info_dict[username][item].keys():
                                        user_temp_list.append(name)
                                        for i in [list(i)for i in user_info_dict[username][item][name].items()]:
                                            user_temp_list.extend(i)
                                    user_info_list.extend(user_temp_list)
                                else:
                                    good_s = user_info_dict[username][item]
                                    if good_s:
                                        user_info_list.append(good_s)
                            user_info_to_write = user_info_list
                        goods_to_write = ','.join(user_info_to_write)
                        with open(user_info,'w',encoding='utf-8') as f:#把购物信息写入数据库中(文本文件)
                            f.write(goods_to_write+'\n')
                        print('购物总消费: %s   余额: %s'%(price_sum,price_inp))
                        break
                    else:
                        print('余额不足请充值! 余额:%s'%user_info_dict[uname_info[0]]['balance'])
                        inp_money = int(input('请输入充值金额:').strip())
                        money = inp_money + int(user_info_dict[uname_info[0]]['balance'])
                        user_info_dict[uname_info[0]]['balance'] =str(money)
    elif choice == 'q':
        print('已退出购物商城')
        break
    else:
        print('输入字符非法!')
View Code

 

 

账户锁定文本是db

alex |egon |

  

用户信息和购物信息在文本shopping_cart

alex,abc,4490,美女,count,5,price,100,鼠标,count,20,price,10,电脑,count,1,price,2000

  

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:室友最近情绪很不稳定!只好用Python来进行情绪分析!此技乃神技

下一篇:网络爬虫基础知识(Python实现)