Digit_sum


#1
   i am so lost don't know what to do plz help

#2

I solved this but there might be a better way to do it.

Basically you want a way to separate each digit in the input (n). Then, once they're separated you can add them all!

So if you remember, we can parse through each letter of a string.

For example, if x = "moose", x[0] would be the letter m. x[1] would be the letter o. etc.

So if we convert the number passed to (n) into a string, we'll be able to go through each number.

In the function you'll first want to set a variable called total and set it equal to 0.

Then, convert n into a string.

Then we can go through each letter in the string with a for-loop like this:

for item in n:
total += item

but remember, we converted (n) into a string. So, in that for loop we'll want to convert each item back into an integer before doing total+= item

Then, outside the for-loop but inside the function, remember to return total


#3

I solved this but my code prints out "None" after it executes and I'm at a loss why. Code below

def digit_sum(n):
#convert number to string for iteration
talley =[]
n = str(n)
total = 0
#iterate through the list splitting up the 'word'
for x in str(n):
talley.append(x)
if len(talley) ==len(n):
for y in talley:
total+=int(y)
print total

print digit_sum(434)


#4

The code you just posted prints total, but it doesn't return total. Also just a heads up, in your first for-loop you can just do: for x in n. You already set n = str(n) above it.

Hope this helps!


#5

thx it worked lol thx so much


#6

Thank you very much! Lesson learning 'print total' is not 'return total'.

Again, thank you. Man! Some journey! Very, very humbling.


#8