Python int()

Python int() function converts a value (like a string or float) into an integer. It is commonly used to parse user input or transform numerical data into whole numbers for calculations. Python int() also supports converting numbers from different bases (e.g., binary or hexadecimal) into base-10 integers.
Table of Contents

Understanding Python int() Function

The int() function in Python is primarily used to convert various data types into integers. You can convert strings representing whole numbers, floating-point numbers, and even numbers expressed in different bases (like binary, octal, or hexadecimal) into their integer equivalents. If you provide a floating-point number, Python int() truncates it towards zero, effectively discarding the fractional part. It is the primary way to obtain integer values.

Syntax of Python int()

integer_value = int(x, base=10)

Explanation

  • integer_value: Variable stores the integer.
  • int(): Built-in conversion function.
  • x: Value need to be converted.
  • base=10: Optional parameter, the base of the number (default is 10).

Example of Python int()

float_number = 10.7
integer_number = int(float_number)
print(integer_number)

Explanation

  • float_number = 10.7: Assigns a floating-point number.
  • integer_number = int(float_number): Converts float_number to integer.
  • print(integer_number): Displays integer.

Output

10


int() Parameters

Python int() function accepts up to two parameters. The first parameter, x, is the value you want to convert to an integer. This can be a number (integer or float) or a string. If it’s a string, it should represent a valid integer in the given base. The second parameter, base, is optional and defaults to 10. The base parameter specifies the base of the number the string x represents.

Syntax

integer_result = int(value_to_convert, optional_base)

Explanation

  • integer_result: Holds the resulting integer.
  • int(): Converts the provided value.
  • value_to_convert: Number or string to be converted.
  • optional_base: Numeric base of value_to_convert (2, 8, 10, 16, etc.).

Example

binary_string = "101101"
decimal_value = int(binary_string, 2)
print(decimal_value)

Explanation

  • binary_string = "101101": Assigns a binary string.
  • decimal_value = int(binary_string, 2): Converts from base-2 (binary) to base-10 integer.
  • print(decimal_value): Prints converted number.

Output

45


int() Return Value

The int() function returns an integer. If you provide a floating-point number, the returned value is the integer part, truncated towards zero. If you give a string, the function attempts to interpret that string as an integer. If you provide the base argument, Python int() interprets the string in that base. If successful, the integer equivalent is returned; otherwise, a ValueError is raised.

Syntax

returned_integer = int(input_value, input_base)

Explanation

  • returned_integer: Will store the integer result.
  • int(): Performs conversion.
  • input_value: String or number to convert.
  • input_base: The numeric base of input value (default is 10).

Example

string_num = "123"
integer_num = int(string_num)
print(integer_num)

Explanation

  • string_num = "123": Assigns a string.
  • integer_num = int(string_num): Converts string to integer.
  • print(integer_num): Prints integer.

Output

123


Python int() with decimal, octal, and hexadecimal

Python int() can convert string representations of numbers in decimal, octal, and hexadecimal formats to their integer equivalents. You achieve this by providing the optional base parameter. For decimal strings, you can omit the base parameter (or explicitly set it to 10). Use base=8 for octal strings (which typically start with “0o”) and base=16 for hexadecimal strings (usually prefixed with “0x”).

Syntax

integer_equivalent = int(string_representation, base)

Explanation

  • integer_equivalent: Stores the integer value.
  • int(): Conversion function.
  • string_representation: String in decimal, octal, or hexadecimal.
  • base: The base of the number: 10, 8, or 16.

Example

hex_string = "0x1A"  # Hexadecimal representation of 26
decimal_int = int(hex_string, 16)
print(decimal_int)

Explanation

  • hex_string = "0x1A": A hexadecimal string.
  • decimal_int = int(hex_string, 16): Converts from base-16 to integer.
  • print(decimal_int): Outputs the decimal value.

Output

26


Convert Base using int() in Python

You can convert from any base to decimal using int() by using base parameter. Base can be anything between 2 and 36.

Syntax

decimal_equivalent = int(number_in_any_base, base)

Explanation

  • decimal_equivalent: Variable to store converted value.
  • int(): Convert to decimal.
  • number_in_any_base: Number in any base.
  • base: Base of the given number, range is 2-36.

Example

number = "101"
base = 2
decimal_equivalent = int(number, base)
print (decimal_equivalent)

Explanation

  • number = "101": Assign the value.
  • base = 2: Specify the base of the given number.
  • decimal_equivalent = int(number, base): Convert the value to decimal.
  • print(decimal_equivalent): Display converted value.

Output

5


Exception of int() in Python (TypeError and ValueError)

While Python int() is flexible, providing invalid input leads to exceptions. A TypeError occurs if you try to convert something fundamentally not convertible to an integer, like a list or a dictionary. A ValueError is raised if the provided string doesn’t represent a valid integer in the given base. For example, attempting int("abc") or int("12", 2) (since “2” is not a valid digit in base-2) would raise a ValueError.

Syntax

try:
    integer_result = int(invalid_input)
except (TypeError, ValueError) as e:
  #Handle Exception
    pass

Explanation

  • try...except: Used to catch exceptions.
  • integer_result = int(invalid_input): Could cause a TypeError or ValueError.
  • (TypeError, ValueError) as e: Catches both TypeError and ValueError.
  • pass: Placeholder.

Example

try:
    result = int("abc")
    print (result)
except ValueError as e:
    print(e)

Explanation

  • try...except: Catches potential exceptions.
  • result = int("abc"): Attempts an invalid conversion, will fail.
  • print(result): Will not executed.
  • except ValueError as e: Handles ValueError if it occurs.
  • print(e): Prints the error message.

Output

invalid literal for int() with base 10: ‘abc’


Python int() Function for Custom Objects

You can customize how Python int() behaves with your classes. You can define either the __int__() or the __index__() special method within your class. When int() is called on an instance of your class, Python will first look for a __int__() method. If __int__() isn’t found, it then looks for __index__(). If neither is found, a TypeError is raised.

Syntax

There are two different syntaxes available.

First is:

class MyClass:
    def __int__(self):
        # Return integer representation
        pass

Explanation

  • class MyClass:: Start of class definition.
  • def __int__(self):: Defines behavior for int().
  • pass: Placeholder, replaced with actual implementation.

Second is:

class MyClass:
    def __index__(self):
        # Return integer representation
        pass

Explanation

  • class MyClass:: Start of class definition.
  • def __index__(self):: Defines behavior for int() if __int__ is missing.
  • pass: Placeholder, replaced with the conversion logic.

int() with __int__() function

Define __int__() dunder method for custom classes for int().

Example

class MyNumber:
    def __init__(self, value):
        self.value = value

    def __int__(self):
        return self.value

my_num = MyNumber(42)
integer_representation = int(my_num)
print(integer_representation)

Explanation

  • class MyNumber:: Defines a custom class.
  • def __init__(self, value):: Initializes with a value.
  • self.value = value: Stores the value.
  • def __int__(self):: Defines behavior of int().
  • return self.value: Return integer representation.
  • my_num = MyNumber(42): Creates object of the class.
  • integer_representation = int(my_num): Calls int() on the object, triggering __int__().
  • print(integer_representation): Prints the returned integer.

Output

42


int() with __index__() function

Define __index__() dunder method for custom classes for int().

Example

class MyNumber:
    def __init__(self, value):
        self.value = value
    def __index__(self):
        return self.value
my_num = MyNumber(42)
integer_representation = int(my_num)
print(integer_representation)

Explanation

  • class MyNumber: Defines custom class.
  • def __init__(self, value): Initializes with a value.
  • self.value: Store the value.
  • def __index__(self):: Custom behavior for int().
  • return self.value: Returns integer value.
  • my_num = MyNumber(42): Creates instance of the class.
  • integer_representation = int(my_num): Calls int() , uses __index__().
  • print(integer_representation): Output the result.

Output

42


Conclusion

Python int() function converts various datatypes into integers. You learned that the function takes value and optional base parameters. You also get familiar with the return value being an integer, and if the value cannot be converted to an integer value, then it raises TypeError or ValueError. You can also define __int__() or __index__() dunder methods to use the function for custom objects.


Also Read

Python isinstance()

Python issubclass()


Python Reference

Python int()