0
def spynum (n,r,sm=0,pd=1):

 #s = 0

 #p = 1

 #b = False 

 if n == 0:

  print (sm==pd)

  return sm == pd

 else:

  rem = n % 10

  sm += rem

  pd *= rem

  print (sm,pd,rem)

  spynum(n//10,rem,sm,pd)

num = 1124

print (spynum(num,num%10,0,1))

The program returns Boolean also working if I print the variable inside base condition but it is not print the same outside the function.Im really confused ABT it !

1
  • You are calling spynum from inside spynum from inside spynum ... and so on. At some point the last invocation finds that n == 0 and returns a boolean. That boolean is returned to the invocation before it, which simply ignores it, not to the main program. You need to propagate the answer back through your chain of spynum invocations, all the way to the top and the main program. It's probably just a one-word change: add return before the recursive invocation of spynum. Commented Jan 8, 2023 at 4:34

2 Answers 2

0
def spynum (n,r,sm=0,pd=1):
 #s = 0
 #p = 1
 #b = False 
 if n == 0:
  print (sm==pd)
  return sm == pd <-- returns either true or false
 else:
  rem = n % 10
  sm += rem
  pd *= rem
  print (sm,pd,rem)
  spynum(n//10,rem,sm,pd)
num = 1124
print (spynum(num,num%10,0,1))

The == operator compares and returns either a true or false value. To return a number, consider returning an int value.

Sign up to request clarification or add additional context in comments.

Comments

0

Recursive functions work exactly like non-recursive functions; they return to their immediate caller, and if you don't return a value on some path, they return None.

You need to return the recursive result:

def spynum (n, r, sm=0, pd=1):
    if n == 0:
        print (sm == pd)
        return sm == pd
    else:
        rem = n % 10
        sm += rem
        pd *= rem
        print (sm, pd, rem)
        return spynum(n//10, rem, sm, pd)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.