Python Integers: Complete Beginner Guide

Published on: July 10, 2026
Reading time: 5 minutes
números inteiros sendo mostrados

Integers are whole numbers without a fractional part. Python uses them for counters, quantities, ages, indexes, identifiers, scores, dates, loops, and countless calculations. They may be positive, negative, or zero.

This guide explains Python integers from basic literals and arithmetic to division, conversion, validation, numeric bases, large values, bitwise operations, loops, and common mistakes.

Create Integer Values

age = 28
temperature = -4
balance_change = 0

print(age)
print(type(age))

The type is int. Python infers it automatically from a whole-number literal. The official numeric types documentation describes integers, floating-point numbers, and complex numbers.

Readable Large Literals

Underscores can group digits without changing the value.

population = 8_000_000_000
file_size = 1_048_576

print(population)
print(file_size)

Use grouping that makes the domain clear. Python ignores the underscores during evaluation.

Basic Arithmetic

a = 12
b = 5

print(a + b)   # addition
print(a - b)   # subtraction
print(a * b)   # multiplication
print(a ** b)  # exponentiation

Python’s arithmetic and comparison operators are covered more broadly in the Python operators guide.

Division: /, //, and %

Regular division with / returns a floating-point result, even when the division is exact.

print(10 / 2)  # 5.0
print(7 / 2)   # 3.5

Floor division with // rounds down toward negative infinity.

print(7 // 2)    # 3
print(-7 // 2)   # -4

The remainder operator % returns what remains after floor division.

print(7 % 2)   # 1
print(15 % 4)  # 3

These operators are useful for pagination, clocks, grouping, and checking whether a number is even.

number = 18

if number % 2 == 0:
    print("Even")
else:
    print("Odd")

Use divmod()

divmod() returns the quotient and remainder together.

minutes = 137
hours, remaining_minutes = divmod(minutes, 60)

print(hours)
print(remaining_minutes)

This is equivalent to calculating minutes // 60 and minutes % 60 separately.

Order of Operations

result = 2 + 3 * 4
print(result)  # 14

result = (2 + 3) * 4
print(result)  # 20

Parentheses make intention explicit. Exponentiation happens before multiplication and division, which happen before addition and subtraction.

Compare Integers

score = 82

print(score == 82)
print(score != 100)
print(score >= 60)
print(0 <= score <= 100)

Comparison expressions return booleans. Python supports chained comparisons, which are useful for validating ranges. The Python booleans guide explains truth values and logical operators.

Convert Text to an Integer

External input usually arrives as text. Use int() to convert a valid whole-number string.

text = "42"
number = int(text)

print(number + 8)

Whitespace around a valid number is accepted:

print(int("  25  "))

Decimal text is not a valid integer literal:

# int("3.5") raises ValueError
print(int(float("3.5")))  # 3, truncates toward zero

Converting through float() discards the fractional part when passed to int(). Do this only when truncation is deliberate.

Validate Keyboard Input

while True:
    try:
        quantity = int(input("Quantity: "))
    except ValueError:
        print("Enter a whole number.")
        continue

    if quantity < 1:
        print("Quantity must be positive.")
        continue

    break

print(f"Accepted quantity: {quantity}")

The Python input() guide covers reusable validation functions, menus, defaults, and multiple values. The exception-handling guide explains ValueError and specific handlers.

Convert an Integer to Text

order_id = 582
message = "Order #" + str(order_id)
print(message)

F-strings are usually clearer:

print(f"Order #{order_id}")

Binary, Octal, and Hexadecimal Literals

Python supports several integer bases.

binary_value = 0b1010
 octal_value = 0o12
hex_value = 0xA

print(binary_value)
print(octal_value)
print(hex_value)

All three values equal decimal 10. Remove the accidental leading space before octal_value when copying this example:

binary_value = 0b1010
octal_value = 0o12
hex_value = 0xA

Convert Text from Another Base

print(int("1010", 2))   # binary to decimal
print(int("12", 8))     # octal to decimal
print(int("A", 16))     # hexadecimal to decimal

A base of zero lets Python recognize a standard prefix:

print(int("0b1010", 0))
print(int("0xFF", 0))

Format Integers in Different Bases

number = 255

print(bin(number))
print(oct(number))
print(hex(number))

print(f"{number:b}")
print(f"{number:o}")
print(f"{number:x}")
print(f"{number:X}")

The built-in functions bin(), oct(), and hex() include prefixes. Format specifications can omit them.

Python Integers Can Be Very Large

Python integers use arbitrary precision, limited mainly by available memory rather than a fixed 32-bit or 64-bit range.

large_number = 10 ** 100
print(large_number)
print(len(str(large_number)))

This is convenient for exact whole-number calculations, though very large operations still consume time and memory.

Booleans and Integers

In Python, bool is a subclass of int. True behaves numerically like 1 and False like 0.

print(True + True)    # 2
print(False + 10)     # 10
print(isinstance(True, int))

This can be useful for counting conditions, but explicit code is often clearer.

responses = [True, False, True, True]
accepted_count = sum(responses)
print(accepted_count)

Integers in range()

range() generates integer sequences commonly used in loops.

for number in range(1, 6):
    print(number)

The stop value is excluded. A step controls the interval:

for number in range(10, 0, -2):
    print(number)

The complete Python range() guide covers start, stop, step, negative values, and indexing patterns.

Integers as Indexes

colors = ["blue", "green", "orange"]

print(colors[0])
print(colors[-1])

Indexes must be integers or integer-like objects. A floating-point index raises TypeError. An index outside the valid range raises IndexError.

index = 1

if 0 <= index < len(colors):
    print(colors[index])

Useful Integer Methods

bit_length() reports how many binary bits are required for the absolute value.

number = 255
print(number.bit_length())  # 8

to_bytes() and from_bytes() convert integers to and from byte sequences.

number = 1024
encoded = number.to_bytes(2, byteorder="big")
decoded = int.from_bytes(encoded, byteorder="big")

print(encoded)
print(decoded)

These methods are common in binary file formats, networking, and cryptographic protocols.

Bitwise Operations

Bitwise operators work on the binary representation of integers.

a = 0b1100
b = 0b1010

print(bin(a & b))   # AND
print(bin(a | b))   # OR
print(bin(a ^ b))   # XOR
print(bin(a << 1))  # left shift
print(bin(a >> 1))  # right shift

They are useful for flags, permissions, masks, protocols, and low-level formats. For ordinary application conditions, boolean operators are usually easier to read.

Rounding and Integer Conversion

int() truncates toward zero. It does not round to the nearest whole number.

print(int(3.9))    # 3
print(int(-3.9))   # -3
print(round(3.9))  # 4

round() follows Python’s rounding rules and may return an integer when no number of decimal places is requested. Choose the operation that matches the requirement.

Random Integers

import random

value = random.randint(1, 6)
print(value)

randint(1, 6) includes both endpoints. Use the secrets module rather than random for passwords, security tokens, and other security-sensitive values. The random module guide explains selection, sampling, shuffling, seeds, and the security distinction.

Practical Example: Change Calculator

def calculate_change(amount_cents: int) -> dict[int, int]:
    if amount_cents < 0:
        raise ValueError("amount cannot be negative")

    denominations = [100, 50, 25, 10, 5, 1]
    result = {}
    remaining = amount_cents

    for denomination in denominations:
        count, remaining = divmod(remaining, denomination)
        result[denomination] = count

    return result


change = calculate_change(287)

for denomination, count in change.items():
    print(f"{denomination:>3} cents: {count}")

This example combines validation, lists, dictionaries, loops, integer division, remainders, functions, and formatted output.

Practical Example: Page Calculator

def total_pages(total_items: int, items_per_page: int) -> int:
    if total_items < 0:
        raise ValueError("total_items cannot be negative")
    if items_per_page <= 0:
        raise ValueError("items_per_page must be positive")

    return (total_items + items_per_page - 1) // items_per_page


print(total_pages(101, 20))  # 6

This formula performs ceiling division using integers, which is common in pagination and batching.

Common Mistakes

Expecting / to Return an Integer

result = 10 / 2
print(result)        # 5.0
print(type(result))  # float

Use // only when floor division is the intended behavior.

Confusing int() with Rounding

int(4.9) returns 4, not 5. Use an appropriate rounding policy.

Doing Arithmetic on input() Text

first = input("First: ")
second = input("Second: ")
print(first + second)  # concatenates text

Convert values before arithmetic.

Dividing by Zero

divisor = 0

if divisor == 0:
    print("Cannot divide by zero")
else:
    print(10 / divisor)

Using a Number as a Mutable Identifier

An integer ID should not be reused to mean different records. Treat identifiers as stable values and validate their source.

Assuming All Numbers Fit External Systems

Python can hold huge integers, but databases, file formats, APIs, and other languages may have fixed limits. Validate before exporting.

Frequently Asked Questions

What is an integer in Python?

It is a whole-number value represented by the int type, including negative numbers and zero.

Does Python have a maximum integer?

Python integers are limited mainly by available memory, but external systems may impose fixed ranges.

Why does division return a float?

The / operator performs true division. Use // for floor division when appropriate.

How do I convert user input to an integer?

Pass the text to int() inside a try block and validate the allowed range afterward.

What is the difference between int() and round()?

int() truncates toward zero; round() applies Python’s rounding behavior.

Can integers be used as dictionary keys?

Yes. Integers are immutable and hashable, so they can be keys in dictionaries and elements of sets.

Conclusion

Python integers support exact whole-number arithmetic, readable large literals, unlimited practical precision, several numeric bases, and operations ranging from simple counters to bit masks. Convert external text carefully, distinguish true and floor division, validate ranges, and remember that outside systems may have stricter numeric limits.

Share:

Facebook
WhatsApp
Twitter
LinkedIn

Article content

    Related articles

    Definição e uso de funções com def em Python
    Fundamentals
    Foto de perfil de Leandro Hirt da Academify

    Python Functions: Complete Beginner Guide

    Learn Python functions with def, parameters, return values, defaults, keyword arguments, scope, type hints, docstrings, flexible arguments, testing, and practical

    Ler mais

    Tempo de leitura: 5 minutos
    10/07/2026
    logo do Python com o texto input() no meio
    Fundamentals
    Foto de perfil de Leandro Hirt da Academify

    Python input(): Complete Beginner Guide

    Learn Python input() with text, numbers, validation loops, conversions, menus, passwords, multiple values, error handling, and practical beginner projects.

    Ler mais

    Tempo de leitura: 4 minutos
    10/07/2026
    Logo do Python com emoji pensativo e a palavra PRINT sobre fundo azul
    Fundamentals
    Foto de perfil de Leandro Hirt da Academify

    Python print(): Complete Beginner Guide

    Learn Python print() from basic text and variables to separators, line endings, f-strings, alignment, files, debugging, logging, and common mistakes.

    Ler mais

    Tempo de leitura: 4 minutos
    10/07/2026
    Ilustração que representa um algoritmo
    Fundamentals
    Foto de perfil de Leandro Hirt da Academify

    What Is an Algorithm in Programming?

    Learn what an algorithm is in programming with everyday examples, pseudocode, flowcharts, Python implementations, efficiency, testing, and practice tips.

    Ler mais

    Tempo de leitura: 6 minutos
    10/07/2026
    Logo do Python com expressão pensativa e o texto range(), representando a função range no Python
    Fundamentals
    Foto de perfil de Leandro Hirt da Academify

    Python range(): Complete Guide with Examples

    Learn Python range() with start, stop, step, negative values, loops, indexing patterns, performance, common mistakes, and practical beginner examples.

    Ler mais

    Tempo de leitura: 4 minutos
    10/07/2026
    texto 'operadores em Python' com os simbolos de operadores e o logo do Python à direita
    Fundamentals
    Foto de perfil de Leandro Hirt da Academify

    Python Operators: Types and Practical Examples

    Learn Python operators with arithmetic, comparison, assignment, logical, membership, identity, bitwise, set, and conditional examples, plus precedence and common mistakes.

    Ler mais

    Tempo de leitura: 5 minutos
    10/07/2026