Home »
Python »
Python Reference »
Python Built-in Functions
Python bin() Function: Use, Syntax, and Examples
Python bin() function: In this tutorial, we will learn about the bin() function in Python with its use, syntax, parameters, returns type, and examples.
By IncludeHelp Last updated : June 23, 2023
Python bin() function
The bin() function is a library function in Python, it is used to get the binary value of a number, it accepts a number and returns an equivalent binary string.
Syntax
The following is the syntax of bin() function:
bin(number)
Parameter(s):
The following are the parameter(s):
- number – A valid number whose value can be converted to the binary.
Return Value
The return type of bin() function is <class 'str'>, it returns string containing binary value of given number.
Python bin() Function: Example 1
# python code to convert number to binary
# an example of bin() function in Python
num1 = 55 # number (+ve)
num2 = -55 # number (-ve)
# converting to binary
bin_str = bin(num1)
print("Binary value of ", num1, " is = ", bin_str)
bin_str = bin(num2)
print("Binary value of ", num2, " is = ", bin_str)
Output
Binary value of 55 is = 0b110111
Binary value of -55 is = -0b110111
Python bin() Function: Example 2
If the input value is not a valid integer, the method returns a TypeError.
# bin() with non-integer value
x = 10.2
print(bin(x))
Output
Traceback (most recent call last):
File "main.py", line 5, in <module>
print(bin(x))
TypeError: 'float' object cannot be interpreted as an integer