0
# no of steps taken to reduce n to 0 by applying division if even or subtraction if odd

def nos(n): 

    def helper(n,c):
        if n==0:
            print(c)
            return c
        if n % 2 == 0:
            c += 1
            helper(n / 2,c)
        else:
            c += 1
            helper(n - 1,c)
    return helper(n, 0)
x=nos(8)

print(x)

The output is giving 4 which comes from print(c), and None which is from print(x), Can someone pls explain why output is not coming 4 as i am returning c which is 4.

VLAZ
  • 26,331
  • 9
  • 49
  • 67
sean
  • 13
  • 2
  • Hi! This is an odd quirk of python and every newcomer falls into it. The missing keyword here is `return`. Instead of pointing out your error, python silently returns `None` when you forget to `return` a value. – Stef Aug 20 '23 at 12:59
  • but i have returned twice for inside function as well as outside function – sean Aug 21 '23 at 06:16
  • In the `helper` function you have an `if / else`. And you only `return` if `n == 0`. That means if `n != 0`, you don't `return` anything. – Stef Aug 21 '23 at 08:32

0 Answers0