beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

Python bin() Function (With Examples)

By Chaitanya Singh | Filed Under: Python Tutorial

The bin() Function is a standard library function in Python. It converts an integer number to an equivalent binary number.

Python bin() Function Syntax

bin(x)

Parameter: It takes a single parameter x, which is an integer number whose binary equivalent we want to find out. If x is not a Python int object, it has to define an __index__() method that returns an integer.

Return value: This function returns a binary String equivalent to the given integer number.

Python bin() Function Example

In the following example, we are using bin() function to find out the binary equivalent of an integer number 10.

#integer number
num = 10
print('The binary equivalent of 10 is:', bin(num))

Output:
Python bin function example

The bin() function example implementing __index__() method

When the object that we pass to the bin() function is not an integer then it has to define an _index_() method. Lets take an example to understand this:

Here we are passing an object of class Pets to the bin() function and it doesn’t return any error even though the object is not an integer, this is because we have implemented the _index_() method, which returns the sum of total animal counts which is an integer.

class Pets:
    dogs = 2
    cats = 3
    horses = 3

    def __index__(self):
        return self.dogs + self.cats + self.horses


print('The binary equivalent of Pets is:', bin(Pets()))

Output:
python bin index implementation example
Reference:
Built-in function bin()

Leave a Reply Cancel reply

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

Python Tutorial

Introduction

  • Python Tutorial
  • Python Introduction
  • Install Python
  • PyCharm IDE Installation
  • Python in PyCharm
  • Python Comments
  • Python Variables
  • Python Keywords & Identifiers
  • Python data types

Flow Control

  • Python If
  • Python if..else
  • Python if..elif..else
  • Python Nested If
  • Python for loop
  • Python while loop
  • Python break
  • Python continue
  • Python pass

Python Functions

  • Python Functions
  • Python Recursion

Python Datatypes

  • Python Numbers
  • Python List
  • Python Strings
  • Python Tuple
  • Python Dictionary
  • Python Set

Python OOPs

  • Python OOP
  • Python Class & Object
  • Python Constructors

Python Examples

  • Python Programs

Recently Added..

  • JSON Tutorial
  • Java Regular Expressions Tutorial
  • Java Enum Tutorial
  • Java Annotations Tutorial

Copyright © 2012 – 2021 BeginnersBook . Privacy Policy . Sitemap