Latest Code Tutorials

Python Int Function Tutorial With Example | Python Built-in Functions


Python Int Function Tutorial With Example | Python Built-in Functions is today’s topic. Python int() method returns an integer object from any number or string. Python int() function in Python and Python3 converts the number in the given base to decimal. The int() function converts the specified value into an integer number.

Python Int Function Tutorial

The syntax of Python int function is following.

int(value, base)

value parameter is a number or a string that can be converted into an integer number.

A base parameter is a number representing the number format. The default value is 10.

See the following example.


data = "1921"

The output is following.


Python Int Function Tutorial

So, the int() method returns:

  • The integer object from a given number or string treats default base as 10
  • If there are no parameters, then it returns 0
  • If the base has given, then it treats the string in the given base (0, 2, 8, 10, 16).

Python int() for custom objects

Internally, the int() method calls an object’s __int__() method.

So, even if an object isn’t the number, you can convert an object into the integer object.

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

The above mentioned two methods should return the same value as an older version of Python uses an __int__(), while newer uses an __index__() method.

See the following code.


class App:
    price = 21

    def __index__(self):
        return self.price
    def __int__(self):
        return self.price

app = App()
print('int(app) is:', int(app))

The output of the above code is following.


Python int() for custom objects

Convert Float into Int

We can convert the float into an int using the following code.


amp = 19.21

The output is following.


Convert Float into Int

You could use the round function. If you use no second parameter (# of significant digits), then I think you will get the behavior you want.

Finally, Python Int Function Tutorial With Example | Python Built-in Functions is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.