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

Python中try/except块内通过函数退出程序的问题(Wordle场景)

Wordle游戏猜对后无法退出程序的解决方法

我在用Python制作Wordle游戏,开发接近尾声,但遇到一个问题:当用户猜对单词时,程序无法终止。我尝试过sys.exit()、quit()、SystemExit(1)等方法,都没有效果。以下是相关代码片段和完整代码:

问题代码区域

winRow = [32, 32, 32, 32, 32]
if colorRow == winRow:
    print("YOU WON!")
    SystemExit(1)


return board, colorList, colorRow, result


numList = ["FIRST", "SECOND", "THIRD", "FOURTH", "FIFTH", "SIXTH"]
for x in range(len(numList)):
    z = True
    while z == True:
        try:
            guess = input(f"{numList[x]} GUESS  > ").upper()
            guess = list(guess)
            checkRight(guess, word, x+1)
            boardprint()
            z = False
        except:
            boardprint()
            print("Make sure your word is 5 letters")

完整代码

import rich
from rich.text import Text
import random

    
testList = ["PRICE"]
word = random.choice(testList)


board = {
    6 : ["_", "_", "_", "_", "_"],
    5 : ["_", "_", "_", "_", "_"],
    4 : ["_", "_", "_", "_", "_"],
    3 : ["_", "_", "_", "_", "_"],
    2 : ["_", "_", "_", "_", "_"],
    1 : ["_", "_", "_", "_", "_"]
}

colorList = {
    6 : [39, 39, 39, 39, 39],
    5 : [39, 39, 39, 39, 39],
    4 : [39, 39, 39, 39, 39],
    3 : [39, 39, 39, 39, 39],
    2 : [39, 39, 39, 39, 39],
    1 : [39, 39, 39, 39, 39] 
}

def boardprint():
    global board, colorList

    final = []
    for x in range(len(board)):
        spots = [f"\033[{col}m{board[x+1][idx]}\33[0m" for idx, col in enumerate(colorList[x+1])]
        l = ' '.join(spots)
        final.append(f"| {l} |")
    ansi_rich = Text.from_ansi('\n'.join(final))
    rich.print(ansi_rich)

    return colorList



guess = ""

result = "playing"

def checkRight(guess, word, row):
    global board, colorList

    GuessCheckDouble = {i:guess.count(i) for i in guess}
    WordCheckDouble = {i:word.count(i) for i in word}
    result = {key: GuessCheckDouble[key] - WordCheckDouble.get(key, 0) for key in GuessCheckDouble.keys()}
    updateRow = []
    colorRow = []

    for x in range(len(word)):
        if guess[x].upper() == word[x]: # green
            
            letter = guess[x]
            updateRow.append(letter)
            colorRow.append(32)

        elif guess[x].upper() in word and result[guess[x]] == 0: # yellow
            
            letter = guess[x]
            updateRow.append(letter)
            colorRow.append(33)
            
        else: # grey

            letter = guess[x]
            updateRow.append(letter)
            colorRow.append(30)

    

    board.update({row : [updateRow[0], updateRow[1], updateRow[2], updateRow[3], updateRow[4]]})
    colorList.update({row : [colorRow[0], colorRow[1], colorRow[2], colorRow[3], colorRow[4]]})

    winRow = [32, 32, 32, 32, 32]
    if colorRow == winRow:
        print("YOU WON!")
        SystemExit(1)


    return board, colorList, colorRow, result

word = word.upper()
word = list(word)


print("hello! welcome to \033[32;1mWORDLE\033[0m")
print("\tTry to guess a 5-letter word in 6 guesses or less.\n\t\tIf a letter is \033[32mgreen\033[0m, then it is in the right place,\n\t\tIf a letter is \033[33myellow\033[0m, then it is in the wrong place, \n\t\tif a letter is \033[30mgrey\033[0m, then it is the wrong letter.")
print()
boardprint()
print()

numList = ["FIRST", "SECOND", "THIRD", "FOURTH", "FIFTH", "SIXTH"]
for x in range(len(numList)):
    z = True
    while z == True:
        try:
            guess = input(f"{numList[x]} GUESS  > ").upper()
            guess = list(guess)
            checkRight(guess, word, x+1)
            boardprint()
            z = False
        except:
            boardprint()
            print("Make sure your word is 5 letters")

问题原因

  1. 退出异常未正确抛出:SystemExit(1)只是创建了一个异常对象,没有用raise关键字抛出,无法触发程序退出逻辑。
  2. 全局异常捕获拦截:外层循环的except:会捕获所有异常,包括SystemExit,导致退出信号被拦截,程序继续执行。

解决方案

1. 正确触发退出

在checkRight函数的胜利判断处,替换原有代码为:

winRow = [32, 32, 32, 32, 32]
if colorRow == winRow:
    print("YOU WON!")
    import sys
    sys.exit(0)  # 正常退出,状态码0表示无错误

或者直接抛出SystemExit异常:

winRow = [32, 32, 32, 32, 32]
if colorRow == winRow:
    print("YOU WON!")
    raise SystemExit(0)

2. 避免拦截退出异常

修改外层循环的except语句,只捕获输入长度错误对应的IndexError,而不是所有异常:

numList = ["FIRST", "SECOND", "THIRD", "FOURTH", "FIFTH", "SIXTH"]
for x in range(len(numList)):
    z = True
    while z == True:
        try:
            guess = input(f"{numList[x]} GUESS  > ").upper()
            guess = list(guess)
            checkRight(guess, word, x+1)
            boardprint()
            z = False
        except IndexError:  # 仅捕获输入非5字符时的索引错误
            boardprint()
            print("Make sure your word is 5 letters")

原理说明

  • sys.exit()内部会抛出SystemExit异常,Python解释器默认会处理该异常并终止程序,但如果被except:捕获则无法生效。
  • 限定捕获IndexError是因为当输入单词长度不是5时,guess列表长度不足,在checkRight函数遍历5次循环时访问guess[x]会触发该异常,既能处理输入错误,又不会拦截退出信号。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 21:57:19