In Python, the int() function is used to convert a numeric value or string to an integer. If a string is provided as a parameter, the int() function attempts to interpret the string as an integer and returns the corresponding integer value.

Function Syntax

int(x, base=10)

Parameters:

  • x: The object to convert, either a number or string.
  • base: Optional parameter specifying the base for string conversion, defaults to 10.

Returns a decimal integer. If the object cannot be interpreted as an integer, a ValueError exception is raised.

int() Function Examples

Examples converting strings and floats to integers:

# Convert string to integer
num_str = "123"
num_int = int(num_str)
print(num_int)  # Output: 123

# Convert float to integer (fractional part truncated)
num_float = 3.14
num_int = int(num_float)
print(num_int)  # Output: 3

If int() is called without any parameters, it returns 0:

# int() function without parameters
num_int = int()
print(num_int)  # Output: 0

Convert binary and hexadecimal strings to integers:

# Interpret string as binary
num_str = "0b1010"
num_int = int(num_str, 2)
print(num_int)  # Output: 10

# Interpret as hexadecimal
num_str = "0xffff"
num_int = int(num_str, 16)
print(num_int)  # Output: 65535

__int__() Method

You can add an __int__() method to objects to make them compatible with the int() function:

class MyClass:
    def __int__(self):
        return 123

obj = MyClass()
print(int(obj))  # 123