2

I can't figure out why the function returns the correct letter when I enter "N" or "n". The function is called but return "None" when I enter the incorrect letter. The function should be keep looping until the correct letter is entered.

This is the output when I enter the correct letter.

(N)ew game
Your choice?: n
Your choice before returning the value to main: n
Your choice: n

This is the output when I enter the incorrect letter.

(N)ew game
Your choice?: j
Wrong input
(N)ew game
Your choice?: n
Your choice before returning the value to main: n
Your choice: None

Source code:

def auswahl():
    print("(N)ew game")

    choice = input("Your choice?: ")

    if choice == 'N' or choice == 'n':
        print("Your choice before returning the value to main:", choice)
        return choice
    else:
        print("Wrong input")
        auswahl()

#main
eingabe = auswahl()
print("Your choice:", eingabe)
3
  • 5
    Your else branch has no return Commented Oct 30, 2018 at 14:54
  • 3
    Note though that recursion is the wrong solution here anyway. Commented Oct 30, 2018 at 14:56
  • But if i put a return there, it gets back to main?! With recursion u mean that the function calls itself? Commented Oct 30, 2018 at 14:58

1 Answer 1

2

With auswahl() you are just calling your function recursively, but do nothing with the value it produces.

It would have to be return auswahl().

However, note that using recursion in functions that take user input is considered harmful because you can blow the stack if a user fails too many times. See the "Common Pitfalls" section of the answer I linked to.

~edit~

But if i put a return there, it gets back to main?! With recursion you mean that the function calls itself?

Yes, recursion in this contexts refers to a function calling itself. return auswahl() does not immediately return from the function, it has to wait for the result another call to auwahl produces. Of course, in that other call the user could fail again, which would trigger another call, and so on ...

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you timgeb "return auswahl ()" works. I will read that link and try my luck with "try" and "except".
@KapitaenWurst no problem. The accepted answer in that other question is a complete guide how to write a good function that takes user input.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.