4/15 digit_sum


Write a function called digit_sum that takes a positive integer n as input and returns the sum of all that number’s digits. For example: digit_sum(1234) should return 10 which is 1 + 2 + 3 + 4. (Assume that the number you are given will always be positive.)

I’m not sure how to separate the digits of “n” without using a precise value. Do I count the digits first? I tried turning “n” into a string and calculating the length, but not sure what to do with that information.


that is a possible approach, given strings are iterable we can loop over the string to get each digit.


Ok. I’m trying to say:

  1. convert n to a string
  2. set a variable result, which will ultimately show the total
  3. calculate the sum of each digit for a range that spans zero to the length of whatever n is [Is this represented by i?]
  4. convert the digit in the string back to an integer and add it to the result
  5. print the answer

I’m not sure how to fix my following draft to reflect this:

def digit_sum(n):
	n = str(n) 
	result = 0
	for i in range(0, len(str(n))-1):
		result += int(i)
print digit_sum


i contains the indexes (thanks to range), by looping over n directly (without range) you get the values from the string, so that is much easier.

if you insist on using range, you have to use i as index to get value from string. You can square brackets to access string by index

print digit_sum, digit_sum() is a function call, so it should have parentheses.


Ok. I tried running the example with the recommended actions and received a response of “none.” Did I forget something?

n = 1234

def digit_sum(n):
	n = str(n) 
	result = 0
	for i in n:
		result += int(i)
print digit_sum(n)


you need to return the sum of the digits, as stated in the instructions

function return none by default at the end, so its a pretty big hint


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