user8568440
user8568440

Reputation: 1

Nonetype function which should be an integer (Python)

a=0

def r(x):
    global a

    if len(str(x))==1:
        print(a)
        b=int(a)
        a=0
        return b
    else:
        a+=1
        print(a)
        r(reduce(lambda z, y: int(z)*int(y), list(str(x))))

def persistence(n):

    if len(str(n))==1:
        return 0
    else:
        return r(n)

(This is a challenge on codewars.com)

Why is the type(r(n))==NoneType? The variable b is an integer so why isn't the type of the function integer too?

Upvotes: 0

Views: 656

Answers (1)

Dan
Dan

Reputation: 537

I believe your problem is that you are not returning a value from the function in the else case. So you should add the return keyword as shown below:

a=0

def r(x):
    global a

    if len(str(x))==1:
        print(a)
        b=int(a)
        a=0
        return b
    else:
        a+=1
        print(a)
        return r(reduce(lambda z, y: int(z)*int(y), list(str(x))))

def persistence(n):

    if len(str(n))==1:
        return 0
    else:
        return r(n)

Upvotes: 1

Related Questions