In this Python tutorial, we have provided a Python code that uses the recursion function to convert the Decimal number input by a user to its equivalent Binary number.
Python Concepts Required to Create this Program
- User-Defined Functions in Python
- if-else statements in Python
- Python Input/Output
- Python Recursion
Steps to Create the Program that Converts Decimal to Binary Using Recursion
- Ask the user to enter a decimal number.
- Create a recursive function in which the function calls itself again and again till the base condition is satisfied.
- In recursive function, we first divide the number with 2 and then again divide its quotient by 2. We continuously need to divide its quotient till we get the quotient as 1.
- At last, we reverse back all the remainders of the division process, which will give us the equivalent Binary Format.
For example, if we want to covert 34 into a binary number , we need to follow the below-mentioned procedure:
34 / 2 = quotient 17 remainder = 0 17/2 = quotient 8 remainder = 1 8/2 = quotient 4 remainder = 0 4/2 = quotient 2 remainder = 0 2/2 = quotient 1 remainder = 0 1/2 = quotient 1 remainder =1
Now we will write all reminders from bottom to top and this will give us the Binary number for 34. (34) 10 = (100010) 2
Python Program to Convert Decimal to Binary Using Recursion
def decTobin(n): if n > 1: #this recursion will call for dectobin(n//2) decTobin(n//2) print(n % 2,end = '') num = int(input("Enter the Number: ")) print(num,"in Binary is:",end=" ") decTobin(num)
Enter the Number: 8 8 in Binary is: 1000
Enter the Number: 12 12 in Binary is: 1100
Enter the Number: 16 16 in Binary is: 10000
To Sum it Up
Creating a Python program that can convert a decimal number to its equivalent binary number is quite easy. All you need to do is use a recursive function that continuously divides the input decimal number by 2 until the quotient remains 1.
We hope, that you have understood the Python program mentioned in this article easily. If you have any issues or suggestions, feel free to share them in the comments section below.
People are also reading:
- Python Program to Display Calendar
- WAP in C to Check Whether the Number is a Prime or not
- WAP in C++ & Python to calculate the size of each data types
- Python Program to Find HCF or GCD
- WAP to find the largest number amongst the numbers entered by the user
- WAP in C to check whether the number is a Palindrome number or not
- Python Program to Remove Punctuations From a String
- WAP to check whether a given character is an alphabet, digit or any special character
- WAP to swap two numbers
- Python Program to Find Sum of Natural Numbers Using Recursion
Leave a Comment on this Post