[SOLVED] python recursion function return

Issue

I want to make decimal-binary converter using recursion.
I’ve done it, but my function (below) returns None..
If I change return clause to print – it’s work properly.
But I want returning here!
What’s the problem?

def my_bin(num, result = ''): 

    if num == 0:
        return result[::-1]
    else:
        result += str(num%2)   
        my_bin(num//2, result)
       
my_bin(5) # None

Solution

One return is missing:

def my_bin(num, result = ''):

    if num == 0:
        return result[::-1]
    else:
        result += str(num%2)
        return my_bin(num//2, result)

my_bin(5)

Answered By – Brinfer

Answer Checked By – Cary Denson (BugsFixing Admin)

Leave a Reply

Your email address will not be published.