1. 让用户输入用户名密码 2. 认证成功后显示欢迎信息、程序结束 3. 输错三次后退出程序 升级需求: 1. 可以支持多个用户登录 (提示:用户可以通过列表或者是字典进行存储) 2. 用户3次认证失败后,退出程序,再次启动程序尝试登录时,还是锁定状态(提示:需把用户锁定的状态存到文件里)
代码一(只用到了列表),需要在同级别目录先创建名为lockedname.txt的空文件。
#!/usr/bin/env python # coding=utf-8 # __author__ = "zhaohongwei" # Date: 2019/1/27 name_list = ["zhangsan","lisi","wangwu"] # 用户名列表 passwd_list = ["zhangsan666","lisi666","wangwu666"] # 用户的密码列表 count = [0, 0, 0] # 用户登录密码错误的次数计数 while True: name_index = 999999 # 定义一个不存在的用户的下标 name = input("请输入你的姓名:").strip() passwd = input("请输入你的密码:").strip() with open("lockedname.txt","r+") as f: locked_name = "".join(f.readlines()).splitlines() if name in locked_name: print("用户已经被锁定,请联系管理员") continue for i in range(len(name_list)): if name == name_list[i]: name_index = name_list.index(name_list[i]) if name_index == 999999: print("用户名不存在,请重新输入") continue if name == name_list[name_index] and passwd == passwd_list[name_index]: # 判断用户名密码 print("欢迎 %s 同学"%(name_list[name_index])) break else: count[name_index] += 1 # 同一个用户名输错密码加一 print("密码错误") if count[name_index] == 3 : print("3次密码错误,用户账号已被锁定") with open("lockedname.txt","a+") as f: f.writelines(name_list[name_index]+" ") break
代码二(修改版,用到了字典)
#!/usr/bin/env python # coding=utf-8 # __author__ = "zhaohongwei" # Date: 2019/1/27 import json user = { "zhangsan": ["zhangsan666",3,False], "lisi": ["lisi666",0,True], "wangwu": ["wangwu666",0,True] } #用户名:[密码,密码输错次数,False锁定用户] while True: name = input("请输入你的姓名:").strip() try: with open("lockedname.txt","r+",encoding="utf-8") as f: user = json.load(f) #若是有lockedname.txt文件,则user重新赋值 except Exception as err: pass if name not in user: print("用户名不存在,请重新输入") continue elif user[name][2] == False: print("用户已经被锁定,请联系管理员") continue elif name in user: passwd = input("请输入你的密码:").strip() if passwd == user[name][0]: # 判断用户名密码 print("欢迎 %s 同学"%(name)) user[name][1] = 0 with open("lockedname.txt", "w", encoding="utf-8") as f: json.dump(user, f) break else: user[name][1] += 1 # 同一个用户名输错密码加一 print("密码错误") if user[name][1] >= 3: print("用户账号已被锁定") user[name][2] = False with open("lockedname.txt", "w", encoding="utf-8") as f: json.dump(user, f)