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

banner
Close banner
0 points
Submitted by Aalok Kamble

# 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):
y = int(x)
for i in range(len(x)-1,-1,-1):
y -= (y/10**i) * (10**i)

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

1 vote

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