-1

Why this code return None? But print(sum_) in else, gives the correct answer

n = 942
def digital_root(n):
    n_str = str(n)
    result = []
    sum_ = 0
    for i in range(0, len(n_str), 1):
        result.append(int(n_str[i: i + 1]))
    for i in result:
        sum_ += i
    
    if len(str(sum_)) > 1:
        digital_root(sum_)

    else:
        return sum_
InSync
  • 4,851
  • 4
  • 8
  • 30
onecry
  • 1

2 Answers2

0

Here when you are calling the function recursively it calculates the root correctly but it is not returning anything to the caller.

if len(str(sum_)) > 1:
     return  digital_root(sum_)

Please add the return statement and try.

Luff li
  • 123
  • 2
  • 11
0

you lose return before the digital_root(sum_) digital_root(sum_) -> return digital_root(sum_)

def digital_root(n):
    n_str = str(n)
    result = []
    for i in range(0, len(n_str), 1):
        result.append(int(n_str[i: i + 1]))

    sum_ = sum(result)
    if len(str(sum_)) > 1:
        return digital_root(sum_)
    else:
        return sum_
Xiaomin Wu
  • 400
  • 1
  • 5