1. 程式人生 > >python小程序(模擬用戶登陸系統)

python小程序(模擬用戶登陸系統)

賬號 this src 使用 div [0 please one str

模擬登陸
1.用戶輸入賬號密碼進行登陸
2.用戶信息存在文件內
3.用戶密碼輸錯三次後鎖定用戶

知識點:strip()、split()、while、for循環混用以及布爾值的使用

strip() 方法用於移除字符串頭尾指定的字符(默認為空格)

實例1:

>> str = "0000000this is string example....wow!!!0000000";
>> print str.strip( ‘0‘ );
this is string example....wow!!!

split() 通過指定分隔符對字符串進行切片,如果參數num 有指定值,則僅分隔 num 個子字符串,註意,他的返回值為字符串列表

實例2:

>> str = "Line1-abcdef \nLine2-abc \nLine4-abcd"
>> print str.split( )
>> print str.split(‘ ‘, 1 )
[‘Line1-abcdef‘, ‘Line2-abc‘, ‘Line4-abcd‘]
[‘Line1-abcdef‘, ‘\nLine2-abc \nLine4-abcd‘]

程序如下:

技術分享
#!/usr/bin/env python
#author:sunwei
‘‘‘
模擬用戶登陸
1.使用存在於文本中的用戶名、密碼登陸系統
2.用戶輸錯密碼三次後,將鎖定賬戶
‘‘‘ login_times = 0 blacklist = [] file1 = open("blacklist.txt","r") #將黑名單以列表的形式讀入內存,以便判斷賬戶是否被凍結 for line1 in file1: blacklist.append(line1.strip()) file1.close() while True: #是否退出最外層循環,初始狀態為False big_loop_status = False username = input("please input your username:").strip() #若用戶輸入賬戶為空,則重新輸入
if len(username) == 0:continue #匹配黑名單用戶成功,則直接退出 if username in blacklist: print("非常抱歉,您的賬戶已被凍結!!!") break else: while login_times < 3: password = input("please input your password:").strip() #strip()去掉字符串首尾空格,默認為去空格 #若用戶輸入密碼為空,則重新輸入 if len(password) == 0:continue #匹配狀態,初始狀態為False match_status = False user_info = open("db.txt","r") for line2 in user_info: #判斷是否全匹配,若全匹配,則修改匹配狀態以及最外層循環狀態為True if username == line2.strip().split()[0] and password == line2.strip().split()[1]: #split()使用空格對字符串分片,默認為空格 match_status = True big_loop_status = True break else: match_status = False continue if match_status and big_loop_status: print("Welcome to {_username}".format(_username=username)) exit() else: print("用戶名或密碼輸入有誤,請重試!!!") login_times +=1 user_info.close() else: big_loop_status = True file2 = open("blacklist.txt","a") file2.write(username + "\n") file2.close() print("{_username} 對不起,密碼輸錯三次,賬戶已被凍結!!!".format(_username=username)) if big_loop_status: exit()
View Code

python小程序(模擬用戶登陸系統)