python小程序(模拟用户登陆系统)

流程图

模拟登陆

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 
Line2-abc 
Line4-abcd"
>> print str.split( )
>> print str.split(' ', 1 )
['Line1-abcdef', 'Line2-abc', 'Line4-abcd']
['Line1-abcdef', '
Line2-abc 
Line4-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 + "
")
            file2.close()
            print("{_username} 对不起,密码输错三次,账户已被冻结!!!".format(_username=username))
            if big_loop_status:
                exit()
View Code
在你说话之前,先听;在你回应之前,先想;在你消费之前,先挣;在你退出之前,先试
原文地址:https://www.cnblogs.com/sunweigogogo/p/7492329.html