Перехват исключений UnboundLocalError - PullRequest
0 голосов
/ 26 февраля 2020

Мне нужно использовать «попробовать и кроме», чтобы поймать ошибку в этом коде:

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)

1 Ответ

0 голосов
/ 26 февраля 2020
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: ') 

Это не те строки, которые вы ищете. Попробуйте - кроме здесь, не поймает вашу ошибку.

Это здесь:

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. Для этого вы можете переместить объявление hand над оператором if или скопировать его в ветку elif.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...