Python三次登陆
题目:Python实现三次登陆
不要急于马上把三次登陆写出来,一定要将复杂的程序简单化,必须一步一步地去扩展,这样才保证不会出错。
步骤一:实现简单的一次登陆
# 事先定义 user = 'dark_knight' pwd = 'dk123' username = input('Please enter username:') password = input('Please enter password:') # 判断 if username == user and password == pwd: print('Login successfully!') else: print('Login failed!')
步骤二:实现简单的三次登陆
# 事先定义 user = 'dark_knight' pwd = 'dk123' count = 1 # 定义次数 while True: if count == 4: # 大于3次则退出循环 print('Too many times!') break username = input('Please enter username:') password = input('Please enter password:') # 判断 if username == user and password == pwd: print('Login successfully!') break else: print('Login failed!') count += 1 # 每次循环都次数都进行加1操作
步骤三:解决三次登陆中的BUG
1、去除字符串两边的空格
2、当用户输入None时则提示用户反复输入。
3、当用户输入的信息不匹配时则告诉用户还有几次机会。
# 事先定义 user = 'dark_knight' pwd = 'dk123' count = 1 # 定义次数 while True: if count == 4: # 大于3次则退出循环 print('Too many times!') break username = input('Please enter username:').strip() # 去除字符串两边的空格 password = input('Please enter password:').strip() # 去除字符串两边的空格 # 当用户输入有值时 if username and password: # 判断 if username == user and password == pwd: print('Login successfully!') break else: print('Login failed!') print('You have %s chance.'%(3 - count)) # 当用户输入None时 else: print('You enter blank, please re-enter!') continue # 当用户输入None时,跳出本次循环。 count += 1 # 每次循环都次数都进行加1操作
步骤四:扩展三次登陆
要求:将登陆三次失败后的用户进行锁定。
思路:1、先手动创建一个黑名单文件。
2、再创建一个空列表,将每次输入错误的用户名添加至列表中。
3、当加入列表中的用户名出现3次相同的用户名时,把这个用户名添加至黑名单进行锁定。
user = 'knight' pwd = 'dk123' count = 1 times = [] # 用于统计密码输错时的用户名的个数 with open('blacklist.txt', 'r', encoding='utf-8') as f_black: black_line = f_black.readlines() # 将黑名单内容以列表的形式读出来 # print(black_line) while True: # 当登陆次数超过3次时提示登陆次数过多,退出程序 if count == 4: print('Too many times!') break username = input('Please enter your username:').strip() password = input('Please enter your password:').strip() # 判断用户名是否为空 if not username: print('The username you entered is blank, please re-enter') continue # 判断密码是否为空 elif not password: print('The password you entered is blank, please re-enter') continue # 判断用户名再加上"\n"是否在黑名单的列表里,如果在则提示用户已锁定再退出程序 if username + '\n' in black_line: print('Sorry, your account has been locked!') break # 判断用户名和密码是否匹配 if username == user and password == pwd: print('Login successfully!') break else: print('The username or password you entered is incorrect,Please try again!') print('You still have %s chances' % (3 - count)) # 如果不匹配则提示用户名或密码错误并告之用户还有几次机会 times.append(username) # 将错误的用户名加入至事先定义的times列表中, if times.count(username) == 3: # 然后计算加入的用户名的个数是否等于三个,如果是则写入至黑名单文件中。 with open('blacklist.txt', 'a', encoding='utf-8')as f: f.write(username+'\n') count += 1