In Python programming, the bin() function converts and returns the binary string of the given integer. So what is the syntax of the bin() function, parameters and how to use the bin() function? Let’s find out together.
Syntax of bin() function in Python
bin(num)
Parameters of the bin() function:
The bin() function has only one parameter, num, which is the integer from which the binary string needs to be taken. If the parameter is not an integer, it must execute the method __index__()
to return an integer.
What value does the bin() function return?
Jaw bin()
Returns a binary string corresponding to the given integer. Failure to specify an integer will raise a TypeError, highlighting the data type is not interpreted as an integer.
Bin() function example
Example 1: Get binary string of integer
so = 10
print('Chuỗi nhị phân của ', so, 'là: ', bin(so))
#Kết quả đầu ra:
Chuỗi nhị phân của 10 là: 0b1010
Example 2: Use __index__() to convert object to binary
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()))
#Kết quả đầu ra:
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 a function bin()
that’s it.