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))
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.
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
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))
Both the above methods will work and give the same result, you can choose the one you are more comfortable with.