Python Program to Convert Decimal to Binary
In this post, we will see programs to convert decimal number to an equivalent binary number. We will see two Python programs, first program does the conversion using a user defined function and in the second program we are using a in-built function bin() for the decimal to binary conversion.
1. Decimal to Binary conversion using recursive function
In this program we have defined a function decimalToBinary() for the conversion. This function takes the decimal number as an input parameter and converts it into an equivalent binary number.
def decimalToBinary(num):
"""This function converts decimal number
to binary and prints it"""
if num > 1:
decimalToBinary(num // 2)
print(num % 2, end='')
# decimal number
number = int(input("Enter any decimal number: "))
decimalToBinary(number)
Output
Enter any decimal number: : 42
101010
2. Python program to convert decimal number to binary using bin() function
In this program, we are using a in-built function bin() to convert the decimal number to binary.
# decimal number
number = int(input("Enter any decimal number: "))
# print equivalent binary number
print("Equivalent Binary Number: ", bin(number))
Output
Enter any decimal number: 42
Equivalent Binary Number: 0b101010
Leave Comment