首页 > 解决方案 > 捕获 UnboundLocalError 异常

问题描述

我需要使用“try and except”来捕获此代码中的错误:

while hand_numbers > 0:
    hand_type = input('Enter \'n\'to deal a new hand,  \'r\' to replay the last hand, or \'e\' to end game: ') 

当我输入“r”时,我收到以下错误:

Traceback (most recent call last):
  File "C:/Users/User/PycharmProjects/mit/mit_w4_pset/ps4a - Copy.py", line 310, in <module>
    playGame(wordList)
  File "C:/Users/User/PycharmProjects/mit/mit_w4_pset/ps4a - Copy.py", line 295, in playGame
    playHand(hand, wordList, HAND_SIZE)

UnboundLocalError: local variable 'hand' referenced before assignment

我需要用以下短语替换这个错误:'你还没有玩过一手牌。请先玩新手!

我尝试了以下方法:

while hand_numbers > 0:
    try:
        hand_type = input('Enter \'n\'to deal a new hand,  \'r\' to replay the last hand, or \'e\' to end game: ')
    except UnboundLocalError as Error:
        print('You have not played a hand yet. Please play a new hand first!')
        continue

但它不工作..我也尝试过除了ValueError和NameError..没有任何工作..有什么建议吗?提前致谢。

查看其他代码:

def playHand(hand, wordList, n):
    """
    Allows the user to play the given hand, as follows:

    * The hand is displayed.
    * The user may input a word or a single period (the string ".") 
      to indicate they're done playing
    * Invalid words are rejected, and a message is displayed asking
      the user to choose another word until they enter a valid word or "."
    * When a valid word is entered, it uses up letters from the hand.
    * After every valid word: the score for that word is displayed,
      the remaining letters in the hand are displayed, and the user
      is asked to input another word.
    * The sum of the word scores is displayed when the hand finishes.
    * The hand finishes when there are no more unused letters or the user
      inputs a "."

      hand: dictionary (string -> int)
      wordList: list of lowercase strings
      n: integer (HAND_SIZE; i.e., hand size required for additional points)

    """
    # BEGIN PSEUDOCODE <-- Remove this comment when you code this function; do your coding within the pseudocode (leaving those comments in-place!)
    # Keep track of the total score
    total_score = 0
    # As long as there are still letters left in the hand:
    while (calculateHandlen(hand)) > 0:
        #Display the hand
        print('Current hand: ', end='')
        displayHand(hand)
        # Ask user for input
        word = input('Enter a valid word, or a "." to indicate that you are finished: ')
        # If the input is a single period:
        if word == '.':
            # End the game (break out of the loop)
            print('Goodbye!')
            break

        # Otherwise (the input is not a single period):
        else:
            # If the word is not valid:
            if isValidWord(word, hand, wordList) == False:
                # Reject invalid word (print a message followed by a blank line)
                print('Invalid word, please try again: \n')
            # Otherwise (the word is valid):
            else:
                # Tell the user how many points the word earned, and the updated total score, in one line followed by a blank line
                score = getWordScore(word, HAND_SIZE)
                total_score = total_score + score
                print('Score earned: ', getWordScore(word, HAND_SIZE), 'Your current total score is: ', total_score, '\n')
                # Update the hand
                hand = updateHand(hand, word)
                if calculateHandlen(hand) == 0:
                    print('You have no more letters to play,Game over!')

    # Game is over (user entered a '.' or ran out of letters), so tell user the total score
    print('Total score for this hand is: '+str(total_score)+' points.')

def playGame(wordList):
    """
    Allow the user to play an arbitrary number of hands.

    1) Asks the user to input 'n' or 'r' or 'e'.
      * If the user inputs 'n', let the user play a new (random) hand.
      * If the user inputs 'r', let the user play the last hand again.
      * If the user inputs 'e', exit the game.
      * If the user inputs anything else, tell them their input was invalid.

    2) When done playing the hand, repeat from step 1    
    """
    # TO DO ... <-- Remove this comment when you code this function
    hand_numbers = 10
    while hand_numbers > 0:
        hand_type = input('Enter \'n\'to deal a new hand,  \'r\' to replay the last hand, or \'e\' to end game: ')
        choices = ['e','n','r']
        if hand_type not in choices:
            print('Invalid command.')
        elif hand_type == 'e':
            print ('Goodbye!')
            break
        else:
            if hand_type == 'n':
                hand = dealHand(HAND_SIZE)
                playHand(hand, wordList, HAND_SIZE)
            elif hand_type == 'r':
                playHand(hand, wordList, HAND_SIZE)
            hand_numbers -= 1
            #print(hand_numbers)

#
# Build data structures used for entire session and play game
#
if __name__ == '__main__':
    wordList = loadWords()
    playGame(wordList)

标签: pythonexception

解决方案


while hand_numbers > 0:
    hand_type = input('Enter \'n\'to deal a new hand,  \'r\' to replay the last hand, or \'e\' to end game: ') 

这些不是您要查找的线路。Try-except 这里不会发现你的错误。

是这里:

if hand_type == 'n':
    hand = dealHand(HAND_SIZE)
    playHand(hand, wordList, HAND_SIZE)
elif hand_type == 'r':
    playHand(hand, wordList, HAND_SIZE)

问题很简单:hand在第二个分支中未定义(嵌套在 下elif)。它仅在第一个分支中定义嵌套在 下if)。因此,当您键入 时r,会发生错误。

解决方案同样简单:确保hand为 if 和 elif 分支都定义了。为此,您可以移动handif 语句上方的声明或将其复制到 elif 分支中。


推荐阅读