python - 函数的返回值是none

标签 python python-2.7 recursion return-value

我是Python初学者。这是我用 python 编写的一个简单代码,它递归地计算字符串中字符出现的次数。输入是硬编码的。需要的话请看评论

# . : Logic : .
# Recursively counts the number of occurrences of a character
# in a given string and returns the count when the length of the string becomes zero

def recSearch(g_str, g_ch, val):
    # Length of string is zero, hence function will terminate
    if len(g_str) is 0:
        x = val
        print "Number of times [%s] occurs is %d" % (g_ch, x) 
        return val
        # ERROR : Returning none instead of a number

    # 1st character of string is a match
    # Hence val is incremented 
    elif g_str[0] is g_ch:
        recSearch(g_str[1:], g_ch, val + 1)

    # 1st character of string is NOT a match
    else:
        recSearch(g_str[1:], g_ch, val)

strSer = "this is most probably a valid string"
charSer = "t"
# Answer should be 3 for this input
# Feel free to experiment

print "The input string = [%s]" % (strSer)
print "Character to be found = [%s]" % (charSer)

i = recSearch(strSer, charSer,0)

print "I should be getting a valid return value %d" % i
# But instead, I'm getting an error here

但是我收到以下错误

Traceback (most recent call last):
File "sample2.py", line 31, in <module>
print "I should be getting a valid return value %d" % i
TypeError: %d format: a number is required, not NoneType

可能是什么原因?

最佳答案

代码在 elifelse block 中的递归调用中缺少 return;没有 return 语句的返回函数会导致返回 None

elif g_str[0] is g_ch:
    return recSearch(g_str[1:], g_ch, val + 1)  # <---
else:
    return recSearch(g_str[1:], g_ch, val)  # <---

关于python - 函数的返回值是none,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33537411/

相关文章:

python - 如何在不保留对连接器的引用的情况下连接到 python 中的 GObject 信号?

python - 使用正则表达式匹配字符串(特定字符串组合除外)

python - if 语句未命中中的 continue 断点

python - opencv2 Aruco 库模块不适用于 python

c++ - 不使用循环和数字和的数字根递归

python - 我不明白如何在游戏 FallDown 中的 pygame 中生成多个平台

python - 使用 pytest 记录毫秒

c++ - 函数返回错误值

Java : recursive constructor call and stackoverflow error

python - 使用自定义方法保存/加载 Keras 模型