<Below this line, add a link to the EXACT exercise that you are stuck at.>
https://www.codecademy.com/en/courses/python-intermediate-en-rCQKw/0/4?curriculum_id=4f89dab3d788890003000096<In what way does your code behave incorrectly? Include ALL error messages.>
Oops, try again. Your function fails on digit_sum(434). It returns 1302 when it should return 11.<What do you expect to happen instead?>
i was expecting for n to become variable m changing the value of n to a string so it could be iterable so that in the for loop j makes m an integer and then i append to the empty list l
and then return the sum of list L


def digit_sum(n):
for i in m:
return sum(list(l))

<do not remove the three backticks above>


In the line
j=int (m)

Change m to i

i represents the digit in the string m.
i.e. i represents the item in the list m


thanks bro … it worked


Did take me some while but I got it to work with any value.
Thought would be nice to share.:smiley:

if n is -123
give you an error
Traceback (most recent call last):
File β€œβ€, line 8, in
File β€œβ€, line 5, in digit_sum
ValueError: invalid literal for int() with base 10: β€˜-’

if n is 12.3
Traceback (most recent call last):
File β€œβ€, line 8, in
File β€œβ€, line 5, in digit_sum
ValueError: invalid literal for int() with base 10: β€˜.’

To make it run always with negative and/or floats

def digit_sum(n):
    m=m.translate(None, ".,-")
    for i in m:
    return sum(list(l))

print digit_sum(-12.5)
# https://discuss.codecademy.com/t/digit-sum/33637/3
# study by @jeanpauljaspers

def digit_sum(n):
    l = []
    m = str(n)
    m = m.translate(None, ".,-")
    for i in m:
        j = int(i)
    return sum(list(l))
print digit_sum(-12.5)


Thank you for the help here! Can you walk me through the translate function, and what you have in between the parenthesis? Everything else seems to make sense.

Update: the m. tells you what to translate, correct?

And the None is included because you don’t need a table for strings, right?

And the β€œ.,-” is what is being removed from any string of numbers, in this case negatives, thousands with the comma, and decimals or floats, right?

Calling the translate function where you did translated into a string that can be easily converted into integers, for the summing of each characther.

In the for loop, you turned each character into an integer, and then appended each integer to list l, and then summed the contents of list l.

Is that right?


I used the translate function to make sure that all I’m left with is a number in string form.
The assignment was for positive outcome only.
So this β€œ.,-” takes care of that in the translate function.
As I understand the function, if you use NONE it will remove what is between the parentheses.

Everything was like you wrote.
The m. Is the string on which the function will perform the action.