Python-购物车

要求:

1、允许用户选择购买商品的数量(输入:1 2);
例:
输入:1 2回车;
则购买num为1的商品,数量为2,不输入数量默认为1。
2、允许多用户登录,查看当前余额;
3、选择同样的商品,不打印多行;
4、允许用户查看之前的购买记录,并显示购买时间;

import json
import time

m_list=[
    '购买商品',
    '查看购买记录',
    '查看余额',
    '退出'
]

tupf = ("车辆类", "服装类", "家电类")
tups = [
    [("VW(Shanghai)",8000), ("SANTANA",70000), ("Phaeton",30000)],
    [("T-shirt",800), ("Jeep",700), ("Cat-fire",300)],
    [("Computer",1600), ("iphone",3750), ("TV",3000)]
]

exit_flag = False
#数据保存进文件
def save(file, data):
    with open(file, 'w') as f:
        json.dump(data, f)
#打印字典数据
def printData(data,t_flag):
    print("Your Shop Car".center(80, '*'))
    car_shop = data['buyHist']
    if t_flag:
        print("{a:^5}".format(a='Num'), "{a:<20}".format(a='Name'), "{a:>8}".format(a='Price'),
              "{a:>8}".format(a='Count'), "{a:>8}".format(a='Cost'), "{a:>20}".format(a='BuyTime'))
    else:
        print("{a:^5}".format(a='Num'), "{a:<20}".format(a='Name'), "{a:>8}".format(a='Price'),
              "{a:>8}".format(a='Count'), "{a:>8}".format(a='Cost'))
    i = 0
    total = 0
    for key in car_shop:
        i += 1
        obj_price = car_shop[key]['price']
        obj_count = car_shop[key]['count']
        obj_time = car_shop[key]['buyTime']
        total += obj_count * obj_price
        if t_flag:
            print("{a:^5}".format(a=str(i) + '.'), "{a:<20}".format(a=key), "{a:>8}".format(a=obj_price),
                  "{a:>8}".format(a=obj_count), "{a:>8}".format(a=obj_price * obj_count), "{a:>25}".format(a=obj_time))
        else:
            print("{a:^5}".format(a=str(i) + '.'), "{a:<20}".format(a=key), "{a:>8}".format(a=obj_price),
                  "{a:>8}".format(a=obj_count), "{a:>8}".format(a=obj_price * obj_count))
    print("{a:>44}".format(a='Total:'), "{a:>8}".format(a=total))
    print("END".center(80, '*'))
    # print("your salary\033[31;1m[%s]\033[0m" % user_salary)
#购买--函数
def buy(user_salary, exit_flag):
    data = {'salary': user_salary, 'buyHist': {}}

    while not exit_flag:
        data_list=ch_object(tupf, tups, [])
        shop_list=data_list.get('data')
        choose = data_list.get('num')
        input_on = choose.split()
        if input_on[0].isdigit():
            if int(input_on[0]) < len(shop_list):
                if user_salary >= shop_list[int(input_on[0])][1]:

                    if len(input_on) < 2:
                        count_num = 1
                    else:
                        count_num = int(input_on[1])
                    user_salary -= shop_list[int(input_on[0])][1]*count_num
                    data['salary'] = user_salary
                    if data['buyHist'].get(shop_list[int(input_on[0])][0]) is None:
                        data['buyHist'][shop_list[int(input_on[0])][0]] = \
                            {
                                'price': int(shop_list[int(input_on[0])][1]),
                                'count': count_num,
                                'buyTime':time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
                            }
                    else:
                        count_num = count_num + data['buyHist'][shop_list[int(input_on[0])][0]].get('count')
                        data['buyHist'][shop_list[int(input_on[0])][0]]['count'] = count_num
                    print("your input_on \033[33;1m[%s]\033[0m your balance\033[31;1m[%s]\033[0m" % (
                        shop_list[int(input_on[0])][0], user_salary))
                else:
                    print("\033[31;1m余额不足,请充值!\033[0m")
            else:
                print("false number!")
        elif input_on[0] == 'q' or input_on[0] == "quit":
            return data
            exit_flag = True
        elif input_on[0] == 'c' or input_on[0] == 'check':
            printData(data,False)
            print("your salary\033[31;1m[%s]\033[0m" % user_salary)
#打印三级菜单
def check(list):
    for i in range(len(list)):
        print(i + 1, list[i])
    return input("Choose(q-quit):")

# 三级菜单-----此处只为两层,三级参看上一篇
def ch_object(tupf, tups, mindex):
    data_num ={}
    if len(mindex) == 0:
        one = check(tupf)
        flag = tupf  # 设置标志位,为len判断长度做好准备
    elif len(mindex)==1:
        print("shop_list".center(40, '-'))
        for item in enumerate(tups[int(mindex[0])-1]):
            item_index = item[0]
            item_name = item[1][0]
            item_price = item[1][1]
            print(item_index, '.', item_name, item_price)
        print("END".center(40, '-'))
        one=input('Choose(q-quit/b-back):')
        if one.lower()=="b":
            mindex.pop()  # 将最后一个参数弹出
            return ch_object(tupf, tups, mindex)  # 准备返回上级
        else:

            data_num['data']=tups[int(mindex[0])-1]
            data_num['num']=one

            return data_num
    if one.lower() == "q" or one.lower()=='c':
        data_num['num'] = one.lower()
        return data_num
    elif not (one.isdigit()) or int(one) > len(flag):
        return ch_object(tupf, tups, mindex)
    else:
        mindex.append(one)  # 将输入添加到数组中
        return ch_object(tupf, tups, mindex)


#主要函数---
username = input("your name:")
with open('test.json', 'r') as f:
    data = json.load(f)
if data.get(username) is None:
    salary = input("your salary:")
    salary = int(salary)
    data[username]=buy( salary, exit_flag)
    save("test.json",data)
else:

    user_data = data.get(username)
    while not exit_flag:
        for item in enumerate(m_list):
            item_index = item[0] + 1
            item_content = item[1]
            print(item_index, '.', item_content)
        cho = input('your choose number:')
        if cho == '1':
            data[username] = buy(user_data['salary'], exit_flag)
            save("test.json", data)
        elif cho == '2':
            printData(user_data, True)
        elif cho == '3':
            print('账号余额\033[31;1m[%d]\033[0m'% user_data['salary'])
        elif cho == '4':
            exit_flag=True

此间出现的问题:
1、if-else 语句中

import sys
def test(a,mindex):
    if len(mindex)==0:
        print('1')#(1)
    else:
        return 1#(2)
    if a==2:
        sys.exit()
    else:
        print('digui')#(3)
        mindex.append(a)#(4)
        return test(a-1,mindex)#(5)


print(test(3,[]))
print('finished')

调试程序可以发现:程序执行顺序是(1)(3)(4)(5)(2)(5)
也是就是说当执行到(2)的return语句时候,程序还会跳到(5)的return,但是(3)(4)并没有执行!猜想是因为有两个if-else块,俩个else是平级,所以return都会执行(没有道理的猜想),于是继续测试:

import sys
def test(a,mindex):
    if len(mindex)==0:#(1)
        print('1')#(2)
        if a == 2:
            sys.exit()
        else:
            print('digui')#(3)
            mindex.append(a)#(4)
            return test(a - 1, mindex)#(5)
    else:
        return 1#(6)
print(test(3,[]))
print('finished')

将代码改成这样,程序执行顺序(1,2,3,4,5,1,6,5),我天!居然从(6)的return跳上去找(5)的return,颠覆小白的世界观喽~~求解呀
2、打印有中文字符的时候,"{a:<8}".format(a='hello')讲道理是hello站8个字符,不够的用空白填充,但是换成a换成中文,各种错位,但是我测试了一下,python3中一个汉字就是一个字节呀

s='我们'
s1='wo'
print(len(s))
print(len(s1))
#输出结果:
#2
#2

有点懵。。我想静静。。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值