8 作业:用户登录,3次锁定

1 基础需求

username = "abc"
password = '123'
count = 0
while True:
    user = input("输入用户名:")
    passwd = input("输入密码:")
    if user == username and passwd == password:
        print("登录成功!")
        break
    else:
        print("登录失败,请重新输入!")
    count += 1
    if count == 3:
        print("登录失败错误过多,程序将退出!")
        break
#运行结果
输入用户名:a
输入密码:1
登录失败,请重新输入!
输入用户名:abc
输入密码:123
登录成功!

Process finished with exit code 0

简化版

user = 'abc'
pwd = 123
i = 0
while i < 3 :
    username = input("输入用户名:")
    password = int(input("输入密码:"))
    if username == user and password == pwd:
        print("登录成功")
        break
    else:
        print("登录失败")
    i += 1

#运行结果
输入用户名:1
输入密码:1
登录失败
输入用户名:abc
输入密码:123
登录成功

Process finished with exit code 0

2 升级需求

import  os#导入包
user_list = {
    'alex':{'password':'123'},
    'jack':{'password':'123'}
}
if os.path.exists('lock'):#判断文件是否存在,如存在,就读取,否则创建一个新文件。
    f = open('lock', 'r',encoding =' utf-8')
else:
    f = open('lock','w')
with open('lock','r') as f1:
    lock_user = f1.read()

count = 0
while count < 3:
    username = input("please input you username:")
    if username == lock_user:#判断用户名是否锁定
        print("username is lock!!!")
    else:
        if username not in user_list:
            print("not find username!")
        else:
            password = input("please input your password:")
            if password == user_list[username]['password']:#判断密码是否正确
                print("welcome %s"%username)
                break
            else:
                print("password is error,please again")
    count += 1
    if count == 3:#账号锁定
        with open('lock','a') as f2:#a'表示append,表示不清除原有数据,在原有数据之后,继续写数据
            f2.write(username)
else:
    print("Three errors will be locked!")
#运行结果
please input you username:abc
not find username!
please input you username:123
not find username!
please input you username:alex
please input your password:123
welcome alex

Process finished with exit code 0
原文地址:https://www.cnblogs.com/Mobai-c/p/10097749.html