使用python操作文件实现购物车程序

使用python操作文件实现购物车程序

题目要求如下:

题目要求

实现思路

始终维护一张字典,该字典里保存有用户账号密码,购物车记录等信息。在程序开始的时候读进来,程序结束的时候写回文件里去。在登录注册的部分,我添加3次登录失败锁定的小功能,以前不会这样实现,现在一并做进去了。

在程序运行的过程中,随时键入q程序就退出,如果是进入到购买阶段,则会打印相应信息。

测试生成器代码

import json

data = {
    'zsheng': {
        'pwd': 'z123',
        'lock': 0,
		'balance': 0,
        'login_times': 0,
		'goods': []
    },
    'xsheng': {
        'pwd': 'x123',
        'lock': 0,
		'balance': 0,
        'login_times': 0,
		'goods': []
    },
    'csheng': {
        'pwd': 'c123',
        'lock': 0,
		'balance': 0,
        'login_times': 0,
		'goods': []
    },
    'vsheng': {
        'pwd': 'v123',
        'lock': 0,
		'balance': 0,
        'login_times': 0,
		'goods': []
    }
}

f = open('data.json', mode='w', encoding='utf-8')
data2 = json.dumps(data)
f.write(data2)
f.close

完整实现代码

import json
f = open('data.json', mode='r+', encoding='utf-8')
my_data = json.loads(f.read())

# 登录验证模块 登录失败程序结束,登录成功则返回用户名
def login():
    while 1:
        username = input('Please input your username: ')
        if username == 'q':
            exit()
        if username not in my_data:
            print('Wrong username!')
            continue
        if username in my_data:
            if my_data[username]['lock'] == 1:
                print('Your account is locked! Refuse to login!')
                exit()
            count = 0
            while 1:
                count += 1
                if count > 3:
                    my_data[username]['lock'] = 1
                    f.seek(0)
                    f.write(json.dumps(my_data))
                    print('Your account is locked!')
                    exit()
                print('This is your %d time try!' % count)              
                password = input('Please input your password: ')
                if my_data[username]['pwd'] == password:
                    print('Welcome to login %s' % username)
                    return username
                elif password == 'q':
                    exit()
                else:
                    print('Wrong password, retry!')
                    continue
                
# 查询记录模块,可打印已购商品和余额信息
def print_cart(username):
    if my_data[username]['goods']:
        print('你的购物车物品如下:')
        for i in range(len(my_data[username]['goods'])):
            print(i, my_data[username]['goods'][i]['name'], my_data[username]['goods'][i]['price'])
    else:
        print('你的购物车里没有商品。')
    print('您还剩余\033[1;31;40m%s\033[0m元!' % my_data[username]['balance'])

# 购买商品模块
def shopping(username):
    while 1:
        print('本店在售的商品如下:')
        for i in range(len(goods)):
            print(i, goods[i]['name'], goods[i]['price'])
        no = input('please input goods number that you want to buy:')
        if no == 'q':
            print_cart(username)
            # 程序退出时把数据写入文件中
            f.seek(0)
            f.write(json.dumps(my_data))
            f.close()
            print('欢迎下次光临!')
            exit()
        elif no.isdigit():
            no = int(no)
            if not 0 <= no < len(goods):
                print('programme wrong!')
                exit()
            if my_data[username]['balance'] - goods[no]['price'] > 0:
                my_data[username]['balance'] -= goods[no]['price']
                my_data[username]['goods'].append(goods[no])
                print('物品\033[1;31;40m%s\033[0m已经添加到购物车!' % (goods[no]['name']))
                print('您还剩余\033[1;31;40m%s\033[0m元!' % my_data[username]['balance'])
            else:
                print('钱不够啦!')
                print('您还剩余\033[1;31;40m%s\033[0m元!' % my_data[username]['balance'])
                print('您要买的物品价值\033[1;31;40m%s\033[0m元!' % (goods[no]['price']))
                print('如需结束购买,请按q')
        else:
            print('programme wrong!')
            exit()    

goods = [
	{"name": "电脑", "price": 1999},
	{"name": "鼠标", "price": 10},
	{"name": "油条", "price": 20},
	{"name": "女票", "price": 998},
	{"name": "机械键盘", "price": 388},
	{"name": "降噪耳机", "price": 1234},
	{"name": "地狱火X6", "price": 7999},
	{"name": "Luffycity_python_course", "price": 99}
]

username = login()
my_data[username]['login_times'] += 1
print('这是你第 %d 次登录' % my_data[username]['login_times'])

if my_data[username]['login_times'] > 1:
    print('你上一次的消费记录如下:')
    print_cart(username)
    shopping(username)
else:
    budget = input("please input your salary: ") 
    if budget.isdigit():
	    budget = int(budget)
    else:
	    print('sorry you have no money!')
	    exit()
    my_data[username]['balance'] = budget
    print('start shopping, enter q to quit')
    shopping(username)
f.close()

posted @ 2018-04-18 16:05  阿胜4K  阅读(293)  评论(0编辑  收藏  举报