0

I'm quite new to python and ive been practicing on codewars, one of the kanas is as follows;


Given n, take the sum of the digits of n. If that value has more than one digit, continue reducing in this way until a single-digit number is produced. The input will be a non-negative integer.

Examples

16 --> 1 + 6 = 7

942 --> 9 + 4 + 2 = 15 --> 1 + 5 = 6

132189 --> 1 + 3 + 2 + 1 + 8 + 9 = 24 --> 2 + 4 = 6

493193 --> 4 + 9 + 3 + 1 + 9 + 3 = 29 --> 2 + 9 = 11 --> 1 + 1 = 2


my problem arises when i try to return the value. when i replace return with print, i get the answer i want, but when i use return i just get 'None'

I'll post my script bellow:

def digital_root(n):
    sum = 0
    for i in list(str(n)):
        sum += int(i)
    n = sum
    if len(str(n)) > 1:
        digital_root(n)
    else:
        print(n)

this prints the correct answer^

def digital_root(n):
    sum = 0
    for i in list(str(n)):
        sum += int(i)
    n = sum
    if len(str(n)) > 1:
        digital_root(n)
    else:
        return n

this returns none ^ unless the input value is 2 digits long

  • 2
    Does this answer your question? [How is returning the output of a function different from printing it?](https://stackoverflow.com/questions/750136/how-is-returning-the-output-of-a-function-different-from-printing-it) – Mechanic Pig Jun 05 '22 at 06:05

4 Answers4

2

You need to return the result of recursively calling digital_root if you want the original invocation of your function to return it in turn:

def digital_root(n):
    n = sum(int(i) for i in str(n))
    if len(str(n)) > 1:
        return digital_root(n)
    else:
        return n
>>> digital_root(123)
6
>>> digital_root(1)
1
Samwise
  • 51,883
  • 3
  • 26
  • 36
0
def digital_root(n):
    sum = 0
    for i in list(str(n)):
        sum += int(i)
    n = sum
    if len(str(n)) > 1:
        digital_root(n) # <-- A function returns the value where it is called,
                        # so when you eventually return n, what is it being assigned to?
    else:
        return n
BeRT2me
  • 2,930
  • 1
  • 4
  • 24
0

You need to return when calling the function recursively, else you compute the value but return nothing:

def digital_root(n):
    sum = 0
    for i in list(str(n)):
        sum += int(i)
    n = sum
    if len(str(n)) > 1:
        return digital_root(n)  ## return here
    else:
        return n

digital_root(12345)
# 6
mozway
  • 81,317
  • 8
  • 19
  • 49
0

To Solve This Error You need to define n like this n = sum(int(i) for i in str(n)) and You need to return the result of recursively calling digital_root if you want the original invocation of your function to return it in turn. Have Fun Now!

TUTO-REAL
  • 1
  • 1
  • 1