Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is my Python function returning None?

I’m new to python and I tried creating a GCD function using Eucliean’s Algorithm. But any time I try to print the answer, it returns none. May someone let me know what I’m doing wrong.

Code:

def gcd(a,b):
    if a - b != 0:
        b = b - a
        b = abs(b)
        if a > b:
            a,b = b, a
            return gcd(a,b)
            
        else:
            gcd(a,b)
    else: 
        print(a)

x = input("Give First Num... ")

y = input("Give Second Num... ")

answer = gcd(int(x), int(y))

print("GCD = {}".format(answer))

Console:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

120
GCD = None

>Solution :

To return something, there is just a minor adjustment to make on your code :

def gcd(a,b):
    if a - b != 0:
        b = b - a
        b = abs(b)
        if a > b:
            a,b = b, a
            return gcd(a,b)
            
        else:
            return gcd(a,b)
    else: 
        return a

Written this way, your function will always return something assigned to answer.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading