What is the Python bin() function?

bin() is an in-built function in Python that takes in integer x and returns the binary representation of x in a string format. If x is not an integer, then the _index()_ method needs to be implemented to obtain an integer as the return value instead of as a “TypeError” exception.

svg viewer

Code

The code below details how to convert the integer to binary using bin():

# Integer 15 represented in decimal
decimal = 15
# Integer 15 represented in hexadecimal
hexadecimal = 0xf
# Integer 15 represented in octal
octal = 0o17
print("Binary representation", bin(decimal))
print("Binary representation", bin(hexadecimal))
print("Binary representation", bin(octal))

Code

The code below details how to convert the user-defined object to binary using bin() and __index()__:

class Total:
def __init__(self, price, quantity):
self.price = price
self.quantity = quantity
# Implement __index()__ to return an integer
def __index__(self):
return self.price * self.quantity
# supply integral values to the constructor only
total_price = Total(1, 4)
print("Binary representation", bin(total_price))

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved