Python bin() function

(Sponsors) Get started learning Python with DataCamp's free Intro to Python tutorial. Learn Data Science by completing interactive coding challenges and watching videos by expert instructors. Start Now!

The bin() function returns the binary representation of the integer as a string.

Its syntax is as follows:

numberAny numeric value

Here is an example:

bin() with User-defined object

To use bin() with user-defined objects, we have to first overload the __index__() method.
The __index__() method is used to coerce an object to an integer, in the context of slicing and index. For instance, consider the following:

When we access items in a list using indexing and slicing, internally Python calls __index__()  method of the int  object.

In addition to bin() , the __index__() method is also called when you call hex(), and oct()  on the object. Here is


Other Tutorials (Sponsors)

This site generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join over a million other learners and get started learning Python for data science today!

Leave a Reply

Your email address will not be published. Required fields are marked *