Python Program to Convert Binary Number to Decimal and vice-versa

In this example, we will convert a binary number into a Decimal number and a Decimal number into Binary number using Python User-Defined function.

A user-defined function is a function that is not available in the language or in any other library and a user generates this function to achieve something special.

Python function to Convert Decimal number into Binary Number

#   program to find out binary equivalent of any decimal number
#   made by         : rakesh kumar
n = int(input('Enter any number :'))
l = ''
while(n != 0):
    l = str(n % 2) + l
    n = n//2

print(l)

Output of the above decimal to bianry conversion function

rakesh@folio MINGW64 /e/python (master)
$ python -u "e:\python\Loops\decimal_binary.py"
Enter any number :6
110

Program to convert Binary Number into Decimal number

#   program to find out decimal number of any given binary number
#   made by         : rakesh kumar
n = int(input('Enter any number  :'))
sum = 0
i = 0
while n != 0:
    rem = n % 10
    sum = sum+rem*2**i
    n = n//10
    i = i+1

print('Decimal Equivalent :', sum)

Output of binary into decimal conversion

rakesh@folio MINGW64 /e/python (master)
$ python -u "e:\python\Loops\binary_decinal.py"
Enter any number :1101
Decimal Equivalent : 13

rakesh@folio MINGW64 /e/python (master)
$ python -u "e:\python\Loops\binary_decinal.py"
Enter any number :11101
Decimal Equivalent : 29

rakesh@folio MINGW64 /e/python (master)
$ python -u "e:\python\Loops\binary_decinal.py"
Enter any number :11001101
Decimal Equivalent : 205

  
  

Related Posts

If you like CBSEToaday and would like to contribute, you can also write an article using submit article or mail your article to contribute@cbsetoday.com See your article appearing on the cbsetoday.com main page and help other students/teachers.