文件操作练习2

2.1:编写用户登录接口
1、输入账号密码完成验证,验证通过后输出"登录成功"
2、可以登录不同的用户
3、同一账号输错三次锁定,(提示:锁定的用户存入文件中,这样才能保证程序关闭后,该用户仍然被锁定)

count =1
while count <= 3:
    inp_username = input('your name>>:').strip()
    inp_password = input('your password>>:').strip()
    with open('user1.txt',mode='rt',encoding='utf-8') as f1:
        for line in f1:
            username,password = line.strip().split(':')
            if inp_username == username and inp_password == password:
                print('登陆成功')
                count = 4
                break
        else:
            with open('user1,txt',mode = 'at',encoding='utf-8') as f2:
                f2.write('{
    
    }:{
    
    }'.format(username,password))
                print('您输入的账号或者密码错误,请重新输入')
    count+=1
with open ('user1.txt',mode='rt',encoding='utf-8') as f3:
    for i in f3.readlines():
        print(i)

2.2:编写程序实现用户注册后(注册到文件中),可以登录(登录信息来自于文件)
提示:
while True:
msg = “”"
0 退出
1 登录
2 注册
“”"
print(msg)
cmd = input('请输入命令编号>>: ').strip()
if not cmd.isdigit():
print(‘必须输入命令编号的数字,傻叉’)
continue

 if cmd == '0':
     break
 elif cmd == '1':
     # 登录功能代码(附加:可以把之前的循环嵌套,三次输错退出引入过来)
     pass
 elif cmd == '2':
    # 注册功能代码
     pass
 else:
     print('输入的命令不存在')

思考:上述这个if分支的功能否使用其他更为优美地方式实现

 while True:
    msg = """
    0 退出
    1 登录
    2 注册
    """
    print(msg)
    cmd = input('请输入命令编号>>: ').strip()
    if not cmd.isdigit():
        print('必须输入命令编号的数字,傻叉')
        continue

    if cmd == '0':
        print('退出成功')
        break
    elif cmd == '1':
        inp_name = input('your name>>:').strip()
        inp_password = input('your password>>:').strip()
        with open('user1.txt', mode='rt', encoding='utf-8') as f:
            for line in f:
                print(line, end='')
                username, password = line.strip().split(':')
                if username == inp_name and password == inp_password:
                    print('登陆成功')
                    break
            else:
                print('账号或密码失败')
        pass
    elif cmd == '2':
        name = input('your name>>:').strip()
        password = input('your password>>:').strip()
        with open('user2.txt', mode='at', encoding='utf-8') as f:
            f.write('{
    
    }:{
    
    }\n'.format(name, password))
        pass
    else:
        print('输入的命令不存在')

猜你喜欢

转载自blog.csdn.net/weixin_47237915/article/details/114645387