The int()
function in Python is used to convert a given value to an integer. It can take different types of input and convert them into integers based on specific rules. Here's the general syntax of the int()
function:
int(x, base=10)
The int()
function takes two arguments:
x
(required): The value to be converted to an integer. It can be a string, float, boolean, or another integer.base
(optional): The base in which the input value is represented. It can be an integer between 2 and 36. If not specified, the default value is 10.Here are a few examples to illustrate the usage of the int()
function:
# Converting a string to an integer
num_str = "42"
num_int = int(num_str)
print(num_int) # Output: 42
# Converting a float to an integer
num_float = 3.14
num_int = int(num_float)
print(num_int) # Output: 3
# Converting a boolean to an integer
bool_val = True
bool_int = int(bool_val)
print(bool_int) # Output: 1
# Converting an integer from a different base (binary)
binary_str = "10101"
binary_int = int(binary_str, base=2)
print(binary_int) # Output: 21
In the last example, the int()
function is used to convert a binary string representation of a number to an integer. By providing base=2
, we specify that the input string is in base 2 (binary), and the resulting integer will be the decimal equivalent.