You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 17:52:05