This forum is now read-only. Please use our new forums! Go to forums

banner
Close banner
0 points
Submitted by Aalok Kamble
about 11 years

object of type 'int' has no len()" error.

Following code gives results as expected. it works. but i get error-“Oops, try again! Does your digit_sum function take exactly one argument (a positive integer)? Your code threw a “object of type ‘int’ has no len()” error.”

def digit_sum(x):
    add=0
    y = int(x)
    for i in range(len(x)-1,-1,-1):
        add+= y/10**i
        y -= (y/10**i) * (10**i)
    return add

num = raw_input("Enter num:")
print digit_sum(num)

Answer 51c2f4737c82ca42e3009095

1 vote

Permalink

The problem is: your function is designed to handle strings. If you give it a string (that you obtained from the user via raw_input, then everything’s fine. But the exercise (more precisely, its submission correctness test) expects your function to accept integers, so it tests your function by calling it with, say 5 as an argument: digit_sum(5), expecting it to return 1. But an int such as 5 doesn’t have a len()gth, so your function produces an error.

Just change it to accept an integer – you can still convert that into a string internally, then go digit-by-digit as you are doing now.

By the way – why all the complicated math (unless you just wanted to exercise)? Why not simply do as the function’s name suggests: calculate the sum of the single digits? See here for the possibly shortest solution.

points
Submitted by Alex J
about 11 years

2 comments

Aalok Kamble about 11 years

Thanks. Correct link for the possibly shortest solution.

Alex J about 11 years

Changed the link.