所以每当我尝试返回一个可选参数时,我发现在python中发生了一件奇怪的事情,或者至少我认为这就是它发生的原因。
这是我的代码
def reverse(string, output = ""):
if string == "":
print "winner: ", output
return output
output = output + string[-1]
string = string[:-1]
reverse(string, output=output)
以下是我运行时会发生的事情:
>>> output = reverse("hello")
winner: olleh
>>> print output
None
任何人都知道为什么我的回归总是没有?
答案 0 :(得分:2)
您必须返回递归调用的返回值。
def reverse(string, output = ""):
if string == "":
print "winner: ", output
return output
output = output + string[-1]
string = string[:-1]
return reverse(string, output=output)
答案 1 :(得分:0)
def reverse(string, output = ""):
if string == "":
print ("winner: ", output)
return output
output = output + string[-1]
string = string[:-1]
return reverse(string, output=output)
def main():
reverse("hello")
main()
OR
def reverse(string, output = ""):
if string == "":
print ("winner: ", output)
return output
output = output + string[-1]
string = string[:-1]
return reverse(string, output=output)
reverse("hello")
两个输出
>>>
winner: olleh
>>> ================================ RESTART ================================
>>>
winner: olleh
>>>