Python Program To Convert Decimal To Binary

Hello everyone, welcome to nkcoderz.com. In this article we will going to discuss about Python Program To Convert Decimal To Binary.

Code For Python Program To Convert Decimal To Binary

def decimal_to_binary(num):
    binary = bin(num)[2:]
    return binary

# Test the function
print(decimal_to_binary(10))

Output

1010

Explanation

The program defines a function decimal_to_binary that takes an integer as an argument (num). Inside the function, it uses the built-in bin() function to convert the decimal number to its binary representation.

The bin() function returns a string representation of the binary number, with the prefix ‘0b’, so we slice the string to remove this prefix. The slicing is done by [2:]

Another way is to use a while loop to keep dividing the number by 2 and storing the remainder, then adding the remainder to a binary string, for each division.

def decimal_to_binary(num):
    if num == 0:
        return "0"
    binary = ""
    while num > 0:
        binary = str(num % 2) + binary
        num = num // 2
    return binary

# Test the function
print(decimal_to_binary(10))

Conclusion

Both the above methods will work and give the same result, you can choose the one you are more comfortable with.


If You Like This Page Then Make Sure To Follow Us on Facebook, G News and Subscribe Our YouTube Channel. We will provide you updates daily.
Shares
facebook sharing button Share
twitter sharing button Tweet
whatsapp sharing button Share
telegram sharing button Share
pinterest sharing button Pin

Leave a Comment