Python int()

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

Example

# converting a floating-point number to its equivalent integer

result = int(9.9)
print('int(9.9):', result)    # int(9.9): 9

int() Syntax

The syntax of the int() method is:

int(value, base [optional])

int() Parameters

int() method takes two parameters:

  • value - any numeric-string, bytes-like object or a number
  • base [optional] - the number system that the value is currently in

int() Return Value

The int() method 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)

Example 1: Python int() with a Single Argument

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

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

# 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

In the above example, we have returned the integer equivalent of an integer number, a float number and a string value.


Example 2: int() with Two 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 3: int() for custom objects

Even if an object isn't a number, we can still convert it to an integer object.

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

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

class Person:
    age = 23

    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: 23

In the above example, the class Person is not of the integer type.

But we can still return the age variable (which is an integer) using the int() method.


Also Read:

Did you find this article helpful?

Your builder path starts here. Builders don't just know how to code, they create solutions that matter.

Escape tutorial hell and ship real projects.

Try Programiz PRO
  • Real-World Projects
  • On-Demand Learning
  • AI Mentor
  • Builder Community