Python Integer

The Python integer is a non-fractional number, like 1, 2, 45, -1, -2, and -100. It’s one of the three types of numbers Python supports natively, the other being floating point numbers and complex numbers.

Max size of an integer

Integers in Python 3 can have large values. In fact, they are unbounded, meaning there is no limit to their size, for example:

>>> num = 98762345098709872345000
>>> num + 1

Of course there is a limit, since your computer does not have unlimited memory. However, for all practical purposes you don’t have to worry about it.

Integer types

Unlike Python 2 and many other languages, Python 3 has only one type of integer. This is part of Python’s aspiration to be a clean, easy to learn language. It’s one less thing we have to worry about. For more details, see PEP-0237.

Converting from and to an integer

String to integer

To convert a string to integer in Python, use the int() function:

>>> int('100')

Integer to string

To convert an integer to string in Python, use the str() function:

>>> str(200)

Float to integer

To convert a float to an integer, use the int() function:

>>> int(2.3)

Python random integer

Many use cases require a random integer. For this, you need to import the random library. Be warned that this offers pseudo randomness, which is not suitable for cryptography.

Let’s get a random number:

>>> import random
>>> random.randint(1,10)

The above instruction returns a pseudo random number from in to 10 inclusive, which means including 1 and 10. For full details of the random module, visit the Python documentation.

Is it an integer?

To check if a value is an integer, we can use the type() function. It will return int for integers. Here’s a simple example of how to use this in an if-statement:

>>> type(2)
>>> if isinstance(2, int):
...     print('An integer')
An integer

Don’t use if type(2) == int.
Using isinstance() is almost always the better, cleaner way and covers more use cases, like subclasses.