Bin () function in Python

In Python programming, the bin () function converts and returns the binary string of the given integer. So what is the syntax of bin () function, parameters and how to use bin ()? Let's find out together.

In Python programming, the bin () function converts and returns the binary string of the given integer. So what is the syntax of bin () function, parameters and how to use bin ()? Let's find out together.

Python () function syntax (Python):

 bin(num) 

Parameters of bin () function:

The bin () function has only one parameter, num, ie the integer that takes the binary string. If the parameter is not an integer, it must execute the __index __ () method to return an integer.

What value does bin () return?

The bin () function returns a corresponding binary string of a given integer. Without specifying an integer, TypeError will be generated, highlighting the data type that is not understood as an integer.

Example of bin function ()

 # Ví dụ 1: Lấy chuỗi nhị phân của số nguyên 

so = 10
print('Chuỗi nhị phân của ', so, 'là: ', bin(so))

# Ví dụ 2: Dùng __index__() để chuyển đối tượng So_luong sang nhị phân

class So_luong:

hoa_hong = 5
hoa_dao = 10
hoa_sen = 15

def __index__(sl):
return sl.hoa_hong + sl.hoa_dao + sl.hoa_sen

print('Chuỗi nhị phân của So_luong là: ', bin(So_luong()))

After running the above program, we get the output as:

 Chuỗi nhị phân của 10 là: 0b1010 
Chuỗi nhị phân của So_luong là: 0b11110

From now on, whenever you need to get the binary value of a number or object, you just need to use the bin () function to finish.

See more:

  1. Built-in Python functions
  2. More than 100 Python exercises have solutions (sample code)
  3. The loop technique in Python
4 ★ | 1 Vote