简体   繁体   中英

How to return an answer from Yes/No answer out of respective function?

I am asking a Yes or No prompt to a user as a function and I want to return what the answer was back to the rest of the code.

How could I get the answer from the yesNo() function to figure out if the user would like to run the intro variable/function?

prompt = " >>> "


def yesNo():
    answer = input('(Y/N)' + prompt)
    i = 1
    while i > 0:
        if answer == str.lower("y"):
            tutorial()
            i = 0
        elif answer == str.lower('n'):
            startGame()
            i = 0
        else:
            print("command not understood. try again.")


def newGame():
    print("would you like a tutorial?")
    yesNo()

I think you'll want something closer to this:

def get_user_input(choices):
    prompt = "Please enter ({}): ".format("/".join(f"'{choice}'" for choice in choices))
    while True:
        user_input = input(prompt)
        if user_input in choices:
            break
        prompt = "Unsupported command '{}', Try again: ".format(user_input)
    return user_input


def main():
    print("Would you like a tutorial?")
    user_input = get_user_input(["Yes", "No"])

    if user_input == "Yes":
        tutorial()
    startGame()

The function that gets user input should only be responsible for getting user input, and returning the user's provided input to the calling code. It should not have any other side-effects, like starting a tutorial, or starting the game.

Your code is mostly correct, just put the input inside de loop so it will prompt the user again if the condition isn't satisfied:

prompt = " >>> "


def yesNo():
    
    i = 1
    while i > 0:
        answer = input('(Y/N)' + prompt)
        if answer == str.lower("y"):
            tutorial()
            i = 0
        elif answer == str.lower('n'):
            startGame()
            i = 0
        else:
            print("command not understood. try again.")


def newGame():
    print("would you like a tutorial?")
    yesNo()

To get the answer of the user outside the yesNo() method, you can use return , and then store the returned value in a variable

Like this:

prompt = " >>> "


def yesNo():
    
    i = 1
    while i > 0:
        answer = input('(Y/N)' + prompt)
        if answer == str.lower("y"):
            tutorial()
            i = 0
        elif answer == str.lower('n'):
            startGame()
            i = 0
        else:
            print("command not understood. try again.")

        return answer


def newGame():
    print("would you like a tutorial?")
    answer = yesNo()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM