Technology3 min read

Python bin() Method - Python Library Function

Abhishek Ahlawat

By Abhishek Ahlawat โ€” Recently

Founder of StudyTonight and a MERN fullstack developer. Writes about JavaScript, web development, Linux, and tech.

Summarize this article using AI

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!


Spotted something outdated or wrong?

Liked this? See more StudyTonight posts in Google results.

Add StudyTonight as a preferred source
Next questLIVE OPSStep 2 / 3

Practice real incidents in the browser

System Design Ops โ€” put out fires, ship fixes, and stack XP. Reading done. Time to play.

Play System Design
  • +XP

    Every sim

  • Incidents

    Live ops

  • Ranks

    Climb up

Read next