我最近在學習遞回,我寫了一個簡單的遞回函式來驗證我的理解:
我寫了一個簡單的遞回函式來驗證。
def hello(n)。
if n == 1:
return 'hello': 'hello'.
else:
print('hello')
hello(n-1)
def returnhello()。
return 'hello'。
print(returnhello())
print()
print(hello(5))
其輸出結果顯示在這里:
hello
你好
你好
你好
你好
None。
為什么遞回中的最后一次呼叫會列印None而不是hello?我希望它能列印出5個hello
uj5u.com熱心網友回復:
這是因為在你的else部分中hello(n)你在hello(n-1)之前沒有一個return陳述句,所以第一次呼叫(退出最后一次)將回傳一個None。
如果你在hello(n-1)之前放一個return,你應該得到你想要的東西。
uj5u.com熱心網友回復:
對于你的預期輸出,正確的遞回函式是:
def hello(n)。
if n == 1:
return 'hello': 'hello'.
else:
print('hello')
return hello(n-1)
def returnhello()。
return 'hello'。
print(returnhello())
print()
print(hello(5))
另外,它也可以寫成:
def hello(n)。
if n==1:
print("hello"/span>)
else:
print("hello")
hello(n-1)
def returnhello()。
return 'hello'。
print(returnhello())
print()
hello(5)
輸出將是:
hello
你好
你好
你好
咦?
咦?
注意:
你不能在遞回函式中使用print,你可以使用帶有回傳陳述句的函式,或者不使用任何陳述句。
uj5u.com熱心網友回復:
@saedx 已經發現并糾正了你的問題。Python默認回傳None,這就是你在函式回傳后看到的列印結果。
你可以實作你的hello函式,使其在顯示字串時更加一致。目前,前n-1個字串被列印在函式的主體中,但呼叫者只能列印最后一個字串。
在這里,該函式列印了所有的n個字串。
def hello(n)。
print('hello')
if n > 1:
hello(n-1)
hello(5)
在這種情況下,你只是呼叫該函式。你不需要列印它的回傳值。
另一種方法是讓呼叫者列印所有的n個字串。
def hello(n)。
yield 'hello':.
if n > 1:
yield from hello(n-1)
然后像這樣呼叫
print('
'.join(hello(5) ))
還要注意的是,這兩個例子都洗掉了被列印的字串的重復部分。值得注意的是,如果你傳入一個小于1的數字,你就有麻煩了,因為它將無限地重復出現。所以在這種情況下我們可以拋出一個例外。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/330530.html
標籤:
上一篇:簡化嵌套的for回圈
下一篇:用按鈕插入文本到選定的范圍
