Digit_sum


#1
def digit_sum(n):
    string_n = str(n)
    total = 0 
    for char in string_n:
        total += int(n)
    return total    

Guyz please help me. I am getting the following error:

Oops, try again. Your function fails on digit_sum(434). It returns 1302 when it should return 11.


#2

434 + 434 + 434 = 1302, see the problem? You add the whole number to total each time


#3

Ohk, Now i see where is the problem. But how do I correct it???


#4

I only purpose showed you the problem, so you can take a couple of minutes to think about the solution. Which variable contains the individual digits from the number?


#5

Total is the variable !


#6

that is the variable in which we store the result, which variable contains each individual digit/charater of n so we can add it to total?


#7

“string_n” is that variable!!!


#8

that still contains the entire string, not each individual character. What is the purpose of the loop?


#9

so below is your code

def digit_sum(n):
string_n = str(n)
total = 0
for char in string_n:
total += int(n)
return total

now make the alteration at the 5th line.
use intead total += int(char)
because u are adding every char, not “n”


#10

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