Skip to content
Related Articles

Related Articles

int() function in Python

View Discussion
Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 05 Aug, 2022

Python int() function returns an integer from a given object or converts a number in a given base to a decimal.

Python int() Function Syntax :

Syntax: int(x, base)

  • x [optional]: string representation of integer value, defaults to 0, if no value provided.
  • base [optional]: (integer value) base of the number.

Returns: Return decimal (base-10) representation of x

Python int() Function Example:

Python3




age = "21"
print("age =", int(age))

Output:

age = 21

Example 1: Working with int() function in Python

Demonstrating usage of Python int() function on different data-types in Python.

Python3




# int() on string representation of numbers
print("int('9')) =", int('9'))
 
# int() on float values
print("int(9.9) =", int(9.9))
 
# int() on Python integer
print("int(9) =", int(9))

Output : 

int('9')) = 9
int(9.9) = 9
int(9) = 9

Example 2: Convert base using Python int()

Convert numbers from different base to decimal using Python int()

Python3




# octal to decimal using int()
print("int() on 0o12 =", int('0o12', 8))
 
# binary to decimal using int()
print("int() on 0b110 =", int('0b110', 2))
 
# hexa-decimal to decimal using int()
print("int() on 0x1A =", int('0x1A', 16))

Output : 

int() on 0o12 = 10
int() on 0b110 = 6
int() on 0x1A = 26

Python int() Exception and Errors 

TypeError : raises TypeError when any object that do not have __int__() or __index__() Python magic methods implemented.

ValueError: raises ValueError when any object cannot be converted to integer.

Example 1: Program to demonstrate TypeError when using int() function

Python3




print(int(0b101, 2))

Output : 

TypeError: int() can't convert non-string with explicit base

Example 2: Program to demonstrate ValueError when using int() function

Python3




print(int('geeks'))

Output:

ValueError: invalid literal for int() with base 10: 'geeks'

Python int() Function on custom objects

Example 1: int() with __int__() function

Python int() function can be used on any objects having implementation of __int__() function. 

Python3




class Number:
    value = 7
     
    def __int__(self):
        return self.value
 
data = Number()
print("number =", int(data))

Output:

number = 7

Example 2: int() with __index__() function

Python int() function can also be used on any objects having implementation of __index__() function.

Python3




class Number:
    value = 7
     
    def __index__(self):
        return self.value
 
data = Number()
print("number =", int(data))

Output:

number = 7

Application:

It is used in all the standard conversions. For example, conversion of binary to decimal, octal to decimal, hexadecimal to decimal.


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!