Python:返回值,不返回任何值

Python:返回值,不返回任何值,python,Python,我不明白为什么当我输入“N”或“N”时,函数返回正确的字母。函数被调用,但当我输入错误的字母时返回“None”。 函数应保持循环,直到输入正确的字母 这是输入正确字母时的输出 (N)ew game Your choice?: n Your choice before returning the value to main: n Your choice: n (N)ew game Your choice?: j Wrong input (N)ew game Your choice?: n You

我不明白为什么当我输入“N”或“N”时,函数返回正确的字母。函数被调用,但当我输入错误的字母时返回“None”。 函数应保持循环,直到输入正确的字母

这是输入正确字母时的输出

(N)ew game
Your choice?: n
Your choice before returning the value to main: n
Your choice: n
(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
这是输入错误字母时的输出

(N)ew game
Your choice?: n
Your choice before returning the value to main: n
Your choice: n
(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
源代码:

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)
使用
auswahl()
只需递归调用函数,但不处理它生成的值

它必须是
返回auswahl()

但是,请注意,在接受用户输入的函数中使用递归,因为如果用户失败太多次,可能会破坏堆栈。请参阅我链接到的答案的“常见陷阱”部分

~编辑~


但如果我在那里放一个回程,它就会回到主干道?!对于递归,你的意思是函数调用自身


是的,在这种上下文中,递归指的是调用自身的函数
return auswahl()
不会立即从函数返回,它必须等待另一个调用
auwahl
产生的结果。当然,在另一个调用中,用户可能再次失败,这将触发另一个调用,依此类推…

您的
else
分支没有
返回
注意,尽管递归在这里是错误的解决方案。但是如果我在那里放一个返回,它将返回到main?!对于递归,你的意思是函数自己调用吗?谢谢timgeb“returnauswahl()”的工作原理。我会读那个链接,用“try”和“except”试试运气。@KapitaenWurst没问题。另一个问题的公认答案是一个完整的指南,指导如何编写一个接受用户输入的好函数。