Digit_sum kept returning None


I'm doing the digit_sum exercise on the Practice makes perfect section of the Python course in Codecademy

I'm getting the message:

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

def digit_sum(n):
added_number = 0
for i in str(n):
added_number += int(i)
return added_number

number = raw_input("Enter your chosen number here: ")


When I run the code, it prompts for the user input. I enter: 1234

This is the output:

Enter your chosen number here: 1234

I have no idea what I'm doing wrong. I don't see where 4 is returned. Please help.


A function ends the moment a return keyword is reached

a return keyword is reached in the first run/iteration of your loop, so your function ends in the first iteration of the loop. That can't be right, the whole loop needs to run to get the digits sum


Simplify the problem by not drawing user input into the equation. Use a direct call with a literal.

print digit_sum(1234)

You are the user, nobody else. Once we pass these introductory lessons is the time to review, research and refine.


So in other words it needs to loop before it is returned?


how would I rewrite this code to make the function iterate through the entire loop?


by placing return outside the loop


I took your advice and changed it. Thanks.


Oh wow! It worked! I guess I'm still getting used to the spacing in Python. Thank you so much!


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