Python Program To Convert a Number From Decimal to Binary

Hey Shouters!! Today we have come up with the Decimal to binary number program in python.
In this blog, we will see programs to convert decimal number to an equivalent binary number. But if you are a beginner and do not know how to write programs in Python. Check it first Introduction to Python.
We will see two Python programs in this blog that will convert a number in the decimal number system to the binary number system.
- Using User Defined Function
- Using In-built Function
1. Decimal To Binary Using User Defined Function-
In this program we have defined a function declToBin() for the conversion. This function takes the decimal number as an input parameter and converts it into an equivalent binary number.
In this program, we take the input from the user and then call the function and then will recursively call the function to get the binary equivalent as mentioned in the program below.
1 2 3 4 5 6 7 8 9 10 11 12 |
"This function converts a number from decimal number system to binary system and prints the binary equivalent" def decToBin(num): if num > 1: decToBin(num // 2) print(num % 2) # Taking decimal number as user inyput number = int(input("Enter the decimal number: ")) decToBin(number) |
Output:
Enter the decimal number: 44
101100
Python program to convert decimal number to binary using bin()-
In this program, we are using an in-built function bin() to convert the decimal number to binary.
The function just takes the decimal number input from the user and then the function calculates the binary and returns the binary equivalent.
1 2 3 4 5 6 7 |
# Taking the decimal number from User number = int(input("Enter the decimal number: ")) # print the equivalent to binary number system print("Equivalent Binary Number: ", bin(number)) #the bin() returns the binary of decimal number |
Output:
Enter the decimal number: 34
Equivalent Binary Number: 100010
Please comment down your codes that you used for decimal to binary number in python.
If you are preparing for Campus Placement and want to learn more about the Online Tests and get the basic tips and tricks that are required. Please check our Instagram handle Shout Coders.