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

Python(Anaconda3)密码校验循环实现及次数限制需求

Python密码校验功能实现(带尝试次数限制与锁定机制)

以下是符合需求的代码实现,直接在Anaconda3环境下即可运行:

import time
import getpass

def enterPassword():
    # 替换为你实际使用的目标密码
    correct_password = "my_secure_pwd"
    max_attempts = 5
    lockout_duration = 5 * 60  # 转换为秒数
    attempt_count = 0

    while True:
        if attempt_count >= max_attempts:
            print(f"连续错误{max_attempts}次,账户锁定5分钟")
            time.sleep(lockout_duration)
            attempt_count = 0
            print("锁定已解除,请重新输入")
        
        # 隐藏输入内容,避免明文泄露
        input_password = getpass.getpass("请输入密码: ")
        if input_password == correct_password:
            print("密码正确,验证通过")
            break
        else:
            attempt_count += 1
            print("Wrong password")

if __name__ == "__main__":
    enterPassword()

关键说明

  • 密码安全输入:用getpass.getpass()替代普通input(),输入过程中不会显示明文,更符合密码校验的安全需求
  • 尝试次数管控:通过attempt_count统计错误次数,达到max_attempts上限后触发锁定逻辑
  • 锁定机制实现:借助time.sleep()完成5分钟的暂停,锁定结束后重置尝试次数,允许用户再次尝试
  • 循环逻辑:通过while True实现持续询问,直到输入正确密码才退出循环

你只需将代码中的correct_password替换为实际密码即可,Anaconda3自带Python标准库,无需额外安装依赖,直接运行脚本就能使用。

内容的提问来源于stack exchange,提问作者Nico Sören

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 00:05:25