4. digit_sum


#1



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

Thanks

This is the exact link to the exercise.
https://www.codecademy.com/courses/python-intermediate-en-rCQKw/0/4?curriculum_id=4f89dab3d788890003000096#


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:
        my_list.append(int(number))
    total += sum(my_list)
    return total


#2

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.


#3

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)
    
digit_sum(a)

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


#4

Glad you got it to work!


#5

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)


#6

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