python面向函數式編程,模擬用戶登錄驗證、注冊的代碼實現。
主要有以下兩個文件:
1、user.txt文檔文件,相當於數據庫的用戶信息表,主要是記錄用戶名和密碼。
注意:1)此文檔需要與.py文件放在同一個路徑下。
2)用戶名、密碼在存儲時,是以$符號區別開。
2、模擬用戶登錄驗證、注冊的代碼實現。

1 #!/usr/bin/env python
2 # -*- coding:utf-8 -*-
3
4 def login(username, password): 5 """
6 用於用戶登錄驗證 7 :param username: 用戶名 8 :param password: 密碼 9 :return: True,登錄成功;False,登錄失敗。 10 """
11 with open("user.txt", "r", encoding="utf-8") as f: 12 for line in f: 13 line = line.strip() #默認strip無參數,會去掉首尾空格、換行符;有參數則去除指定值
14 line_list = line.split("$") #以$符號提取用戶名和密碼
15 if username == line_list[0] and password == line_list[1]: 16 return True 17 else: 18 return False 19
20 def register(username, password): 21 """
22 用戶注冊 23 :param username:用戶名 24 :param password:密碼 25 :return: True,注冊成功 26 """
27 with open("user.txt", "a", encoding="utf-8") as f: 28 temp = "\n" + username + "$" + password # "\n"換行符
29 f.write(temp) 30 return True 31
32 def user_exsit(username): 33 """
34 注冊時,判斷用戶名是否存在 35 :param username:用戶名 36 :return:True, 用戶名已存在 37 """
38 with open("user.txt", "r", encoding="utf-8") as f: 39 for line in f: 40 line = line.strip() 41 line_list = line.split("$") 42 if username == line_list[0]: 43 return True 44 return False 45
46 def main(): 47 print("歡迎您使用本系統,請輸入你進行操作選項。") 48 inp = input("1.登錄;2.注冊。請輸入編號: ") 49 if inp == "1": 50 times = 1
51 while True: 52 if times == 4: 53 print("輸入3次用戶名或密碼不正確,請在一小時后再重試。") 54 break
55 user = input("請輸入你的用戶名:") 56 pwd = input("請輸入你的密碼:") 57 is_login = login(user, pwd) 58 if is_login: 59 print("恭喜您!系統登錄成功。") 60 else: 61 print("用戶名或密碼不正確。") 62 times += 1
63 if inp == "2": 64 user = input("請輸入你的用戶名:") 65 pwd = input("請輸入你的密碼:") 66 if user_exsit(user): 67 print("用戶名已經存在,注冊失敗!") 68 else: 69 ret = register(user, pwd) 70 if ret: 71 print("注冊成功!") 72 else: 73 print("注冊失敗!") 74
75 main()