Python Program to convert a decimal number to binary


February 26, 2022, Learn eTutorial
1311

To understand this example, you should have knowledge of the following Python programming topics:

What are decimal and binary numbers?

In this python program, we need to convert a Decimal number to a Binary number. So what is the difference between binary and decimal numbers? A decimal number is a number with base 10, for example, a natural number like 10. A binary number is a number with the base 2, which means a number represented using 1 and 0.

The Binary number system is crucial for a programmer as it is a Language that a machine understands called Machine language.

How to convert a decimal to binary in a python program?

In this python program, we have to convert decimal to binary means from base 10 to base 2. We have to divide the number and display the remainder, and this process has to be continued until the number is 1 or zero.

For example, if you have the number 6, then we divide it with 2, and we get 3 and remainder 0 and divide 3 with 2, we get 1 and remainder 1, and finally divide 1 with 2 we get 0 and again 1 as remainder. Take the remainders in reverse order. Hence the binary for 6 is 110.

We have to accept a number from the user and save that number in a variable after converting it to an integer using int. We use a user-defined function in python 'decimalToBinary' and call the function in recursive mode to get the binary result. Recursion is a process that we call a function call itself repeatedly. Let's break the code.

ALGORITHM

STEP 1: Accept a number from the user using an input function in python programming and convert it to a number using an int datatype.

STEP 2: Call the recursive function and pass the number to the function.

DECIMAL TO BINARY FUNCTION IN PYTHON

STEP 1: Use the def function to define a function in python and add the parameters in the parenthesis.

STEP 2: we have to define the function inside the def function. Use if the condition to check the user number is greater than 1.

STEP 3: Call the function recursively by dividing the number by two.

STEP 4: Print the number which is the remainder of number mod 2

STEP 5: Use the 'end='' ' to append the remainders to the end of the last result while using a recursive function.

Here we alter the default 'end=' value with no space. for example, we have 'hello' and 'world,' by using ' end= ' ' ' in the print statement, we will get the result as ' Hello world. 'By default, the 'end=' value parameter is ‘\n,’ newline character.

Python Source Code

                                          # Function to print binary number using recursion
def convertToBinary(n):
   if n > 1:
       convertToBinary(n//2)
   print(n % 2,end = '')

# decimal number
dec = 34

convertToBinary(dec)
print()
                                      

OUTPUT

100010