4. digit_sum


Hey guys I'm having some trouble doing this exercise, can someone show me what i'm doing wrong?


This is the exact link to the exercise.

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

This is what i've been working on:

my_list = []

def digit_sum(n):
    total = 0
    n = str(n)
    for number in n:
    total += sum(my_list)
    return total


Functionally your code seems to be working, but I do see a problem with how you've constructed it and that is what is causing you issues. Because my_list is a vital part of your function and only being used by it, you should place it within your function. Once you move my_list to be inside of the function than everything should work fine.


I'd like to piggyback onto this. The code I've written seems to work fine, but it prints the answer as well as None. This is causing it to fail. Here is my code

import math

a = input("input a number: ")

def digit_sum(n):
    nums = [int(x) for x in str(n)]
    print sum(nums)

Edit: I got it to work. Just had to use return instead of print in the function.


Glad you got it to work!


This is how it should work with return and printing:
(If you use "print function(argument)" it will print what the function returns.)

import math

a = input("input a number: ")

def digit_sum(n):
nums = [int(x) for x in str(n)]
return sum(nums)

print digit_sum(1234)


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