The bin() function converts a decimal to binary. You can use a positive or negative integer as the parameter to be converted.
Syntax
Below is the syntax of the function.
bin(n) Parameters : an integer to convert Return Value : A binary string of an integer or int object. Exceptions : Raises TypeError when a float value is sent as argument.
In the below example we convert a positive and a negative integer to binary. The results come out with a prefix of 0b to indicate that the number is a binary representation.
Example
n = input("Enter an integer :") dec_number = int(n) bin_number = bin(dec_number) print(bin_number)
Output
Running the above code gives us the following result −
Write the code result here. Result Enter an integer :23 0b10111 Enter an integer :-31 -0b11111
If we do not want the 0b prefix in front of the converted number, then we need to apply string function to remove the initial 2 characters.
Example
n = input("Enter an integer :") dec_number = int(n) bin_number = bin(dec_number) print(type(bin_number)) x = bin_number[2:] print(x)
Output
Running the above code gives us the following result −
Enter an integer :13 1101