Skip to main content

Python int() Function

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

note
  • A value can be a number or a string, except complex numbers.
  • You can also specify the base (number formats like binary, hex, octal etc.) of the given value.

Syntax

int(value, base)

int() Parameters

Python int() function parameters:

ParameterConditionDescription
valueOptionalA number or a string to be converted into an integer. Default is 0.
baseOptionalThe 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.

# int() with an integer value
print("int(123) is:", int(123))

# int() with a floating point value
print("int(123.45) is:", int(123.45))

# int() with a numeric-string value
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

# converting a string (that is in binary format) to integer
print("For 0b101, int is:", int("0b101", 2))

# converting a string (that is in octal format) to integer
print("For 0o16, int is:", int("0o16", 8))

# converting a string (that is in hexadecimal format) to integer
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.

note
  • The two methods are identical.
  • The newer version of Python uses the __index__() method.

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

# def __int__(self):
# return self.age

person = Person()

# int() method with a non integer object person
print("int(person) is:", int(person))

output

int(person) is: 25