Decimal to Binary in Python

Written by

Himani Kohli

Program to convert decimal to binary in Python

In this program, we will be learning to perform conversions such as decimal to binary.

To find the result we need to divide the number by 2 successively and printing the number in reverse order. This program works for whole numbers only. 

I would encourage you to perform the program of decimal to binary conversion for the real numbers using python.

Algorithm: 

  1. Define a function named dectobin(n)
  2. If statement is used to perform the conversions.
  3. Print the number after every iteration.
  4. Input the decimal number from the user.
  5. Call the function dectobin(n)
  6. Function statements are performed.
  7. Print result.
  8. Exit

 

Code:

def dectobin(n):

    if n>1:

        dectobin(n//2)

    print(n%2,end='')

n=int(input("Enter the decimal number: "))

dectobin(n)

 

Output:

Enter the decimal number: 5

101

Decimal to Binary in Python