Javaexercise.com

Python bin() Method

Python bin() method is a built-in method. It returns a binary string of an integer number. The binary string prefixed with “0b”.


Signature

bin(x)

Parameter Description
x (Required) This argument is an integer number.


Return Value

It returns a binary string of an integer value.


Error: It returns an error (TypeError), if the argument is not an integer.


Python bin() Method Example

Let’s first understand, how this method works and what does it return?

#bin() method
val1 = bin(5)
print(val1)
val2 = bin(100)
print(val2)
 Output:
0b101
0b1100100

As you can see, in the above example, both values are integer and converted to binary by prefix '0b' to the generated value.


Python bin() Method Example: If we use non-integer value

#bin() method
val1 = bin(2.5)
print(val1)
 Output:
TypeError: 'float' object cannot be interpreted as an integer