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)
kit
  • 1,166
  • 5
  • 16
  • 23
KapitaenWurst
  • 83
  • 1
  • 5

1 Answers1

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 ...

timgeb
  • 76,762
  • 20
  • 123
  • 145
  • 1
    Thank you timgeb "return auswahl ()" works. I will read that link and try my luck with "try" and "except". – KapitaenWurst Oct 30 '18 at 15:06
  • @KapitaenWurst no problem. The accepted answer in that other question is a complete guide how to write a good function that takes user input. – timgeb Oct 30 '18 at 15:07