【问题标题】:Recursive function return None even though print() works [duplicate]即使 print() 有效,递归函数也返回 None [重复]
【发布时间】:2021-12-10 00:45:27
【问题描述】:

我试图在这个递归函数中返回count,但它总是返回无。当我做print(count) 而不是return count 时,它给了我正确的结果。谁能告诉我我做错了什么?提前非常感谢你:)

count = 0


def count_lowercase(s, low, high):
    global count
    if low > high:
        return count
    else:
        if s[low] == s[low].lower():
            count += 1
        count_lowercase(s, low + 1, high)

【问题讨论】:

  • 你需要return count_lowercase(s, low+1, high)
  • 最后一行需要返回count_lowercase

标签: python recursion return


【解决方案1】:

您需要返回count_lowercase(s, low + 1, high),否则函数在执行完该语句后简单地结束,导致返回None

count = 0


def count_lowercase(s, low, high):
    global count
    if low > high:
        return count
    else:
        if s[low] == s[low].lower():
            count += 1
        return count_lowercase(s, low + 1, high)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-06
    • 2020-07-10
    • 2022-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-30
    相关资源
    最近更新 更多