如何捕获Python错误?

时间:2016-05-04 08:55:22

标签: python try-except

我想要一种可以捕获用户错误输入的方法。我发现Pythons尝试/除了方法。

到目前为止,我有这个:

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会抓住这个并告诉我我不能这样做?

2 个答案:

答案 0 :(得分:0)

您需要在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

答案 1 :(得分:0)

你想要尝试/捕获的是

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

你正试图分裂你还不知道的东西。

你试过吗?