簡體   English   中英

Python 中遞歸結束時不需要的無

[英]Unwanted None at the end of the Recursion in Python

當我嘗試使用遞歸打印從 1 到 n 的所有自然數時,我在結果末尾得到 None 我的代碼

def num_1_to_n(n):
   if n==1:
        return n
   print(n)
   print(num_1_to_n(n-1))
n=int(input(enter the n value))
num_1_to_n(n)

我想得到

4
4
3
2
1

但我明白了

4
4
3
2
1
None
None
None

誰能告訴我在 1 之后打印None的原因

遞歸經常會出現這樣的問題,所以使用for循環:

n = int(input("Enter the n value"))
for i in range(n, 1, -1):
    print(i)
print(1) # for the loop to not stop at 2

或者,更短:

n = int(input("Enter the n value"))
for i in range(n, 0, -1):
    print(i)

試試這個代碼

def num_1_to_n(n):
   if n==1:
       print(1)
       return n
   print(n)
   num_1_to_n(n-1)
n=int(input("enter the n value"))
num_1_to_n(n)

Output:

enter the n value4
4
3
2
1

因為 print(num_1_to_n(n-1)) 這個打印,你把那些沒有門

在您的代碼中

def num_1_to_n(n):
   if n==1:
        return n
   print(n)
   print(num_1_to_n(n-1))

語句print(num_1_to_n(n-1))打印 function 調用num_1_to_n(n-1)的返回值。 您的 function 在n == 1的情況下返回1 ,否則返回None ,因為Python 在到達 ZC1C425268E68385D1AB5074C17A94F1Z4 主體的末尾時隱式返回None (執行期間):

return 語句返回來自 function 的值。 沒有表達式參數的返回返回無。 從 function 的末端掉落也返回 None

因此,當您從4開始時,您將看到三個None用於n != 1的三個調用。

你也可以這樣嘗試:

def num_1_to_n(n):
  if n > 1:
      print(n)
      num_1_to_n(n-1)
  else:
      print(1)

n=int(input('enter the n value: '))
num_1_to_n(n)

當您只需要像num_1_to_n(n-1)一樣調用 function 時,它正在打印None因為您是print(num_1_to_n(n-1)) ) 。

最終代碼:

def num_1_to_n(n):
   if n==1:
        print(1)
        return n

   print(n)
   num_1_to_n(n-1)

n=int(input("enter the n value"))
num_1_to_n(n)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM