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

如何实现输入错误密码时重置该Python密码验证脚本?

Python密码验证脚本:错误输入后重新请求输入的解决方案

原脚本仅执行一次密码验证,输入错误后直接终止。要实现错误时重置验证流程(即让用户重新输入),可以通过循环结构来实现,以下是两种可行方案:

基础方案:无限重试直到输入正确

直接使用while True创建无限循环,直到用户输入正确密码才退出:

import getpass

while True:
    p = getpass.getpass(prompt='What is the code you were given?? ')
    if p.lower() == 'breakout':
        print('Welcome..!!!')
        break  # 验证成功,终止循环
    else:
        print('The answer entered by you is incorrect..!!!')
        # 不中断循环,自动进入下一轮输入

代码说明

  • while True会持续执行循环体内的代码,直到遇到break语句
  • 每次循环都会重新调用getpass.getpass()获取用户的新输入
  • 验证通过时打印欢迎信息并执行break退出循环;验证失败时仅打印错误提示,循环自动继续

可选改进:限制重试次数

如果需要限制用户的错误输入次数,可以添加计数器实现:

import getpass

max_attempts = 3
attempts = 0

while attempts < max_attempts:
    p = getpass.getpass(prompt='What is the code you were given?? ')
    if p.lower() == 'breakout':
        print('Welcome..!!!')
        break
    else:
        attempts += 1
        remaining = max_attempts - attempts
        print(f'The answer entered by you is incorrect..!!! You have {remaining} attempts left.')
else:
    # 当循环正常结束(未被break中断)时执行,即所有尝试用完
    print('Too many incorrect attempts. Access denied.')

代码说明

  • 设置max_attempts定义最大允许的错误次数
  • 每次错误输入后计数器attempts加1,并提示剩余尝试次数
  • 当尝试次数耗尽时,执行else块的代码,拒绝访问

内容的提问来源于stack exchange,提问作者Xeno

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 09:45:38