Tutorial Study Image

Python int()

The int() function helps to convert the given value into an integer number. The result integer value always is in base 10.If we use int() with a custom object, then the object __int__() function will be called. 


int(x=0, base=10)# Where x can be Number or string

int() Parameters:

Takes 2 parameters where the first parameter 'x' default value is 0. And the second parameter 'base' default value is 10, it also can be in 0 (code literal) or 2-36.

Parameter Description Required / Optional
x Number or string to be converted to integer object. Required
base  The base of the number in x Optional

int() Return Value

Input Return Value
integer object base as 10
No parameters returns 0
If base given in the given base (0, 2, 8, 10, 16)

Examples of int() method in Python

Example 1:How int() works in Python?


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

# float
print("int(123.23) is:", int(123.23))

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

Output:

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

Example 2:How int() works for decimal, octal and hexadecimal?


# binary 0b or 0B
print("For 1010, int is:", int('1010', 2))
print("For 0b1010, int is:", int('0b1010', 2))

# octal 0o or 0O
print("For 12, int is:", int('12', 8))
print("For 0o12, int is:", int('0o12', 8))

# hexadecimal
print("For A, int is:", int('A', 16))
print("For 0xA, int is:", int('0xA', 16))
 

Output:

For 1010, int is: 10
For 0b1010, int is: 10
For 12, int is: 10
For 0o12, int is: 10
For A, int is: 10
For 0xA, int is: 10

Example 3:int() for custom objects


class Person:
    age = 23

    def __index__(self):
        return self.age
    
    def __int__(self):
        return self.age
 pers
print('int(person) is:', int(person))
 

Output:

int(person) is: 23

Note:Internally, int() method calls an object's __int__() method.Both these methods should return the same value.The case is that older versions of Python uses __int__(), while newer uses __index__() method.