When using raw_input() we must remember that the return is
<type 'unicode'>, not
<type 'int'>. This is important to note.
Passing the output of
raw_input() directly to a function requires that we convert it to the expected type, at which point we are faced with making assumptions that may not be valid. This means we need to filter.
test = True if re.match(u'^[0-9]+$', str(n)) else False
a = list(str(n))
# more code
return "Input Error!"
Now we have an interable in
a and can proceed with the final step, summing up the list elements.
# more code
for i in range(len(a)):
a[i] = int(a[i])
We have used a regular expression to match only digits, and nothing else. All other inputs will be rejected. Note the importance of importing the regular expression module without which this code will throw an error.
The power of Python is illustrated in the following example which uses a list comprehension built around the ternary expression above.
return sum([int(i) for i in str(n)]) if re.match(u'^[0-9]+$', str(n)) else "Input Error!"
I don't necessarily recommend this, though, since it also has some questionable code. We only really need to match the input at the start, not repeatedly in the loop. For that reason, this is undesirable code, even though it does work. Here it is meant only as an example.