模擬登陸作業需求:
1. 用戶輸入帳號密碼進行登陸
2. 用戶信息保存在文件內
3. 用戶密碼輸入錯誤三次后鎖定用戶
額外實現功能:
1.提示輸入錯誤次數
2.輸入已鎖定用戶會提示
3.用戶不存在會提示
正確用戶信息文件中以字典形式保存用戶名密碼:
{'name': 'password','cx':'123','even':'456','test':'ok'}
鎖定用戶信息文件中以列表形式保存鎖定用戶名:
['name']
流程圖:
詳細代碼:(python3.6)

#!/usr/bin/env python # -*- coding:utf-8 -*- # Author: Even count = 0 # 為了記錄需求中3次輸入錯誤避免的次數,計數項賦初始值 load = True # 為了完成功能后退出,賦初始值 file = open("正確用戶信息文件",'r',encoding='utf-8') # 打開正確用戶信息文檔,獲取正確的用戶名密碼 file_wrong = open("鎖定用戶信息文件",'r+',encoding='utf-8') # 打開已鎖定的用戶信息文檔,獲取鎖定的用戶名密碼 line = eval(file.readline()) # 將正確信息中的字符串轉換成字典(原字符串為字典格式) line_wrong = eval(file_wrong.readline()) # 將正確信息中的字符串轉換成列表(原字符串為列表格式) def out(): # 將重復代碼定義,功能是幫助跳出while循環並關閉已打開文檔 global load # 聲明全局變量 load = False # 賦值load,為了跳出while循環 file_wrong.close() # 關閉正確用戶信息文檔 file.close() # 關閉鎖定用戶信息文檔 while load: # 判斷是否已完成功能 name = input("請輸入用戶名:") # 輸入用戶名 password = input("請輸入密碼:") # 輸入密碼 if name in line and name not in line_wrong: # 判斷用戶名是否正確,和是否已被鎖定 while count <= 3: # 判斷是否已循環3次 if password == line[name]: # 判斷用戶名是否對應正確的密碼 print("您已成功登陸") # 輸出成功登陸信息 out() # 調用自定義out方法 break # 跳出本次循環 else: # 說明未輸入正確的密碼 count +=1 # 計數項自加一 msg_count = '''第%s次密碼輸入錯誤\n'''%(count) # 提示輸入錯誤次數 print(msg_count) # 打印錯誤次數信息 if count < 3: # 小於三次錯誤輸入,可以重新輸入 password = input("密碼錯誤,請重新輸入密碼:") # 重新輸入密碼 elif count == 3: # 判斷是否已輸錯三次 print("已輸錯3次,賬號已鎖定") # 打印鎖定提示信息 line_wrong.append(name) # 將已鎖定信息加入鎖定元組中 file_wrong.seek(0) # 輸入指針移到開頭,如果不移動會產生多個元組 file_wrong.write(str(line_wrong)) # 寫入鎖定信息 file_wrong.tell() # 獲取當前的輸入指針位置,如果不獲取會產生多個元組 out() # 調用out方法 break elif name in line_wrong: # 判斷用戶名是否在已鎖定用戶名中 print("該用戶名已被鎖定") # 打印已鎖定通知信息 out() # 調用自定義out方法 break # 跳出當前循環 else: # 說明用戶名不在正確用戶名信息中 print("該用戶名不存在") # 打印用戶名輸入錯誤信息 out() # 調用out方法