4/15 my code works in python shell but not codecademy


#1

Hi all - my code seems to spit out the correct number when I test it in a python shell but codecademy is saying it returns None

Basically I convert it to a string for looping purposes, then converts it back to an integer, and add it to the "grand total" variable.



#2

This is one of my favorite sections, there are two major ways to do this.

Ways:

  1. Convert to a string to be able to loop over
  2. Use floor division and modulus division to get the sum of digits

Here are the examples,

Way: 1

def digit_sum(number):
    return sum([int(digit) for digit in str(number)])

Way: 2 Python 3.* for 2.* use one /

def digit_sum(number, total=0):
    return total if not number else (digit_sum((number // 10), (total + number % 10)))

Regarding your code, just change it to the following. You have some extra steps in that are not needed.

def digit_sum(n):
    d = 0
    for x in str(n):
        d += int(x)
    return d

As you can see I just preform the conversion directly in the loop and then I convert it back into an int as it loops over the str of digits.


#3

The error message actually tells you pretty clearly why it's not working. You are not returning anything from the function.