4. Digit_sum

#1

on the console window display this:
File "python", line 3
n = abs(n)
^
SyntaxError: invalid syntax

...and under:
Oops, try again. Did you create a function called digit_sum? Your code threw a "global name 'digit_sum' is not defined" error.

Is probably a bug of the site??
Thx all!

``````n=(raw_input('Number?')

n = abs(n)
a=[]

def digit_sum(n):
str(n)
for i in n:
i = int(i)
a.append(i)
b=sum(a)
return b

digit_sum(n)``````

#2

look at the parentheses on line 1

The exercise will validate your function works correctly by calling, not the whole script, keeps this in mind

#3

Focus only on the function itself. Include list inside the function and double check that everything is how it should be.
(Hint. Have you successfully transformed the given number to string?)

#4

This list will never reset itself since it is outside of the function. That will cause problems on subsequent calls.

This is not doing anything, therefore `n` is still a number. This will raise an exception. Be sure to assign it to something.

There is a less complicated approach to this. Instead of appending integers to a list, why not just add them to a running total?

Consider also that your global variable, `n` has the same name as your local variable (the parameter) which may be confusing for your reader. There is nothing blatantly wrong with this, it just makes things less clear.

It's fine to have user input outside of the function (where it belongs) but the statement to convert to `abs()` should rightly be inside the function where it makes the most sense.

``````def digit_sum(x):
x = abs(x)``````

Even better, we can do two things at once,

``````s = str(abs(x))
total = 0``````

Now we can iterate over the string and accumulate the total:

``total += int(i)``

Let your user input and the call to the function both follow the function so the global code is grouped in one place.

#6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.