In Python, integers (int
) are positive or negative whole numbers, with no predefined size limit beyond the system’s memory limitations. This allows handling very large integers without concerns about overflow.
In Python, integers can be declared in the following ways:
integer_number = 42
negative_number = -10
Operations with Integers
Python supports basic mathematical operations with integers, such as addition, subtraction, multiplication, and division:
# Addition
sum = 10 + 5
print(sum) # Output: 15
# Subtraction
difference = 10 - 5
print(difference) # Output: 5
# Multiplication
multiplication = 10 * 5
print(multiplication) # Output: 50
# Division
division = 10 / 5
print(division) # Output: 2.0 (result is always a float in Python 3)
Integer Division and Modulus
Python also supports integer division (//
) and the modulus operator (%
):
# Integer Division
integer_division = 10 // 3
print(integer_division) # Output: 3
# Modulus
modulus = 10 % 3
print(modulus) # Output: 1 (the remainder of the division 10 / 3 is 1)
Exponentiation
Python allows calculating powers using the **
operator:
# Power
power = 2 ** 3
print(power) # 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
large_number = sys.maxsize + 1
print(large_number) # Output: 9223372036854775808 (very large integer)
Floating Point Precision
When performing a division, the result is always a float
in Python 3, even if the result is an integer.
result = 10 / 5
print(result) # Output: 2.0 (float)
Binary, Octal, and Hexadecimal Representation
Integers in Python can be represented in different numerical bases:
# Binary
binary = 0b1010 # Represents the number 10 in binary
print(binary) # 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
Type Conversion
It is possible to convert other data types to integers using functions like int()
:
text = "42"
number = int(text) # Converts the text "42" to the integer 42
print(number) # Output: 42
Useful Functions and Methods
Python provides built-in functions that are useful for working with integers:
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 ofa
byb
.
# Example usage of built-in functions
absolute_value = abs(-10)
print(absolute_value) # Output: 10