Decimal To Binary Conversion In Python

Decimal To Binary Conversion In Python

Published on July 05 2023

In this tutorial you will see how to convert decimal numbers into binary numbers using logical implementation with string and List. Also, we will use built in methods and understand each line in detail.

Source code


decimal_number = int(input("Enter any positive integer number:"))

# Method - 1 - Using String
def calculate_binary(num):
    binary_output = ""

    while (num>0):
        remainder = num % 2
        binary_output += str(remainder)

        num = num // 2

    return binary_output[::-1]


output = calculate_binary(decimal_number)
print('Binary Output:' , output)

# Method - 2 - Using List

def calculate_binary_with_list(num):
    binary_output = []

    while (num>0):
        remainder = num % 2
        binary_output.append(remainder)

        num = num // 2

    for i in range(len(binary_output)-1, -1, -1):
        print(binary_output[i], end='')

calculate_binary_with_list(decimal_number)

# Method - 3 - Using Built In Method - bin()

output = bin(decimal_number)
print(output[2:])

# Method - 4 - Using Built In Method - format()
output = format(decimal_number, 'b')
print(output)

Video