python

Python program to convert decimal to binary

In this tutorial, we are going to see how to write a programs to convert a decimal number into an equivalent binary number. We will see two Python programs, the first program performs the conversion using a user-defined function and in the second program, we use a built-in function called bin() for decimal to binary conversion.
 

Python program to convert decimal to binary using a recursive function

In this program, we have defined the function decToBin(). This function takes the decimal number as an input parameter and converts it to an equivalent binary number.
 
[st_adsense]

def decToBin(n):
    if n > 1:
        decToBin(n // 2)
    print(n % 2, end='')


# Asks the user to enter a number
nbr = int(input("Enter a decimal number: "))

decToBin(nbr)

Output:

Enter a decimal number: 9
1001
[st_adsense]  

Python program to convert decimal to binary using bin() function

In this program, we use a built-in function called bin() to convert the decimal number to binary.

# Asks the user to enter a number
nbr = int(input("Enter a decimal number: "))

# Print the binary number
print("Equivalent binary number: ", bin(nbr))

Output:

Enter a decimal number: 9
Equivalent binary number:  0b1001
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More [st_adsense]

Leave a Reply

Your email address will not be published. Required fields are marked *