簡體   English   中英

Python function 總是返回無

[英]Python function always returning none

以下 function 在基本情況下返回 none 而不是 1,這是為什么呢?

def test(num):
  if(num == 1):
    print('our num is:',num)
    return num
  else:
    print(num)
    num -= 1
    test(num)
print(test(5))

因為你沒有在 else 下返回任何東西。 請參閱下面的代碼作為修復。

def test(num):
  if(num == 1):
    print('our num is:',num)
  else:
    print(num)
    num -= 1
    test(num)

  return num

print(test(5))

您只是忘記返回num來修復它:

def test(num):
  if(num == 1):
    print('our num is:',num)
    return num
  else:
    print(num)
    num -= 1
    return test(num)

然后運行print(test(5))將返回 1。

實際上,它在基本情況下非常返回1 問題是當通過所有遞歸層返回時,您不會將其傳播到調用堆棧上,如下圖所示,您使用3調用它:

Caller
|    ^
|    |
|  (None)
v    |
test(3) <-----+
 |            |
 |          (None)
 |            |
 +-----> test(2) <-----+
          |            |
          |           (1)
          |            |
          +-----> test(1)

在這種情況下:

  • 你打電話給test(3)
  • 它調用test(2)
  • 它調用test(1) ,返回1到 `test(2);
  • test(2)然后返回None到 `test(3);
  • test(3)返回None給調用者。

當您擺脫基本情況時,您已經返回1 然后,您沒有顯式返回任何內容到下一層,這意味着 Python 將隱式返回None

您將從當前代碼中獲得1的唯一情況是,如果您直接使用test(1)調用基本情況。

解決這個問題並進行一些可讀性改進,將因此完成(評論是為了解釋我的更改理由,它們不屬於真實代碼):

def test(num):
    # Handle pathological case of passing in something < 1.

    if num <= 1:
        # Will always print 1 so not sure why it's needed.
        print('our num is:',num)
        return num

    # No need for else since above if bit returns anyway.

    print(num)
    return test(num - 1) # just pass (num - 1) directly, and propagate.

你什么都不返回。 嘗試這個。

def test(num):
  if(num == 1):
    print('our num is:',num)
    return num
  else:
    print(num)
    num -= 1
    return test(num)

暫無
暫無

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

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