by BehindJava

Write a program to print binary number using recursion in Python

Home » python » Write a program to print binary number using recursion in Python

In this tutorial we are going to learn about Writinh a program to print binary number using recursion in Python.

Function to print binary number using recursion

Decimal number is converted into binary by dividing the number successively by 2 and printing the remainder in reverse order.

tit

def convertToBinary(n):
   if n > 1:
       convertToBinary(n//2)
   print(n % 2,end = ” ”)

# decimal number
dec =int(input(‘enter a number”))
convertToBinary(dec)
print()

Explanation:

  • Firstly, write a function called convertToBinary and pass a pareameter n ,if n is greater than 1 then recurse the function by dividing n with 2 then print reminder of n.
  • Take user input.
  • Finally, print it.