简体   繁体   English

函数的返回值为none

[英]Return value of a function is none

I'm a beginner in Python. 我是Python的初学者。 Here is a simple code that I wrote in python that recursively counts the number of occurrences of a character in a string. 这是我在python中编写的一个简单代码,它以递归方式计算字符串中字符的出现次数。 The inputs are hardcoded. 输入是硬编码的。 Please see the comments if required 如果需要,请参阅评论

# . : 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

But i'm getting the following error 但我收到以下错误

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

What could be the cause? 可能是什么原因?

The code is missing return in recursive calls in elif , else blocks; 代码缺少在elif中的递归调用returnelse阻塞; returning function without return statement cause the None to be returned. 返回没有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)  # <---

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM