The int()
function in Python is a built-in function that converts a specified value into an integer number. It can convert numeric strings or floating-point numbers to integers, and also takes an optional argument for the base when converting from a string.
Parameter Values
Parameter | Description |
---|---|
x | A number or string to convert to an integer. The value can be a float, integer, or a string that represents a numeric value. |
base | An optional integer argument representing the base to convert the integer from. The default base is 10. This parameter is only used when the |
Return Values
The int()
function can return an int
value or raise a ValueError
or TypeError
.
How to Use int()
in Python
The int()
function converts a string or a number to an integer. It can also convert a floating-point number to an integer by truncating the decimal part.
num_str = '10'
num_int = int(num_str)
print(num_int) # Output: 10
The int()
function can also convert a binary, octal, or hexadecimal string to an integer by specifying the base using the optional second argument.
binary_num = '1010'
int_num = int(binary_num, 2)
print(int_num) # Output: 10
If the string passed to int()
cannot be converted to an integer, it will raise a ValueError.
invalid_str = 'abc'
try:
int_num = int(invalid_str)
except ValueError as e:
print('Error:', e) # Output: Error: invalid literal for int() with base 10: 'abc'