Python Integers
What Are Integers?
An integer (int) is a whole number, positive or negative, without a decimal point. In Python, integers have unlimited precision, meaning they can be as large or as small as your computer's memory allows.
Creating Integers
You can create integers by writing numbers without a decimal point, or by using the int()
constructor:
x = 42
negative = -7
zero = 0
from_string = int("123")
from_float = int(3.99) # Truncates to 3
- You can also use binary (
0b1010
), octal (0o12
), or hexadecimal (0xA
) literals.
Integer Operations
Integers support all standard arithmetic operations:
a = 10
b = 3
print(a + b) # 13 (addition)
print(a - b) # 7 (subtraction)
print(a * b) # 30 (multiplication)
print(a / b) # 3.333... (division, returns float)
print(a // b) # 3 (floor division)
print(a % b) # 1 (modulo)
print(a ** b) # 1000 (exponentiation)
Bitwise Operations
Integers support bitwise operations:
x = 5 # 0b0101
y = 3 # 0b0011
print(x | y) # 7 (bitwise OR)
print(x & y) # 1 (bitwise AND)
print(x ^ y) # 6 (bitwise XOR)
print(~x) # -6 (bitwise NOT)
print(x << 1) # 10 (left shift)
print(x >> 1) # 2 (right shift)
Integer Methods
Python's int type includes several useful methods:
n = 37
print(n.bit_length()) # Number of bits needed to represent n (6 for 37)
print(n.bit_count()) # Number of 1s in the binary representation (3 for 37)
print(n.to_bytes(2, 'big')) # b'\x00%' (2 bytes, big-endian)
print(int.from_bytes(b'\x00%', 'big')) # 37
print(n.as_integer_ratio()) # (37, 1)
print(n.is_integer()) # True (for compatibility with float)
Converting Other Types to int
You can convert floats, strings, and other numeric types to int using int()
:
print(int(3.7)) # 3 (truncates towards zero)
print(int("42")) # 42
Booleans as Integers
In Python, True
and False
are subtypes of int, with values 1 and 0 respectively:
print(True + 2) # 3
print(False * 10) # 0
Summary
- Integers are whole numbers with unlimited precision.
- Support arithmetic and bitwise operations.
- Have useful methods for binary and byte operations.
- Booleans are a subtype of int.
- Use
int()
to convert other types to integers.