Хотя L oop встречается чаще, чем предполагалось (Python) - PullRequest
0 голосов
/ 30 мая 2020

Циклы while, управляемые либо переменной x, не остановятся после того, как соответствующая переменная будет установлена ​​в False кодом, содержащимся в операторе if / elif. Вместо остановки while l oop, когда переменная x установлена ​​на False, это позволяет l oop произойти еще раз, прежде чем l oop остановится. Что вызывает это?

def GameIntro():
# Declaration of outer while loop variable
    x = True
# Outer while loop that I want to keep running until the player enters the 'yes' branch of the if statement
    while x:
# Declaration of inner while loop variable
        j = True
        playerName = input("Please enter your name:")
        print("\nWelcome " + playerName)
        print("At any time, type 'Help' to bring up the list of possible actions." + "\n")
        while j:
            beginGame = input(playerName + ", are you ready to begin? [Y] or [N]")
            beginGame = beginGame.upper()
            if beginGame == "Y" or beginGame == "YES":
# At this point I want this function to end and for it to return a True value. The     # print is purely for testing purposes.
                print("Yes Test")
                x = False
                j = False
                return True
            elif beginGame == "N" or beginGame == "NO":
# At this point, I want the inner loop to stop and for the outer loop to occur again.  # This works.
                print("No Test")
                j = False
            else:
                print("Please enter either [Y] or [N]")

GameIntro()

Вот результат, который я получаю.

Please enter your name:Bob 
Welcome Bob 
At any time, type 'Help' to bring up the list of possible actions. 
Bob, are you ready to begin? [Y] or [N]
Y 
Yes Test 
Please enter your name:Bob2 
Welcome Bob2 
At any time, type 'Help' to bring up the list of possible actions. 
Bob2, are you ready to begin? [Y] or [N]
Y Yes Test 
Run game 
Process finished with exit code 0

«Запустить игру» исходит от другой функции, которая получает возвращенный True от yes ветвь оператора if / elif.

1 Ответ

0 голосов
/ 30 мая 2020

Я не думаю, что вам действительно нужна отдельная переменная, вы можете использовать beginGame, например, в качестве контрольного значения

Я бы также рекомендовал размещать break в каждой точке цикла вместо того, чтобы полагаться на return, если только вы не можете перейти в безопасное состояние возврата

def validInput(x):
    return x in {'YES', 'Y'}

def intro():
    playerName = input("Please enter your name:")
    print("\nWelcome " + playerName)
    print("At any time, type 'Help' to bring up the list of possible actions." + "\n")
    beginGame = 'N'
    while not validInput(beginGame):
        beginGame = input(playerName + ", are you ready to begin? [Y] or [N]").upper()
        if beginGame == "HELP":
            print('[Y] or [N]?')
        elif validInput(beginGame):
            print('Starting Game!')
    print(f'Getting {playerName} ready to play...')
    return (playerName, True)

playerName, ready_intro = intro()
if ready_intro:
    main_game(playerName)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...