Write a Python Program to Convert Decimal to Binary Using Recursion

As a Python programmer, you may come across the need to convert decimal numbers to binary.

There are several methods to do this, but one efficient and elegant way is to use recursion.

In this tutorial, we will discuss how to write a Python program to convert decimal to binary using recursion.


Before we dive into the code, let’s quickly go through the concept of recursion.

Recursion is a programming technique where a function calls itself to solve a problem.

This technique can be useful when you need to solve a problem that can be broken down into smaller sub-problems of the same type.

The recursion function keeps calling itself until it reaches the base case, where the function stops calling itself and returns the final result.

Now, let’s move on to the Python code to convert decimal to binary using recursion.

def decimal_to_binary(n):
    if n == 0:
        return 0
    else:
        return (n %% 2 + 10 * decimal_to_binary(int(n / 2)))

In this code, we define a function called decimal_to_binary that takes in a decimal number as its argument.

The function uses recursion to convert the decimal number to binary.

The first line of the function checks if the decimal number n is equal to 0.

If it is, the function returns 0 as the binary representation of 0 is also 0.

If n is not 0, the function continues with the recursion.

The function calculates the remainder of n when divided by 2 using the modulo operator (%).

This remainder is the rightmost digit of the binary representation of n.

The function then calls itself with n/2 as the argument to get the binary representation of the quotient.

The function multiplies the result of the recursion by 10 and adds the remainder to get the final binary representation of n.

Let’s see how this function works with an example.

Suppose we want to convert the decimal number 13 to binary.

  • The remainder of 13 when divided by 2 is 1. This means that the rightmost digit of the binary representation of 13 is 1.
  • We call the decimal_to_binary function with the argument int(13/2), which is 6. This will return the binary representation of 6, which is 110.
  • We multiply the result of the recursion by 10 and add the remainder, which gives us 1101. This is the binary representation of 13.

In conclusion, converting decimal to binary using recursion is a straightforward and elegant way to solve this problem.

The recursive function breaks down the problem into smaller sub-problems until it reaches the base case and returns the final result.

The Python code we discussed in this tutorial can be used to convert decimal numbers to binary, and it’s easy to understand and implement.