Skip to content

Python int() Function

How to use Python's int() function to convert numbers, strings, and custom objects to integers, including handling different bases like binary, hex, and octal.

The int() function converts a number or a string to its equivalent integer.

Syntax

int(value, base)

int() Parameters

Python int() function parameters:

Parameter Condition Description
value Optional A number or a string to be converted into an integer. Default is 0.
base Optional The number format of specified value. Default is 10. Valid values are 0, 2-36.

int() Return Value

Python int() function returns:

  • integer portion of the number for a single argument value (any number)
  • 0 for no arguments
  • integer representation of a number with a given base (0, 2, 8, 10, 16)

Examples

Example 1: int() function with no argument

Default values for value and base arguments are 0 and 0: so int() function returns 0.

print(int())

output

0

Example 2: int() function with value argument

For example, let's return the integer equivalent of an integer number, a float number and a string value.

print("int(123) is:", int(123))

print("int(123.45) is:", int(123.45))

print("int('123') is:", int("123"))

output

int(123) is: 123
int(123.23) is: 123
int('123') is: 123

Example 3: int() function with value and base arguments

print("For 0b101, int is:", int("0b101", 2))

print("For 0o16, int is:", int("0o16", 8))

print("For 0xA, int is:", int("0xA", 16))

output

For 0b101, int is: 5
For 0o16, int is: 14
For 0xA, int is: 10

Example 4: int() function for custom objects

Even if an object is not a number, you can still convert it to an integer object.

You can do this easily by overriding __index__() and __int__() methods of the class to return a number.

For example, the Person class is not of the integer type. But we can still return the age variable (which is an integer) using the int() method.

class Person:
    age = 25

    def __index__(self):
        return self.age


person = Person()

print("int(person) is:", int(person))

output

int(person) is: 25
Navigation