Python Integer: Non-Fractional Numbers (With Example Code)

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 others being floating-point numbers and complex numbers.

Max size of a Python integer

Unlike many other programming languages, integers in Python 3 can have large values. 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 integer type. 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 an integer in Python, use the int() function:

>>> int('100')

Integer to string

To convert an integer to a 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 module random. 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 1 to 10 inclusive, which means including 1 and 10. For full details of the random module, visit the Python documentation.

Is it a Python integer?

We can use the type() function to check if a value is an integer. 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.

Get certified with our courses

Our premium courses offer a superior user experience with small, easy-to-digest lessons, progress tracking, quizzes to test your knowledge, and practice sessions. Each course will earn you a downloadable course certificate.

Learn more

This article is part of the free Python tutorial. You can head over to the start of the tutorial here. You can navigate this tutorial using the buttons at the top and bottom of the articles. To get an overview of all articles in the tutorial, please use the fold-out menu at the top.

If you liked this article, you might also like to read the following articles:

Leave a Comment

Python Newsletter

Before you leave, you may want to sign up for my newsletter.

Tips & Tricks
Course discounts

Googler exit intent popup

No spam & you can unsubscribe at any time.

Share to...