The bin() method converts a specified integer number to its binary representation and returns it.
Example
bin() Syntax
The syntax of bin() method is:
bin(number)
bin() Parameter
The bin() method takes in a single parameter:
number- an integer whose binary equivalent is calculated
bin() Return Value
The bin() method returns:
- the binary string equivalent to the given integer
TypeErrorfor a non-integer argument
Example 1: Python bin()
Output
The binary equivalent of 5 is: 0b101
In the above example, we have used the bin() method to convert the argument 5 to its binary representation i.e. 101.
Here, the prefix 0b in the output 0b101 represents that the result is a binary string.
Example 2: Python bin() with a Non-Integer Class
Output
TypeError: 'Quantity' object cannot be interpreted as an integer
Here, we have passed an object of class Quantity to the bin() method and got a TypeError.
This is because we have used a non-integer class.
Note: We can fix the TypeError above by using the Python __index__() method with a non-integer class.
Example 3: bin() with __index__() for Non-Integer Class
Output
The binary equivalent of quantity is: 0b101
Here, we have passed an object of class Quantity to the bin() method.
The bin() method doesn't raise a TypeError even if the object Quantity() is not an integer.
This is because we have used the __index__() method which returns an integer (in this case, sum of the fruits).
Recommended Readings: