alirezajoolayi
alirezajoolayi

Reputation: 1

I converted a int to a str but I get "object of type 'int' has no len()"

This function is supposed to return the sum of digits of a number.

I converted the new variable into a string using new = str(x)

def digital_root(x):
    sum=0
    new = str(x)
    while len(new) > 2:
        for i in new:
            sum = sum + int(i)
        new = sum

    if len(str(new))==2:
        return int(new[0])+int(new[1])

Called with e.g. digital_root(65536). But it returns:

TypeError: object of type 'int' has no len()

Upvotes: 0

Views: 92

Answers (1)

h4z3
h4z3

Reputation: 5458

Yes, you converted your variable, so when you first enter the while loop, it's a string.

However, inside the loop you do new = sum, where sum is of type int. So second check of the loop breaks because object of type 'int' has no len().

What you want is:

def digital_root(x):
    sum=0
    new = str(x)
    while len(new) > 2:
        for i in new:
            sum = sum + int(i)
        new = str(sum) # make sure each time you leave, your type is str

    if len(new)==2: # here you don't have to make it a string anymore
        return int(new[0])+int(new[1])

Upvotes: 1

Related Questions