当我输入“N”或“n”时,我不明白为什么函数会返回正确的字母。当我输入不正确的字母时,该函数被调用但返回“无”。该函数应该保持循环直到输入正确的字母。这是我输入正确字母时的输出。(N)ew gameYour choice?: nYour choice before returning the value to main: nYour choice: n这是我输入错误字母时的输出。(N)ew gameYour choice?: jWrong input(N)ew gameYour choice?: nYour choice before returning the value to main: nYour 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()#maineingabe = auswahl()print("Your choice:", eingabe)
1 回答

大话西游666
TA贡献1817条经验 获得超14个赞
随着auswahl()
你只是调用你的函数递归,但什么都不做与它产生的价值。
它必须是return auswahl()
。
但是,请注意,在接受用户输入的函数中使用递归被认为是有害的,因为如果用户失败太多次,您可能会破坏堆栈。请参阅我链接到的答案的“常见陷阱”部分。
~编辑~
但是,如果我在那里返回,它会回到 main 吗?!递归是指函数调用自身?
是的,这里上下文中的递归是指调用自身的函数。return auswahl()
不会立即从函数返回,它必须等待另一个调用auwahl
产生的结果。当然,在另一个调用中,用户可能会再次失败,这将触发另一个调用,依此类推……
添加回答
举报
0/150
提交
取消