Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

returning values of function in python

Why do I have to return function in the else case? Can't I just apply the defined function because I have to only return the value of b and store it?

def gcd_a(a,b):

    if a==0:
        return b
    else:
        gcd_a(b%a,a)
like image 552
Himanshu Jotwani Avatar asked Nov 19 '25 15:11

Himanshu Jotwani


1 Answers

I think the main concept you are missing is that in order to get the result of a recursive function (or any function for that matter), the function that you access the result of must return the value*

Right now, when you call gcd_a, a recursive call to gcd_a will eventually return a value, however it will be lost, since the function that you are accessing the result of does not return a value.

To show you this is true, let's add in a log statement that prints when the function is returning:

def gcd_a(a,b):
    if a==0:
      print('finally returning!', b)
      return b
    else:
        gcd_a(b%a,a)

Now if we call:

print(gcd_a(10, 99))

We get the following output:

finally returning! 1
None

Somewhere, a recursive call to gcd_a found your condition to be True, and returned 1, however, this result is not printed, because it is not returned by your call to gcd_a


* Unless you do something strange like updating a global variable, etc...

like image 79
user3483203 Avatar answered Nov 22 '25 04:11

user3483203