Python bin() Function with Examples

The bin() built-in python function is used to convert an integer number and return the equivalent value in the form of binary string. If there....

In this tutorial we will discuss about the bin() function in python programming language with the help of examples.

Python bin() function

Python bin() function

The built-in python function is used to convert an integer number and return the equivalent value in the form of binary string. If there is no integer then this function is used with the method to get an integer number. If we don't use the method and the specified number is not an integer then it returns as result which highlights that the given number can't be interpreted as an integer.

Syntax

bin(num)

Parameters of bin() function in python

The function in python takes only one argument i.e. an integer number. An integer number which is to be converted into binary string format.

If there is no integer then this function is used with the method to get an integer number.

Return value of Python bin() function 

The python bin() function is used to return an integer number into the equivalent binary string format. If the specified number is not an integer then it returns as result which highlights that the given number can't be interpreted as an integer.

Example 1: How to convert integer to binary using Python bin() Function

num = 15
print('The binary equivalent of 15 is:', bin(num))

Output

The binary equivalent of 15 is: 0b1111

Example 2: How to convert an object to binary implementing __index__() method

class vehicles:

    car = 11

    bike = 21

    bicycle = 8

    def __index__(self):

        return self.car + self.bike + self.bicycle

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

Output

The binary equivalent of vehicles is: 0b101000

Example 3: How to convert integer to binary with user define function

def Binary(n):

    num1 = bin(n)

    num2 = num1[2:]

    return num2

print("The binary representation of 10 is : ", end="")

print(Binary(10))

Output

The binary representation of 10 is : 1010