# bin() in Python program

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

In this tutorial, we are going to learn about the bin() function.

## bin()

bin() function is used to convert a number to binary. If you pass a number to the bin() function, then it will return a binary representation of the number.

Binary numbers in the Python start with 0b. The result of the bin() function also starts with 0b. Don't confuse with that.

Let's see some examples.

### Example

# initialising a number
n = 2
# converting to binary using bin(n)
binary = bin(n)
# displaying the binary number
print(binary)

### Output

If you run the above code, you will get the following results.

0b10

### Example

# initialising a number
n = 100
# converting to binary using bin(n)
binary = bin(n)
# displaying the binary number
print(binary)

### Output

If you run the above code, you will get the following results.

0b1100100

If you pass an object other than a number, then you will get an error. Let's see one example.

### Example

# initialising a number
n = 'Hafeez'
# converting to binary using bin(n)
binary = bin(n)
# displaying the binary number
print(binary)

### Output

If you run the above code, you will get the following results.

TypeError       Traceback (most recent call last)
<ipython-input-4-2184ca5e2014> in <module>
3
4 # converting to binary using bin(n)
----> 5 binary = bin(n)
6
7 # displaying the binary number
TypeError: 'str' object cannot be interpreted as an integer

## Conclusion

If you have any doubts in the tutorial, mention them in the comment section.

Updated on 01-Nov-2019 08:00:45