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

Python循环中累计错误计数终止程序问题求助

问题:Python全局错误计数器失效修复

我在为Python的while循环创建errorCount计数器时遇到问题。我需要这个计数器累计用户回答3个问题的错误次数,当总错误数达到5次时程序直接终止。比如:用户答错问题1两次,errorCount变为2;答错问题2三次,总错误数到5,程序就该终止。但当前程序允许每个问题独立累计错误,不会全局触发终止条件,附上代码如下,求修复方案:

原代码

# Level 5:
print("You have the jewel in your possession, and defeated Joker at his own game")
print("You now hold the precious jewel in your hands, but it's not over, you must leave the maze!")
print("*You must now choose 'Right', 'Left', or 'Straight' as you exit the maze. Keep trying until you find your path.*")

# put an error limit
# space everything out to make it look more neat
# Make sure you can fail the level

errorCount = 0

position = 0
while True:
    answer1 = input("Choose either Right, Left, Straight: ")
    
    
    try:
        if answer1.lower() == "right":
            print("You have chosen the correct path, now you proceed to the next step!")
            print()
            break
        
        if errorCount == 5:
           print("you made too many mistakes and got captured, you have to restart")
           
        elif answer1.lower() == "left":
            print("You see a boulder blocking your path which forces you to go back.")
            errorCount = 1 + errorCount
            
        elif answer1.lower()  == "straight":
            print("On your way to the next stage you are exposed to a toxic gas that forces you to go back .")
            errorCount = 1 + errorCount
            
        else:
            print("Wrong input. Please try again..")
            errorCount = 1 + errorCount
    except Exception:
        print("Wrong input. Please try again..")

# if errors >= 5:

while True:
    answer1 = input("Choose either Right, Left, Straight: ")
    
    if errorCount == 5:
       print("you made too many mistakes and got captured, you have to restart")
       
    try:
        if answer1.lower() == "straight":
            print("You have chosen the correct path, now you proceed to the next step!")
            break
    
        
        elif answer1.lower() == "left":
            print("You chose the wrong path, go back")
            errorCount = 1 + errorCount
            
        elif answer1.lower() == "right":
            print("You chose the wrong path, go back")
            errorCount = 1 + errorCount
            
        else:
            print("Wrong input. Please try again..")
            errorCount = 1 + errorCount
            
    except Exception:
        print("Wrong input. Please try again..")

print("You are now on the third stage, you notice a screen that is asking you a riddle")
while True:
    riddle1 = input("What gets wet when drying? ")
    
    if errorCount == 5:
       print("you made too many mistakes and got captured, you have to restart")
       
    try:
        if riddle1.lower() == "towel":
            print("You have chosen the correct answer")
            print("The giant stone blocking the entrance of the maze opens, and the outside lights shine through..")
            break
        
        else:
            print("Incorrect! Try again..")
            errorCount = 1 + errorCount
            print("Heres a hint: You use it after taking a shower...")
            
    except Exception:
        print("Incorrect! Try again..")
        errorCount = 1 + errorCount

问题原因

  1. 错误检查逻辑位置错误,且仅判断errorCount == 5,未覆盖>=5的情况
  2. 错误计数达标后仅打印提示,未终止整个程序,循环仍会继续
  3. 部分异常处理未正确累加错误计数

修复后的代码

# Level 5:
print("你已经拿到了宝石,还在小丑的游戏里打败了他")
print("现在宝石在你手里,但事情还没结束,你必须离开迷宫!")
print("*你需要选择'Right'(右)、'Left'(左)或'Straight'(直走)来走出迷宫,直到选对路径为止。*")

# 全局错误计数器
error_count = 0

# 检查错误次数是否超限的函数
def check_error_limit():
    global error_count
    if error_count >= 5:
        print("你犯了太多错误,被抓住了,必须重新开始!")
        exit()  # 终止整个程序

# 第一关:选择正确路径
while True:
    check_error_limit()  # 每次循环先检查错误次数
    answer = input("请选择 Right、Left 或 Straight:")
    
    try:
        answer_lower = answer.lower()
        if answer_lower == "right":
            print("你选对了路径,进入下一关!")
            print()
            break
        elif answer_lower == "left":
            print("你遇到了一块巨石挡路,只能退回重来。")
            error_count += 1
        elif answer_lower == "straight":
            print("路上你碰到了有毒气体,只能退回重来。")
            error_count += 1
        else:
            print("输入错误,请重新尝试。")
            error_count += 1
    except Exception:
        print("输入错误,请重新尝试。")
        error_count += 1

# 第二关:选择正确路径
while True:
    check_error_limit()  # 每次循环先检查错误次数
    answer = input("请选择 Right、Left 或 Straight:")
    
    try:
        answer_lower = answer.lower()
        if answer_lower == "straight":
            print("你选对了路径,进入下一关!")
            break
        elif answer_lower in ["left", "right"]:
            print("你选错了路径,退回重来。")
            error_count += 1
        else:
            print("输入错误,请重新尝试。")
            error_count += 1
    except Exception:
        print("输入错误,请重新尝试。")
        error_count += 1

# 第三关:猜谜语
print("你来到了第三关,看到一个屏幕正在问你谜语")
while True:
    check_error_limit()  # 每次循环先检查错误次数
    riddle_answer = input("什么东西越干越湿?")
    
    try:
        if riddle_answer.lower() == "towel":
            print("你答对了!")
            print("挡住迷宫出口的巨石打开了,外面的光照了进来...")
            break
        else:
            print("答错了!再试一次。")
            error_count += 1
            print("提示:你洗完澡后会用到它...")
    except Exception:
        print("答错了!再试一次。")
        error_count += 1

修复要点

  • 新增check_error_limit()函数,每次循环开始前先检查全局错误计数,达到5次直接终止程序
  • 将变量名改为符合Python规范的error_count
  • 调整循环逻辑:先检查错误次数,再处理用户输入
  • 统一异常处理中的错误累加逻辑
  • 简化第二关的条件判断,合并相同逻辑
  • 将英文提示翻译成中文,提升可读性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 16:25:22