[英]Python: Return Value and Return None
当我输入“N”或“n”时,我不明白为什么函数会返回正确的字母。 当我输入不正确的字母时,该函数被调用但返回“无”。 该函数应该保持循环直到输入正确的字母。
这是我输入正确字母时的输出。
(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()
您只是递归地调用您的函数,但对它产生的值不做任何处理。
它必须是return auswahl()
。
但是,请注意,在接受用户输入的函数中使用递归被认为是有害的,因为如果用户失败太多次,您可能会破坏堆栈。 请参阅我链接到的答案的“常见陷阱”部分。
~编辑~
但是,如果我在那里返回,它会回到 main 吗?! 递归是指函数调用自身?
是的,这里上下文中的递归是指调用自身的函数。 return auswahl()
不会立即从函数返回,它必须等待对auwahl
另一个调用产生的结果。 当然,在另一个调用中,用户可能会再次失败,这将触发另一个调用,依此类推……
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.