Попытка вернуться на один цикл, но не к основному родительскому циклу

#python #loops #if-statement

Вопрос:

Эта игра требует двух входных данных от пользователя: «user_choice» и «player_choice». Сначала я получаю ввод user_choice. Последняя проблема, с которой я сталкиваюсь, связана со 2-м входом (player_choice). Если пользователь вводит что-то недопустимое, это заставляет их повторно выбрать user_choice, и я просто хочу, чтобы им пришлось повторно выбрать player_choice.

 def playGame(wordList):
       
    hand = []   
    while True:   
    # ask the user if they want to play
        user_choice = input('Enter n to deal a new hand, r to replay the last hand, or e to end game: ')
        # if they enter 'e' end the game
        if (user_choice == 'e'):
            break
        elif (user_choice == 'r' and len(hand) == 0):
            print('You have not played a hand yet. Please play a new hand first!')
        # if they enter an invalid command send them back
        elif (user_choice != 'n' and user_choice != 'r'):
            print('Invalid command.')
        
        # if they enter n or r ask them who is going to play
        if (user_choice == 'n' or user_choice == 'r'):
            player_choice = input('Enter u to have yourself play, c to have the computer play: ')
            # if human is playing follow the steps from before
            if (player_choice == 'u'):
                if (user_choice == 'n'):
                    hand = dealHand(HAND_SIZE)
                    playHand(hand, wordList, HAND_SIZE)
                elif (user_choice == 'r' and len(hand) != 0):
                    playHand(hand, wordList, HAND_SIZE)
                else :
                    print('You have not played a hand yet. Please play a new hand first!')
                    
            # if computer is playing . . .
            elif (player_choice == 'c'):
                if (user_choice == 'n'):
                    hand = dealHand(HAND_SIZE)
                    compPlayHand(hand, wordList, HAND_SIZE)
                elif (user_choice == 'r' and len(hand) != 0):
                    compPlayHand(hand, wordList, HAND_SIZE)
                else:
                    print('You have not played a hand yet. Please play a new hand first!')
            else:
                print('Invalid command.')
                continue
 

»’

Ответ №1:

Ваше заявление continue о недопустимом выборе переходит к следующей итерации цикла, где user_choice будет запрошено снова.

             elif (player_choice == 'c'):
                if (user_choice == 'n'):
                    hand = dealHand(HAND_SIZE)
                    compPlayHand(hand, wordList, HAND_SIZE)
                elif (user_choice == 'r' and len(hand) != 0):
                    compPlayHand(hand, wordList, HAND_SIZE)
                else:
                    print('You have not played a hand yet. Please play a new hand first!')
            else:
                print('Invalid command.')
                continue # Will go to the start of the loop
 

Вместо этого вы можете завернуть player_choice код в цикл, который повторяется, пока ввод недопустим. Это может выглядеть примерно так:

 player_choice_valid = False
while not player_choice_valid:
   # As you have multiple valid cases but one invalid case,
   # by setting to True here we can save writing it for each valid case
   player_choice_valid = True
   player_choice = input("...")
   ...
   elif (player_choice == 'c'):
       ...
   else
       player_choice_valid = False # Input is not valid, set to False
 

Комментарии:

1. Привет! Спасибо за быстрый ответ. Вчера не смог прокомментировать, так как сайт был в режиме только для чтения. Хотя не уверен, что понимаю на 100%. Вы хотите сказать, что в конце моего кода, в последнем предложении «else», я должен создать этот непрерывный цикл while, который завершается только после того, как ввод допустим?

2. Nvm, я понял! Спасибо!! Единственный вопрос, который у меня есть, заключается в том, что код, похоже, работает независимо от того, добавляю ли я эту строку «player_choice_valid = True» в цикл или нет. Как будто и без этого все еще работает идеально. Это потому, что просто установка значения автоматически меняет его с Ложного на Истинное?