代码-注册\登录\购物车\主菜单

注册\登录\购物车\主菜单

def Register():
    tag=True
    while tag:
        username_reg=input('Please enter your name:').strip()

        # 检测用户名是否已经注册
        with open(r'user.txt','a',encoding='utf-8') as fa,open(r'user.txt','r',encoding='utf-8') as fr:
            f1=fr.read()
            if username_reg in f1:
                print('The username has been registered!')
                continue
            # 输入密码写入文件
            else:
                pwd_reg = input('Please enter you password:').strip()
                fa.write(username_reg + ':' + pwd_reg + '\n')
                print('Registered successfully')
                tag=False
    Action()


def Login():
    name_pwd_dict = {}
    login_count=0
    while login_count < 4:
        login_count+=1

        if login_count == 4:
            break

        username_log = input('Please enter your name:').strip()
        pwd_log = input('Please enter you password:').strip()

        #读文件获取用户列表
        with open(r'user.txt','r',encoding='utf-8') as fr:
            for line in fr:
                users_list=line.strip().split(':')
                name_pwd_dict[users_list[0]]=users_list[1]
            if pwd_log!=name_pwd_dict.get(username_log):
                print('Incurrect username or password!')
                continue
            print('Login successful!')
            Shopping()



def Shopping():
    buy_list = {}
    fruit_list = []

    with open(r'fruit_list.txt','r',encoding='utf-8') as fr :
        for line in fr:
            fruit=line.strip()
            fruit_list.append(fruit)

    # 打印商品清单
    for i in range(len(fruit_list)):
        print(f'{i}:{fruit_list[i]}')


    while True:
        fruit_choice=input('Please enter what you want,or enter N to end shopping:').strip()

        if fruit_choice!='N':
            get_fruit = fruit_list[int(fruit_choice)]
            if buy_list.get(get_fruit):
                buy_list[get_fruit]+=1
            else:
                buy_list[get_fruit]=1
        else:
            break
        # 打印购物车列表
        for j in buy_list:
            print(f'{j}:{buy_list[j]}')
    print(f"You've already bought {buy_list}, Welcome next time!")

    # 写入文件
    with open(r'fruit_shopping_list.txt','a',encoding='utf-8') as fa:
        fa.write(str(buy_list)+'\n')
        fa.close()
        return None


def Action():

    # action_list字典仅用于展示
    action_list={
        0:'Register',
        1:'Login',
        2:'Shopping',
        3:'Quit'
    }

    # action_list1字典用于调用函数,里面的value值实质上是函数名不是字符串直接加()就可以调用函数
    action_list1={0:Register,1:Login,2:Shopping}

    for i in action_list:
        print(f'{i}:{action_list[i]}')
    action_choice=input('Welcome ! Please selcet the action ,or enter 3 to leave :').strip()
    if action_choice!='3':
        action_list1[int(action_choice)]()

    print('Welcome next time!')
posted @ 2019-05-30 18:24  萨萌萌  阅读(248)  评论(0)    收藏  举报