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

Python int() Function

Last Updated : 10 May, 2023
Summarize
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 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
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
How to fix "ValueError: invalid literal for int() with base 10" in Python
The "ValueError: invalid literal for int() with base 10" is a common error in Python that occurs when you try to convert a string to an integer using the int() function, but the string is not in a valid format that can be interpreted as a base 10 integer. This article will explain the causes of this error and provide methods to fix it. What is "Val
3 min read
How to convert Float to Int in Python?
Converting a float value to an int is done by Type conversion, which is an explicit method of converting an operand to a specific type. However, it is to be noted that such type of conversion may tend to be a lossy one (loss of data). Converting an int value like 2 to floating-point will result in 2.0, such types of conversion are safe as there wou
6 min read
Python | pandas int to string with leading zeros
In Python, When it comes to data manipulation and data analysis, Panda is a powerful library that provides capabilities to easily encounter scenarios where the conversion of integer to string with leading zeros is needed. In this article, we will discuss How we can convert pandas int to string with leading zeros using Python? with the help of vario
4 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
4 min read
Convert String to Int in Python
In Python, converting a string to an integer is important for performing mathematical operations, processing user input and efficiently handling data. This article will explore different ways to perform this conversion, including error handling and other method to validate input string during conversion. Using int() FunctionThe simplest way to conv
3 min read
Scala short ==(x: Int): Boolean
Short, a 16-bit signed integer (equivalent to Java's short primitive type) is a subtype of scala.AnyVal. The ==(x: Int) method is utilized to return true if this value is equal to x, false otherwise. Method Definition: def ==(x: Int): Boolean Return Type: It returns true if this value is equal to x, otherwise false. Example #1: // Scala program of
1 min read
What is the meaning of invalid literal for int() with base = ' '?
ValueError is encountered when we pass an inappropriate argument type. Here, we are talking about the ValueError caused by passing an incorrect argument to the int() function. When we pass a string representation of a float or any string representation other than that of int, it gives a ValueError. Example 1 : ValueError with base 10. # ValueError
2 min read
How to Get the Shape of a Tensor as a List of int in Pytorch?
To get the shape of a tensor as a list in PyTorch, we can use two approaches. One using the size() method and another by using the shape attribute of a tensor in PyTorch. In this short article, we are going to see how to use both of the approaches. Using size() method: The size() method returns the size of the self tensor. The returned value is a s
1 min read
Convert the data type of Pandas column to int
In this article, we are going to see how to convert a Pandas column to int. Once a pandas.DataFrame is created using external data, systematically numeric columns are taken to as data type objects instead of int or float, creating numeric tasks not possible. We will pass any Python, Numpy, or Pandas datatype to vary all columns of a dataframe there
2 min read
Convert 2D float array to 2D int array in NumPy
Converting a 2D float array to a 2D integer array in NumPy is a straightforward process using the astype() method. This conversion can be useful in various data analysis and scientific computing tasks where integer data types are required or where memory efficiency is essential. In this article, we are going to have a look at 'How to convert a 2D f
8 min read
What is the fastest way to drop consecutive duplicates a List[int] column?
Handling data efficiently is a critical task in many programming and data analysis scenarios. One common problem is dealing with consecutive duplicates in lists, especially when working with columns of data in formats like CSV files or databases. This article explores the fastest ways to drop consecutive duplicates from a List[int] column, ensuring
3 min read
Wand function() function in Python
function() function is similar to evaluate function. In function() function pixel channels can be manipulated by applies a multi-argument function to pixel channels. Following are the list of FUNCTION_TYPES in Wand: 'undefined''arcsin''arctan''polynomial''sinusoid' Syntax : wand.image.function(function, arguments, channel) Parameters : ParameterInp
1 min read
Python - Call function from another function
Prerequisite: Functions in Python In Python, any written function can be called by another function. Note that this could be the most elegant way of breaking a problem into chunks of small problems. In this article, we will learn how can we call a defined function from another function with the help of multiple examples.  What is Calling a Function
5 min read
Returning a function from a function - Python
Functions in Python are first-class objects. First-class objects in a language are handled uniformly throughout. They may be stored in data structures, passed as arguments, or used in control structures. Properties of first-class functions: A function is an instance of the Object type.You can store the function in a variable.You can pass the functi
4 min read
Python math.sqrt() function | Find Square Root in Python
sqrt() function returns square root of any number. It is an inbuilt function in Python programming language. In this article, we will learn more about the Python Program to Find the Square Root. sqrt() Function We can calculate square root in Python using the sqrt() function from the math module. In this example, we are calculating the square root
3 min read
wxPython - GetField() function function in wx.StatusBar
In this article we are going to learn about GetField() function associated to the wx.GetField() class of wxPython. GetField() function Returns the wx.StatusBarPane representing the n-th field. Only one parameter is required, that is, field number in status bar. Syntax: wx.StatusBar.GetField(self, n) Parameters: Parameter Input Type Description n in
1 min read
How to write an empty function in Python - pass statement?
In C/C++ and Java, we can write empty function as following // An empty function in C/C++/Java void fun() { } In Python, if we write something like following in Python, it would produce compiler error. # Incorrect empty function in Python def fun(): Output : IndentationError: expected an indented block In Python, to write empty functions, we use pa
1 min read
Ways to sort list of dictionaries by values in Python - Using lambda function
In this article, we will cover how to sort a dictionary by value in Python. Sorting has always been a useful utility in day-to-day programming. Dictionary in Python is widely used in many applications ranging from competitive domain to developer domain(e.g. handling JSON data). Having the knowledge to sort dictionaries according to their values can
2 min read
Python Numbers | choice() function
choice() is an inbuilt function in Python programming language that returns a random item from a list, tuple, or string. Syntax: random.choice(sequence) Parameters: sequence is a mandatory parameter that can be a list, tuple, or string. Returns: The choice() returns a random item. Note:We have to import random to use choice() method. Below is the P
1 min read
Python | askopenfile() function in Tkinter
While working with GUI one may need to open files and read data from it or may require to write data in that particular file. One can achieve this with the help of open() function (python built-in) but one may not be able to select any required file unless provides a path to that particular file in code. With the help of GUI, you may not require to
2 min read
Python | Binding function in Tkinter
Tkinter is a GUI (Graphical User Interface) module that is widely used in desktop applications. It comes along with the Python, but you can also install it externally with the help of pip command. It provides a variety of Widget classes and functions with the help of which one can make our GUI more attractive and user-friendly in terms of both look
3 min read
Python pow() Function
Python pow() function returns the result of the first parameter raised to the power of the second parameter. Syntax of pow() Function in Python Syntax: pow(x, y, mod) Parameters : x : Number whose power has to be calculated.y : Value raised to compute power.mod [optional]: if provided, performs modulus of mod on the result of x**y (i.e.: x**y % mod
2 min read
Practice Tags :
three90RightbarBannerImg