0
def g(n):
    s = 0
    while n >= 1:
        s = s + n % 10
        n = n // 10

    if s // 10 == 0:
        return s
    else:
        g(s)


n = 0

while n != -1:
    n = int(input())
    print(g(n))

the sum up a integer until it reaches to a 1 digit number . for example n= 29

2+9=11

1+1=2

so the function should return 2 . but it return "None" . Can anyone please help me where the wrong is ?

CristiFati
  • 38,250
  • 9
  • 50
  • 87
maskur
  • 3
  • 5
  • 5
    You probably meant: `return g(s)` in the last function line. – CristiFati Jul 09 '22 at 23:49
  • its call the function itself when the number is not a one digit number. by the updated sum value of the current integer n . – maskur Jul 09 '22 at 23:52
  • 1
    Calling the function (itself) is one thing. Returning a result is another. You need to return the recursive call result, otherwise the function will return (by default) *None* (even if it computed the correct result) – CristiFati Jul 09 '22 at 23:54
  • Thank you . we should return the value which we got from the recursive call otherwise it will return none . return g(s) – maskur Jul 09 '22 at 23:58
  • 1
    Added a small improvement so that the program ends when user inputs ***-1***. – CristiFati Jul 09 '22 at 23:59
  • @MaskurAlShalSabil Just as an explanation; the recursive call `g(s)` will evaluate `2` but does not do anything with it. It is like writing the integer literal `2` on that line instead. So you need to return it. – akaAbdullahMateen Jul 09 '22 at 23:59
  • (Note that it works the same way that it would if you called *any other function*. Simply calling it does not cause anything to be returned.) – Karl Knechtel Jul 10 '22 at 00:01

0 Answers0