CLOSE

   python  library functions  
   Technology    Programming

Python bin() Method - Python Library Function

           
 AUGUST 2, 2019   by vineelpynam

In this tutorial, we will learn to implement python bin() library method. The main use of bin() function is, it converts and returns the binary equivalent string of a given integer.

What if, the parameter of bin method is not an integer?

In this case, bin() method implements __index__() method to return an integer.

python bin method

The bin method take only one parameter. Below is the syntax for bin() method.

Syntax:

bin( X )

# X can be an integer, or object, or anything the returns integer.




1. Executing the bin() Method

If you pass a string, or anything that doesn't an integer, as a parameter you will get TypeError exception saying the type cannot be interpreted as an integer.

Be aware of that, while using bin() method.

number = 10
print('The binary equivalent of 5 is:', bin(number))

After executing the program, the output will be:

The binary equivalent of 5 is: 0b1010




2. How to use __index__() method with Objects

__index__() is used to convert an object into a binary equivalent string.

class StudyToNight:
    study = 10
    to = 20
    night = 40
    
    def __index__(self):
        return self.study+ self.to+ self.night
        
print('The binary equivalent of quantity is:', bin(StudyToNight()))

After Executing the program, the output will be:

The binary equivalent of quantity is: 0b1000110



Conclusion:

Pheww! This is it. I hope that you enjoyed the post and learned about the bin() python library function. If you feel that this post is useful, please share it with your friends and colleagues.

Thanks for reading it till the end.


SHARE YOUR THOUGHTS WITH US!