Decimal to Binary in Python
Written by
Program to convert decimal to binary in Python
In this program, we will be learning to perform conversions such as decimal to binary.
To find the result we need to divide the number by 2 successively and printing the number in reverse order. This program works for whole numbers only.
I would encourage you to perform the program of decimal to binary conversion for the real numbers using python.
Algorithm:
- Define a function named dectobin(n)
- If statement is used to perform the conversions.
- Print the number after every iteration.
- Input the decimal number from the user.
- Call the function dectobin(n)
- Function statements are performed.
- Print result.
- Exit
Code:
def dectobin(n):
if n>1:
dectobin(n//2)
print(n%2,end='')
n=int(input("Enter the decimal number: "))
dectobin(n)
Output:
Enter the decimal number: 5
101