首先创建一个新的文件,用来保存所有的用户名和密码。文件命名为“bd”
"""
admin$123
alex$456
"""
以下为登陆函数程序
def login(username,password): f = open("db","r",encoding = "utf-8") for line in f: line = line.strip()//消除末端的 line_list = line.split("$")//每一行的数据通过$间隔开 if username == line_list[0] and password == line_list[1]: return True return False
注册程序:
def register(username, password): """ 注册用户 1,打开文件(a模式) 2,输入用户名$密码 """ with open("db","a",encoding = "utf-8") as f: temp = " " + username + "$" + password f.write(temp) return True
判断注册的用户名是否已经存在:
def user_exist(username,password): """ 一行一行去查找,如果存在return True; False """ with open ("db","r",encoding = "utf-8") as f: for line in f: line = line.strip() line_list = line.split("$") if line_list[0] == username: reture True return Fasle
主程序:
def main() print ("欢迎来到XXX系统") inp = input("1:登陆,2:注册") user = input("请输入用户:") pwd = input("请输入密码:") if inp = "1": is_login = login(user, pwd) if is_login: print ("登陆成功") else: print ("登陆失败") elif inp = "2" is_exist = user_exist(user) if is_exist: print ("用户已经存在,无法注册") else: result = register(user, pwd) if result: print ("注册成功") else: print ("注册失败")
直接运行主函数即可。