Python Tutorials

Python Programs

Python Convert Decimal to Binary using Recursion


Python Convert Decimal to Binary using Recursion

In this tutorial, we will learn how to convert a decimal number to binary using recursion in Python. We will cover the basic concept of binary numbers and implement a recursive function to perform the conversion.


What is Binary Conversion

Binary conversion is the process of converting a decimal (base-10) number to a binary (base-2) number. In binary, numbers are represented using only 0s and 1s.


Syntax

The syntax to convert a decimal number to binary using recursion in Python is:

def decimal_to_binary(n):
    if n == 0:
        return '0'
    elif n == 1:
        return '1'
    else:
        return decimal_to_binary(n // 2) + str(n % 2)


Converting a decimal number to binary using recursion

We can create a recursive function to convert a given decimal number to binary by continuously dividing the number by 2 and keeping track of the remainders.

For example,

  1. Define a function named decimal_to_binary that takes one parameter n.
  2. Check if n is 0. If true, return '0'.
  3. Check if n is 1. If true, return '1'.
  4. Otherwise, call the function recursively with n // 2 and append the remainder of n % 2 to the result.
  5. Call the function with a sample number and print the result.

Python Program

def decimal_to_binary(n):
    if n == 0:
        return '0'
    elif n == 1:
        return '1'
    else:
        return decimal_to_binary(n // 2) + str(n % 2)

# Convert 10 to binary
result = decimal_to_binary(10)

# Print the result
print('Binary representation of 10 is', result)

Output

Binary representation of 10 is 1010