Sitelet https://howtodoinjava.com/python-datatypes/python-integer-ints/

Python Integer (int): Operations, Conversion and Limits

Learn the Python integer (int) type. Hex and binary literals, floor division of negatives, int() and str() conversion, the 4300-digit limit and bit tools.

Python

In Python, int is the built-in type for whole numbers, positive, negative or zero, and its values have no fixed size, so they never overflow. An integer literal is any number without a decimal point, and the int() constructor converts strings and floats to integers.

x = 5
y = -10
total = x + y            # -5
product = x * y          # -50
quotient = x / y         # -0.5, always a float
floor_q = x // 2         # 2
remainder = x % 3        # 2
power = x ** 2           # 25
big = 2 ** 100           # 1267650600228229401496703205376

The topics are integer literals in decimal, binary, octal and hexadecimal, arithmetic and its rules for negative numbers, type checks, conversions to and from strings, the 4300-digit conversion limit and bitwise operators and a few useful integer methods, with results from Python 3.14.

1. What is an Integer in Python?

A Python int has these properties.

  • It is a whole number without a decimal point. 5 is an int, while 5.0 is a float.
  • It can be positive, negative or zero.
  • Its size is limited only by memory. There is no long type in Python 3 and no overflow.
  • It can contain underscores to group digits, as in 1_000_000.
  • It is immutable, so every arithmetic operation creates a new int object.
x = 10
y = 12345678987654321
z = 12_34_56              # 123456
million = 1_000_000       # 1000000

2. Integers in Binary, Octal and Hexadecimal

Integer literals can also use base 2, 8 or 16. The prefix decides the base, and the stored value is the same int in all cases.

  • Binary literals start with 0b and use the digits 0 and 1.
  • Octal literals start with 0o (zero followed by the letter o) and use the digits 0 to 7.
  • Hexadecimal literals start with 0x and use the digits 0 to 9 and the letters A to F, in either case.
binary_int = 0b1010      # 10
octal_int = 0o22         # 18
hex_int = 0xAA           # 170

A leading zero without a prefix, such as 022, is a syntax error in Python 3, to avoid confusion with old octal literals.

3. Arithmetic Operations

Integers support the usual arithmetic operators. Python has two division operators, and the result type of each one is fixed.

3.1. Addition, Subtraction, Multiplication and Division

The / operator always returns a float, even when the division is exact. The // operator returns the floored quotient, % returns the remainder, and divmod() returns both as a tuple.

x = 22
y = 5
add = x + y              # 27
sub = x - y              # 17
mul = x * y              # 110
div = x / y              # 4.4
exact = 10 / 2           # 5.0, still a float
floor_div = x // y       # 4
mod = x % y              # 2
both = divmod(x, y)      # (4, 2)

Floor division rounds toward negative infinity, not toward zero. This differs from Java and C, where -7 / 2 gives -3. In Python, the remainder takes the sign of the divisor.

neg_floor = -7 // 2      # -4
neg_mod = -7 % 2         # 1
toward_zero = int(-7 / 2)    # -3

3.2. Increment and Decrement

Python has no ++ or — operators. We use the augmented assignments += and -=, which create a new int and bind it to the same name.

x = 10
x += 1                   # 11
x += 5                   # 16
y = 10
y -= 1                   # 9
y -= 5                   # 4
count = x                # 16

3.3. Exponent

The ** operator raises a base to a power. With a negative exponent, the result is a float, and the built-in pow(base, exp, mod) computes a modular power efficiently.

square = 10 ** 2           # 100
half = 2 ** -1             # 0.5
mod_pow = pow(3, 200, 7)   # 2, without building the full number

4. Type Checking using isinstance() and type()

The isinstance(x, int) check returns True for integers and their subclasses, while type(x) is int accepts only the exact type.

value = 42
check1 = isinstance(value, int)     # True
check2 = type(value) is int         # True
flag = isinstance(True, int)        # True, bool is a subclass of int
strict = type(True) is int          # False

Since bool is a subclass of int, True and False pass an isinstance(x, int) check. When booleans must be rejected, we add and not isinstance(x, bool).

5. Convert Integer to String

The str() function returns the decimal text of an integer. For display, f-strings add thousands separators, padding and other bases.

n = 1234567
text = str(n)                 # '1234567'
grouped = f"{n:,}"            # '1,234,567'
padded = f"{42:05d}"          # '00042'
as_bin = f"{10:#b}"           # '0b1010'
as_hex = f"{255:x}"           # 'ff'

6. Convert String to Integer

The int() constructor converts a string to an integer. It ignores surrounding whitespace and underscores between digits, and its second argument sets the base.

plain = int("10")              # 10
spaces = int(" 42 ")           # 42
from_hex = int("ff", 16)       # 255
from_bin = int("1010", 2)      # 10
auto = int("0x1A", 0)          # 26, base taken from the prefix

A string with a decimal point or other characters raises ValueError. To convert “4.5”, we call float() first.

raw = "4.5"
try:
    value = int(raw)
except ValueError as e:
    message = str(e)           # "invalid literal for int() with base 10: '4.5'"
value = int(float(raw))        # 4

Calling int() on a float truncates toward zero, so int(-3.7) is -3. The round() function rounds to the nearest even value on a tie, so round(2.5) is 2.

7. Unlimited Precision and the 4300-Digit Limit

Python integers grow as large as memory allows, so 2 ** 1000 is exact. Converting very large integers to and from strings is slow, though, so since Python 3.11 (and the security releases 3.10.7, 3.9.14, 3.8.14 and 3.7.14) int() and str() refuse values with more than 4300 decimal digits.

huge = 10 ** 5000               # arithmetic works
bits = huge.bit_length()        # 16610
digits = len(str(2 ** 1000))   # 302
>>> str(10 ** 5000)
ValueError: Exceeds the limit (4300 digits) for integer string conversion; use sys.set_int_max_str_digits() to increase the limit

Code that needs bigger values calls sys.set_int_max_str_digits() with a higher limit, or 0 to remove it. The limit protects web services from inputs that would block the CPU.

8. Bitwise Operators and Memory Size

Integers support bitwise operators, which work on the binary form of the value. They appear in flags, permissions and low-level protocols.

a, b = 12, 10              # 0b1100 and 0b1010
and_ = a & b               # 8
or_ = a | b                # 14
xor = a ^ b                # 6
shifted = 1 << 4           # 16
halved = 40 >> 2           # 10
inverted = ~5              # -6

Unlimited precision has a cost in memory. A small int object takes 28 bytes on 64-bit CPython, and larger values grow by 4 bytes per 30 bits, so sys.getsizeof(2 ** 100) returns 40. NumPy arrays store fixed-size integers when memory matters.

9. Useful int Methods

The int type has a few methods for bit work and binary data.

MethodDescriptionExample and return value
bit_length()Number of bits needed to represent the value(255).bit_length() returns 8
bit_count()Number of 1 bits (Python 3.10+)(255).bit_count() returns 8
to_bytes(length, byteorder)Encodes the value as bytes(10).to_bytes(2, “big”) returns b’\x00\n’
int.from_bytes(data, byteorder)Decodes bytes to an intint.from_bytes(b’\x00\n’, “big”) returns 10
is_integer()Always True for int (Python 3.12+), for duck typing with float(10).is_integer() returns True

10. Real-World Example: Money in Cents and Page Counts

Floats cannot store most decimal fractions precisely, so 0.1 + 0.2 is 0.30000000000000004. Shops often store prices as integer cents, which keeps sums exact, and integer division splits the result into units.

prices_cents = [1999, 450, 1]          # 19.99, 4.50 and 0.01
total_cents = sum(prices_cents)         # 2450
euros, cents = divmod(total_cents, 100)
label = f"{euros}.{cents:02d}"          # '24.50'

items, per_page = 23, 10
pages = -(-items // per_page)           # 3, ceiling division without math.ceil

The expression -(-a // b) rounds up, because floor division of a negative number rounds toward negative infinity. For decimal amounts with rounding rules, the decimal module is the other option.

11. Python int FAQs

Developers who know fixed-size integers from other languages tend to ask these.

11.1. What is the maximum value of an int in Python?

There is none. Python integers grow as needed. The value sys.maxsize (9223372036854775807 on 64-bit systems) is the largest size a list or string can have, not an integer limit.

11.2. How do we check whether a string is an integer?

The str.isdigit() method returns False for negative numbers such as “-5”. A try block around int() handles signs and spaces correctly.

11.3. Why does 7 / 2 return 3.5 and not 3?

In Python 3, / is true division and always returns a float. The // operator gives the floored integer result, 3.

12. Conclusion

The Python int stores whole numbers of any size, written in decimal, binary, octal or hexadecimal. The / operator returns a float, while // and % floor toward negative infinity. The int() constructor parses strings in any base from 2 to 36, rejects decimals and values longer than 4300 digits unless the limit is raised.

13. References

Happy Learning !!

Source Code on Github

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.