如何在Python中实现带循环的密码错误次数锁定机制?
密码锁定功能实现方案
原代码存在的问题
- 缺少循环结构,仅支持单次密码输入,无法实现多次重试
- 分支逻辑错误:第三个
elif fails !=5永远不会触发,因为前两个条件(密码正确/错误)已经覆盖了所有可能的输入情况
修正后的循环实现代码
max_failed_attempts = 5 failed_count = 0 while failed_count < max_failed_attempts: password = input("Please enter the passcode for access to the terminal...") if password == "hello_world": print("Access granted...") break # 验证通过,跳出循环执行后续逻辑 else: failed_count += 1 remaining_attempts = max_failed_attempts - failed_count if remaining_attempts > 0: print(f"Wrong password... You have {remaining_attempts} attempts left.") else: print("Too many failed attempts. Program locked.") exit() # 终止程序,实现锁定效果
代码逻辑说明
- 先定义允许的最大错误次数
max_failed_attempts和当前错误计数failed_count - 通过
while循环控制重试流程:只要错误次数未达上限,就持续请求用户输入密码 - 密码验证通过时,打印授权信息并跳出循环,程序可继续执行后续功能
- 密码验证失败时,错误计数加1:
- 若还有剩余尝试次数,提示用户剩余次数
- 若尝试次数耗尽,提示程序锁定并终止进程,完成锁定机制
内容的提问来源于stack exchange,提问作者F4TAL_3RR0R.exe
相关产品推荐
相关产品推荐

