Search code examples
pythonpython-3.xfunctionreturn

Why the function is not returning the value but printing the same?


See this function:-

def beej(v):
    v = sum(map(int, list(str(v))))
    if len(str(v)) <=1:
        print("printed: {}".format(v))  
        return v
    beej(v)

#outputs
>>> beej(23)
printed: 5
5                # returned
>>> beej(4221)
printed: 9
9                # returned
>>> beej(422199)
printed: 9       #no returned value
>>> beej(999)
printed: 9       #no returned value

So; its simply working for some values; and not for others. I'd like to know the reason behind this; and how to find such hidden bugs.


Solution

  • You are missing a return statement in the recursive call:

    def beej(v):
        v = sum(map(int, list(str(v))))
        if len(str(v)) <= 1:
            print("printed: {}".format(v))  
            return v
        return beej(v)
    

    Your current code will only return v if the first call to beej (ie no recursive calls) produces a single-digit sum.