如何捕获 Python 错误?

How to catch a Python error?

我想要一种可以捕获用户输入错误的方法。我找到了 Pythons try/except 方法。

到目前为止我有这个:

def take_a_guess(self):
    random_card_rank = random.choice(list(self.card.rank.keys()))
    random_card_suit = random.choice(self.card.suit)
    print(random_card_rank)
    print(random_card_suit)
    rank_guess, suit_guess = input('Guess the card: ').split()
    guesses = 3

    while guesses != 0:
        # try:
            if int(rank_guess) == random_card_rank and suit_guess.rstrip() == random_card_suit:
                print('Wow, well done you got it in one')
                guesses -= 3
            else:
                print('Nah')
                return False
            return True
        # except ValueError:
        #     print('You cant do that! Try again...')

但是如果我在输入中输入 1 个东西,它会说 ValueError: not enough values to unpack (expected 2, got 1) 我明白为什么,但我认为 except 会捕捉到这个并告诉我我不能这样做??

您需要在 try 中包围 整个 相关代码段,以便 catch 相关错误。您的错误源于这一行:

rank_guess, suit_guess = input('Guess the card: ').split()

根本不在您的 try 区块中。
您应该在该行之前的任何位置添加 try

def take_a_guess(self):

    random_card_rank = random.choice(list(self.card.rank.keys()))
    random_card_suit = random.choice(self.card.suit)
    print(random_card_rank)
    print(random_card_suit)

    # try should be here at the very least (or higher)
    rank_guess, suit_guess = input('Guess the card: ').split()

    # catch could be here and it would catch the error as expected

    guesses = 3
    while guesses != 0:
        # try should not be here
            if int(rank_guess) == random_card_rank and suit_guess.rstrip() == random_card_suit:
                print('Wow, well done you got it in one')
                guesses -= 3
            else:
                print('Nah')
                return False
            return True
        # except ValueError:
        #     print('You cant do that! Try again...')

为了在出现错误时继续循环,您可以将该行提取到 while 中,如下所示:

def take_a_guess(self):

    random_card_rank = random.choice(list(self.card.rank.keys()))
    random_card_suit = random.choice(self.card.suit)
    print(random_card_rank)
    print(random_card_suit)

    guesses = 3
    while guesses != 0:
        try:
            rank_guess, suit_guess = input('Guess the card: ').split()
        except ValueError:
            print('You cant do that! Try again...')
            continue

            if int(rank_guess) == random_card_rank and suit_guess.rstrip() == random_card_suit:
                print('Wow, well done you got it in one')
                guesses -= 3
            else:
                print('Nah')
                return False
            return True

你想要的try/catch是

rank_guess, suit_guess = input('Guess the card: ').split()

您正在尝试拆分您还不知道的内容。

你试过了吗?