简陋版购物车 练习


goods_msg = '''
    0: '奥特曼',
    1: '钢铁侠',
    2: '《笨方法学python》',
    3: '泰国一日游',
    4: 'iphoneX',
    5: '娃娃',
    6: '阿拉丁',
    7: '特斯拉'
'''

goods_dict = {
    '0': '奥特曼',
    '1': '钢铁侠',
    '2': '《笨方法学python》',
    '3': '泰国一日游',
    '4': 'iphoneX',
    '5': '娃娃',
    '6': '阿拉丁',
    '7': '特斯拉'
}


username_info_list = []
shopping_car_dict = {}

def username_pwd_inp():
    username_inp = input('请输入你的用户名:').strip()
    pwd_inp = input('请输入你的密码:').strip()
    return username_inp, pwd_inp


def register():
    print('欢迎注册')
    username_inp, pwd_inp = username_pwd_inp()

    with open('user_info.txt', 'a', encoding='utf-8') as fa:
        fa.write(f'{username_inp}:{pwd_inp}\n')



def login():
    if username_info_list:
        print('已登录,不需要重复登录')
        return

    count = 0
    while count < 3:
        username_inp, pwd_inp = username_pwd_inp()
        with open('user_info.txt', 'r', encoding='utf-8') as fr:
            for user_info in fr:
                user_info = user_info.strip()
                username, pwd = user_info.split(':')

                if username_inp == username and pwd_inp == pwd:
                    print('登录成功')
                    username_info_list.append(username_inp)
                    return
                else:
                    print('登录失败')
                count += 1


def logout():
    if not username_info_list:
        print('请先登录')
        return

    username_info_list.clear()


def shopping():
    if not username_info_list:
        print('请先登录...')
        return

    print('欢迎来到购物天堂')

    while True:
        print(goods_msg)
        goods_choice = input('请输入你想要商品的编号(输入q退出):').strip()
        if goods_choice == 'q':
            break
        elif goods_choice not in goods_dict:
            print('没有这个商品')
            continue

        goods_name = goods_dict[goods_choice]

        if goods_name in shopping_car_dict:
            shopping_car_dict[goods_name] += 1
        else:
            shopping_car_dict[goods_name] = 1

        print(f'购买商品{goods_name}')
    print(f'购物车内商品:{shopping_car_dict}')



def shopping_car():
    if not username_info_list:
        print('请先登录...')
        return

    print(f'购物车内商品:{shopping_car_dict}')

    shopping_car_dict.clear()


func_msg = '''
1. 注册
2. 登录
3. 注销
4. 购物
5. 购物车
q. 退出
'''

func_dict = {
    '1': register,
    '2': login,
    '3': logout,
    '4': shopping,
    '5': shopping_car
}

while True:
    print(func_msg)

    choice = input('请输入你想要的功能(输入q退出):').strip()
    if choice == 'q':
        break

    if choice not in func_dict:
        print('傻逼,没有这么多功能')
        continue

    func_dict.get(choice)()
上一篇:day05


下一篇:函数 笔记+作业