The int() function in Python can convert various types of values into integers, including strings, floating point numbers, and other types. The int() function converts the integer representation in the string to an integer type, rounds down the floating point number to an integer, and specifies the base to be converted through the second parameter. This function is widely used in data type conversion and integer operations.
#In Python, the int() function is used to convert a value to an integer (int). It can accept arguments of different types and try to convert these arguments to integers. The following are some common uses of the int() function:
Convert a string to an integer:
num_str = "123"num = int(num_str)print(num) # 输出:123
The int() function can convert a string representing an integer to Integer type.
Convert floating point numbers to integers:
num_float = 3.14num = int(num_float)print(num) # 输出:3
int() function will round down floating point numbers and convert them to integers.
Convert other types to integers:
bool_val = Truenum = int(bool_val)print(num) # 输出:1
When converting a Boolean value to an integer, True will be converted to 1 and False will be converted to 0.
Specify base conversion:
num_str = "10"num = int(num_str, 2)print(num) # 输出:2
int() function can also accept a second parameter, indicating the base represented by the string to be converted, such as int ("10", 2) will convert the binary string "10" to decimal 2.
In general, the int() function is used to convert other types of data into integer types. Of course, data type compatibility and possible loss of data accuracy need to be considered when doing conversions.
The above is the detailed content of What is the use of int() function in python. For more information, please follow other related articles on the PHP Chinese website!