The Wayback Machine - https://web.archive.org/web/20240811155615/https://www.geeksforgeeks.org/python-int-function/
Open In App

Python int() Function

Last Updated : 10 May, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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

Example:

In this example, we passed a string as an argument to the int() function and printed it.

Python3




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


Output:

age = 21

Python int() Function Syntax

The syntax of the int() function in Python is as follows:

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 Examples

Let us see a few examples of int() in Python.

Python int() with different DataTypes

In this example, we passed a string, a float, and an integer value as a parameter to the int() function in Python to see how the input is affected by applying the int() function.

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

Convert base using int() in Python

In this example, we used the int() function to convert the base of a number from Binary, Octal, and Hexadecimal to a Decimal integer.

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

Exception of int() in Python

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

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

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

In this example, we are trying to convert a binary number to a decimal number using the Python int() function. But this code will raise an error as the binary number passed is not in a single quote.

Python3




print(int(0b101, 2))


Output : 

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

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

This example will generate a value error as we are passing a Python String to the int() function.

Python3




print(int('geeks'))


Output:

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

Python int() Function for Custom Objects

The int() in Python can be used on custom objects. Let us see a few examples of the same.

int() with __int__() function

In this example, we created a class called ‘Number’ and defined a value and a constructor that returns the value. Then we created an object called ‘data’ of the Number class which invokes the __init__() method. The data object stores the value that is returned by that method and then using the int() function we printed the value.

Python3




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


Output:

number = 7

int() with __index__() function

In this example, we created a class called ‘Number’ and defined a value and a function that returns the value. Then we created an object called ‘data’ of the Number class which invokes the __index__() method. The data object stores the value that is returned by that method and then using the int() function we printed the value.

Python3




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


Output:

number = 7

Application

The int() function in Python is used in all the standard conversions. For example, the conversion of binary to decimal, octal to decimal, and hexadecimal to decimal.



Previous Article
Next Article

Similar Reads

String to Int and Int to String in Python
Python defines type conversion functions to directly convert one data type to another. This article is aimed at providing the information about converting a string to int and int to string. Converting a string to an int If we want to convert a number that is represented in the string to int, we have to use the int() function. This function is used
2 min read
How to Convert Bytes to Int in Python?
A bytes object can be converted to an integer value easily using Python. Python provides us various in-built methods like from_bytes() as well as classes to carry out this interconversion. int.from_bytes() method A byte value can be interchanged to an int value by using the int.from_bytes() method. This method requires at least Python 3.2 and has t
2 min read
Python bit functions on int (bit_length, to_bytes and from_bytes)
The int type implements the numbers.Integral abstract base class. 1. int.bit_length() Returns the number of bits required to represent an integer in binary, excluding the sign and leading zeros. Code to demonstrate num = 7 print(num.bit_length()) num = -7 print(num.bit_length()) Output: 3 3 2. int.to_bytes(length, byteorder, *, signed=False) Return
1 min read
How to find the int value of a string in Python?
In Python, we can represent an integer value in the form of string. Int value of a string can be obtained by using inbuilt function in python called as int(). Here we can pass string as argument to this function which returns int value of a string. int() Syntax : int(string, base) Parameters : string : consists of 1's and 0's base : (integer value)
1 min read
How to Convert Int to Bytes in Python?
An int object can be used to represent the same value in the format of the byte. The integer represents a byte, is stored as an array with its most significant digit (MSB) stored at either the start or end of the array. Method 1: int.tobytes() An int value can be converted into bytes by using the method int.to_bytes(). The method is invoked on an i
2 min read
How to Print String and Int in the Same Line in Python
Printing both texts and integers on the same line is a common chore for programmers. Python, fortunately, has various methods for accomplishing this, making it simple to display a combination of text and numerical values in your output. In this article, we'll explore various ways to print strings and integers in the same line in Python. Print Strin
2 min read
Convert String to Int Python
In Python, strings can be converted into an integer using built-in functions like 'int()', 'eval()', 'str.isdigit()', etc. However, it's important to note that the string must represent a valid integer value for the conversion to succeed. We will look at methods to change datatype from string to int in Python. Example Input: str_num = "1001" Output
3 min read
Check If Value Is Int or Float in Python
In Python, you might want to see if a number is a whole number (integer) or a decimal (float). Python has built-in functions to make this easy. There are simple ones like type() and more advanced ones like isinstance(). In this article, we'll explore different ways to check if a value is an integer or float in Python. To Check If Value Is Int Or Fl
4 min read
Overflowerror: Convert Int Large to Float in Python
Python overflows when an arithmetic operation yields a number that cannot be represented as a floating point. This happens particularly in the case of very large numbers or complex calculations that go beyond the scope of the Python interpreter. The OverflowError is raised to indicate that the result could not be contained within those constraints.
4 min read
Fix 'Int' Object is Not Subscriptable in Python
In this article, we will study how to fix 'int' object that is not subscriptable in Python. But before that let us understand why it occurs and what it means. What is 'Int' Object Is Not Subscriptable Error?The error 'int' object is not subscriptable occurs when you attempt to use indexing or slicing on an integer, a data type that doesn’t support
5 min read
Practice Tags :
three90RightbarBannerImg