In Python, integers (int
) are positive or negative whole numbers, with no predefined size limit (only the limitations of system memory).
In Python, integers can be declared in the following ways:
numero_entero = 42
numero_negativo = -10
Operations with integers
Python supports basic mathematical operations with integers, such as addition, subtraction, multiplication, and division:
# Addition
suma = 10 + 5
print(suma) # Output: 15
# Subtraction
resta = 10 - 5
print(resta) # Output: 5
# Multiplication
multiplicacion = 10 * 5
print(multiplicacion) # Output: 50
# Division
division = 10 / 5
print(division) # Output: 2.0 (the result is always a float in Python 3)
Integer Division and Modulo
Python also supports integer division (//
) and the modulo operator (%
):
# Integer Division
division_entera = 10 // 3
print(division_entera) # Output: 3
# Modulo
modulo = 10 % 3
print(modulo) # Output: 1 (the remainder of the division 10 / 3 is 1)
Exponentiation
Python allows calculating powers using the **
operator:
# Power
potencia = 2 ** 3
print(potencia) # Output: 8 (2 raised to the power of 3)
Integer Overflow
Unlike other languages, Python automatically handles integer overflow by dynamically adjusting the size of the internal representation.
import sys
numero_grande = sys.maxsize + 1
print(numero_grande) # Output: 9223372036854775808 (very large integer)
This allows handling very large integers without worrying about capacity overflow.
Floating Point Operations
When performing a division, the result is always a float
in Python 3, even if the result is an integer.
resultado = 10 / 5
print(resultado) # Output: 2.0 (float)
Binary, Octal, and Hexadecimal Representation
Integers in Python can be represented in different numeric bases:
# Binary
binario = 0b1010 # Represents the number 10 in binary
print(binario) # Output: 10
# Octal
octal = 0o52 # Represents the number 42 in octal
print(octal) # Output: 42
# Hexadecimal
hexadecimal = 0x2A # Represents the number 42 in hexadecimal
print(hexadecimal) # Output: 42
Conversion Between Types
It is possible to convert other data types to integers using functions like int()
:
texto = "42"
numero = int(texto) # Converts the text "42" to an integer 42
print(numero) # Output: 42
Useful Functions and Methods
Python offers useful built-in functions for working with integers:
Function | Description |
---|---|
abs() | Returns the absolute value of an integer. |
pow(base, exponent) | Calculates the power of a number. |
divmod(a, b) | Returns the quotient and remainder of the division of a by b . |
# Example of using built-in functions
valor_absoluto = abs(-10)
print(valor_absoluto) # Output: 10