To convert a decimal number to binary in Python, you can use the bin()
function. This function takes an integer as input and returns a string representation of the number in binary format.
Here’s an example of how to use the bin()
function to convert a decimal number to binary:
decimal_number = 42
binary_number = bin(decimal_number)
print(binary_number)
This will print '0b101010'
, which is the binary representation of the decimal number 42
.
You can also use the format()
function to convert a decimal number to binary and remove the '0b'
prefix that is added by the bin()
function. Here's an example:
decimal_number = 42
binary_number = format(decimal_number, 'b')
print(binary_number)
This will print '101010'
, which is the binary representation of the decimal number 42
without the '0b'
prefix.
Note that the bin()
and format()
functions only work with integers. If you want to convert a float to binary, you will need to use a different approach.