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

如何为用户输入设置固定尝试次数?密码验证程序提示异常求助

密码猜测程序修复方案

原代码的核心问题是计数器x被放在了while True循环内部,每次循环都会重新把x赋值为1,导致永远无法进入x=2或x=3的判断分支,自然没法依次显示剩余次数提示。

修复后的代码

remaining_guesses = 3

while True:
    password = input(f"Enter the password ({remaining_guesses} guesses left):")
    
    if password == "Cookie":
        print("You guessed the password right")
        break
    
    remaining_guesses -= 1
    if remaining_guesses == 2:
        print("Incorrect try again (2 guesses left)")
    elif remaining_guesses == 1:
        print("Incorrect try again (1 guess left)")
    else:
        print("You ran out of guesses")
        break

代码说明

  • 把计数器remaining_guesses移到循环外初始化,确保每次错误猜测后计数器能持续递减,不会被重置。
  • 使用f-string动态显示当前剩余猜测次数,避免重复写提示文本。
  • 错误猜测后先减少剩余次数,再根据剩余值判断要显示的提示,逻辑更清晰。
  • 用break替代quit(),更符合Python循环控制的常规写法,避免强制终止程序的突兀感。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 05:32:13