Open in App
Not now

# bin() in Python

• Difficulty Level : Medium
• Last Updated : 17 Sep, 2021

Python bin() function returns the binary string of a given integer.

Syntax:  bin(a)

Parameters : a : an integer to convert

Return Value : A binary string of an integer or int object.

Exceptions : Raises TypeError when a float value is sent in arguments.

## Python3

 `# Python code to demonstrate working of` `# bin()`   `# declare variable` `num ``=` `100`   `# print binary number` `print``(``bin``(num))`

Output:

`0b1100100`

## Python3

 `# Python code to demonstrate working of` `# bin()`   `# function returning binary string` `def` `Binary(n):` `    ``s ``=` `bin``(n)`   `    ``# removing "0b" prefix` `    ``s1 ``=` `s[``2``:]` `    ``return` `s1`   `print``(``"The binary representation of 100 (using bin()) is : "``, end``=``"")` `print``(Binary(``100``))`

Output:

`The binary representation of 100 (using bin()) is : 1100100`

### Example 3: user-defined object to binary using bin() and __index()__

Here we send the object of the class to the bin methods, and we are using python special methods __index()__ method which always returns positive integer, and it can not be a rising error if the value is not an integer.

## Python3

 `# Python code to demonstrate working of` `# bin()` `class` `number:` `    ``num ``=` `100`   `    ``def` `__index__(``self``):` `        ``return``(``self``.num)`   `print``(``bin``(number()))`

Output:

`0b1100100`

This article is contributed by Manjeet Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.