39
loading...
This website collects cookies to deliver better user experience
bin()
is a built-in function in Python that takes an integer and returns the binary equivalent of the integer in string format. If the given input is not an integer, then the __index__ ()
method needs to be implemented to return an integer. Otherwise, Python will throw a TypeError exception.bin()
* method is**bin(num)**
bin()
function takes a single argument, an integer whose binary representation will be returned. __index__ ()
method needs to be implemented to return a valid integer.bin()
method returns the binary equivalent string of the given integer.bin()
function.# Python code to demonstrate the bin() function
number = 100
print('The binary equivalent of 100 is:', bin(number))
The binary equivalent of 100 is: 0b1100100
# Python code to demonstrate the bin() function
number = 100.66
print('The binary equivalent of 100 is:', bin(number))
raceback (most recent call last):
File "c:\Projects\Tryouts\main.py", line 3, in <module>
print('The binary equivalent of 100 is:', bin(number))
TypeError: 'float' object cannot be interpreted as an integer
bin()
method does not raise an exception even if the argument passed is not of integer type since we have implemented the __index__ ()
method in our class, which always returns the positive integer.# Python code to demonstrate the bin() function using __index__ ()
class TotalPrice:
apple = 100
orange = 50
watermelon=22
def __index__ (self):
return self.apple + self.orange + self.watermelon
print('The binary equivalent of Total Price object is:', bin(TotalPrice()))
The binary equivalent of Total Price object is: 0b10101100