购物车练习

#
# 作者:倪周强
#


import os
import time

goods = [
    {'name': 'Iphone 8', 'price': 7999},
    {'name': 'Xiaomi 6', 'price': 2399},
    {'name': 'Huawei Mate10', 'price': 4999},
    {'name': 'One plus 5', 'price': 2999},
    {'name': 'Meizu pro 7', 'price': 2799},
]
user_profile = {'username': 'john', 'password': '123', 'account_balance': 0}
user_cart = []

username = input('请输入用户名:').lower().strip()
password = input('请输入密码:').strip()

if username == user_profile['username'] and password == user_profile['password']:  # 只有通过认证,才写文件

    need_salary = True  # 默认第一次是需要输入工资的
    if os.path.exists('account_balance'):  # 如果文件存在,说明不是第一次,不需要输入工资
        f = open('account_balance', 'r')
        salary_sum = f.read()
        if salary_sum.isdigit():
            user_profile['account_balance'] = int(salary_sum)
        f.close()
        need_salary = False
    else:  # 说明文件不存在,是第一次,就需要输入工资
        f = open('account_balance', 'w')
        f.write(str(user_profile['account_balance']))
        f.close()

    if os.path.exists('shopping_record'):  # 如果不存在消费记录文件,那是第一次,需要创建;如果存在,说明不是第一次
        pass
    else:
        f = open('shopping_record', 'w')
        f.close()

    if not need_salary:  # 如果不是第一次,不需要输入工资
        pass
    else:  # 如果是第一次,那需要输入工资
        while True:
            salary = input('请输入工资金额:').strip()
            if len(salary) != 0 and salary.isdigit():  # 输入的必须是数字,且不为空,计入余额文件
                user_profile['account_balance'] = int(salary)
                f = open('account_balance', 'w')
                f.write(str(user_profile['account_balance']))
                f.close()
                break
            else:
                print('请输入正确的工资!')

    while True:
        choice_option = '''
                -----------------------
                1. 购物
                2. 查看账户余额
                3. 查看历史消费记录
                4. 退出
                -----------------------
                '''
        print(choice_option)  # 打印菜单
        first_choice = input('请选择: ').strip()  # 选择菜单,不为空,且是1-4的数字
        if len(first_choice) != 0 and first_choice.isdigit() and int(first_choice) in range(1, 5):
            if int(first_choice) == 2:  # 查看余额,从文件里读取
                f = open('account_balance', 'r')
                salary_sum = f.read()
                if salary_sum.isdigit():
                    user_profile['account_balance'] = int(salary_sum)
                print('您的账户余额是: %s 元' % (user_profile['account_balance']))
            elif int(first_choice) == 3:  # 查看消费记录,从文件里读取
                f = open('shopping_record', 'r')
                data = f.read()
                if len(data) == 0:
                    print('没有消费记录!')
                else:
                    print(data)
                f.close()
            elif int(first_choice) == 4:  # 退出
                print('再见!')
                break
            else:  # 购买
                user_cart = []  # 每新的一轮购买前,都要清空购物车
                f = open('account_balance', 'r')  # 读取余额
                salary_sum = f.read()
                if salary_sum.isdigit():
                    user_profile['account_balance'] = int(salary_sum)
                while True:
                    print('商品列表'.center(30, '-'))  # 打印商品列表
                    for i in goods:
                        print('%s. %s %s 元' % (goods.index(i) + 1, (i['name'] + '').ljust(18, '-'), i['price']))
                    print('-'.ljust(34, '-'))
                    choice = input('请输入想购买的商品编号(退出请输入‘q’):')
                    if len(choice) == 0:  # 不能是空的输入
                        print('请输入正确的商品序号!')
                    elif choice.isdigit():  # 输入的数字要在列表范围内
                        if int(choice) in range(1, len(goods) + 1):
                            if user_profile['account_balance'] >= goods[int(choice) - 1]['price']:
                                user_cart.append(goods[int(choice) - 1])  # 余额足够,可以购买
                                user_profile['account_balance'] -= goods[int(choice) - 1]['price']
                                print('已购买一件该商品[%s],花费 %s 元,您的余额为: %s 元' %
                                      (user_cart[-1]['name'], user_cart[-1]['price'], user_profile['account_balance']))
                            else:
                                print('余额不足,不能购买该商品。')
                                print('您的余额为: %s 元' % (user_profile['account_balance']))
                        else:
                            print('请输入正确的商品序号!')
                    elif choice == 'q':  # 退出
                        break
                    else:
                        print('请输入正确的商品序号!')
                cart_list = []  # 新的列表保存商品名字
                for i in user_cart:
                    cart_list.append(i['name'])
                cart_set = set(cart_list)  # 用商品名字的列表来生成集合,是为了去除重复商品
                if not any(cart_set):
                    print('您的购物车是空的。')
                else:
                    print('您的购物清单'.center(42, '-'))
                    set_index = 0
                    for i in cart_set:  # 打印购物清单,名字从集合里取,所以不会重复,数量从列表里取
                        set_index += 1
                        print('%s. %s 数量:%s' % (set_index, i.ljust(18, '-'), cart_list.count(i)))
                print('您的余额为: %s 元' % (user_profile['account_balance']))
                print('-'.center(48, '-'))

                f = open('account_balance', 'w')  # 余额写入文件保存
                f.write(str(user_profile['account_balance']))
                f.close()

                f = open('shopping_record', 'a')  # 购物清单写入文件保存,空的购物车不写入
                if not any(cart_set):
                    f.close()
                else:
                    f.write((' %s 的购物记录' % (time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))) 
                            .center(42, '-') + '
')
                    set_index = 0
                    for i in cart_set:
                        set_index += 1
                        f.write('%s. %s 数量:%s' % (set_index, i.ljust(18, '-'), cart_list.count(i)) + '
')
                    f.write('-'.center(47, '-') + '
')
                    f.write('
')
                    f.close()
        else:
            print('请输入正确的序号!')  # 要输入正确的菜单序号,必须有输入,并且是1-4的数字

else:
    print('认证失败,再见!')  # 用户名或密码错误,退出程序
wechat: nick753159 qq: 417966852 email: nzq42@qq.com base: shanghai
原文地址:https://www.cnblogs.com/cyberbit/p/shopping_cart.html