作业一:登陆认证
基础需求: 让用户输入用户名密码 认证成功后显示欢迎信息 输错三次后退出程序 升级需求: 可以支持多个用户登录 (提示,通过列表存多个账户信息) 用户3次认证失败后,退出程序,再次启动程序尝试登录时,还是锁定状态(提示:需把用户锁定的状态存到文件里)
初始版本:
1 # -*- coding:utf-8 -*- 2 # author: heimu 3 4 import os 5 6 user_dic = {"heimu_1":"111111","heimu_2":"222222","heimu_3":"333333"} 7 lock_state = [] 8 count = 1 9 if os.path.isfile("lock_state.txt"): 10 with open("lock_state.txt","r") as f: 11 lock_state = f.readline() 12 while count <= 3: 13 user_name_input = input("please input user name: ") 14 passwords_input = input("please input six digital passwords: ") 15 if user_name_input in lock_state: 16 print("Sorry,%s account has been locked" % user_name_input) 17 break 18 elif user_name_input in user_dic and user_dic[user_name_input] == passwords_input: 19 print("Welcome!%s" % user_name_input) 20 break 21 elif count < 3: 22 print("Authentication failure! Please input again.") 23 else: 24 print("You have failed three times,the program is going to exit !!!") 25 if user_name_input in user_dic: 26 with open("lock_state.txt","a") as f: 27 f.write(user_name_input) 28 count+=1
经过大王的悉心教诲之后的版本
1 # -*- coding:utf-8 -*- 2 # author: heimu 3 4 import os 5 6 user_dic = {"heimu_1":"111111","heimu_2":"222222","heimu_3":"333333"} 7 lock_state = [] # 存储黑名单 8 count = 1 9 first_input_user = None # 记录第一次输入的账户名 10 is_same_user = True # 标志位,用于判断三次输入的用户名是否相同 11 12 if os.path.isfile("lock_state.txt"): # 如果文件存在则打开文件 13 with open("lock_state.txt","r") as f: # 使用with语句,省去了每次得手动关闭文件 14 for line in f: # 迭代f文件,line循环一次表示一行 15 lock_state.append(line.strip()) # .strip 表示取出空格换行符之类的 16 17 # 主函数 18 while count <= 3: 19 user_name_input = input("please input user name: ") 20 passwords_input = input("please input six digital passwords: ") 21 if user_name_input in lock_state: # 如果账户存在于黑名单,直接退出 22 exit("Sorry,%s account has been locked" % user_name_input) 23 if not first_input_user: # 如果为None,代表为第一次输入账户 24 first_input_user = user_name_input 25 if first_input_user != user_name_input: # 代表本次输入的用户名和第一次用户名不一样 26 is_same_user = False # 标志位设置为False,表示不再执行账户锁定操作 27 if user_name_input in user_dic and user_dic[user_name_input] == passwords_input: 28 print("Welcome!%s" % user_name_input) # 登陆成功 29 break 30 else: 31 print("Authentication failure! Please input again.") # 失败错误少于三次,打印认证失败语句 32 count+=1 33 else: 34 print("You have failed three times,the program is going to exit !!!") 35 if is_same_user: # 锁定用户 36 if user_name_input in user_dic: # 如果账户名存在于文件中,把账户名加入黑名单 37 print("%s账户已经锁定" % user_name_input) 38 with open("lock_state.txt","a") as f: 39 f.write(user_name_input+‘\n‘) 40 else: 41 pass # 如果账户名不在文件中,就算重复三次也不加入黑名单