Python3学习实例上手(1)-----模拟登录认证
要求:输入用户名、密码进行认证,认证成功则欢迎,若输错三次会锁定最后一次输入的用户
知识点归纳:字典操作(items()方法)、字符串操作(如strip()、split()等)、文件读写(for line in f 变迭代器)、while&else循环、if判断
其他:分清变量类型,不要混淆整数和字符串数据类型
源码:
# -*- coding:utf-8 -*- # Author: WUJiang # 分别存储用户密码、用户锁定标志 info_pw = {} info_lock = {} # 读取txt中记录并对上述变量赋值 with open("user_info.txt", "r") as f: for line in f: line = line.strip() name = line.split(" ")[0] pw = line.split(" ")[1] lock_flag = line.split(" ")[2] info_pw[name] = pw info_lock[name] = lock_flag # -------------用户登录------------------- login_num = 0 while login_num < 3: login_name = input("enter your name:") login_pw = input("enter your password:") if login_name in info_pw.keys(): if info_lock[login_name] == "0": # 易遗漏"" if info_pw[login_name] == login_pw: print("welcome %s log in" % login_name) break else: print("wrong password") else: print("user has been locked, please contact to admin") break else: print("user does not exist") login_num += 1 else: print("input num is out of limit") print("%s is locked" % login_name) info_lock[login_name] = "1" # 被这里坑惨了!!!易遗漏""!!! # ----若锁定标志更新,需将更新数据写回txt-------- with open("user_info.txt", "w") as f: for i, j in info_pw.items(): data = i + " " + j + " " + info_lock[i] + "\n" f.write(data)