Integers
Count users in a database. Calculate pixels on a screen. Track inventory quantities. Process financial transactions. Loop exactly 100 times. Index into the 42nd element of a list.
Every one of these tasks requires whole numbers—integers. No fractions, no decimals, just precise counting and calculation. Integers are Python's workhorse numeric type, appearing in nearly every program you write.
What is an Integer?
Integers (int type) represent whole numbers—positive, negative, or zero:
| Creating Integers | |
|---|---|
- Positive integers—the most common case
- Negative integers work identically
- Underscores improve readability for large numbers (Python 3.6+)—
1_000_000is the same as1000000
Unlike many programming languages where integers have size limits (32-bit, 64-bit), Python integers can be arbitrarily large—limited only by available memory.
Why Integers Matter
Integers solve fundamental programming problems:
- Counting: Users, iterations, items in a collection
- Indexing: Accessing elements in sequences (lists, strings)
- File I/O: Byte offsets, line numbers, file sizes
- Game development: Scores, health points, coordinates
- Web applications: Pagination (page 5 of 100), user IDs
- Data processing: Row counts, batch sizes
Every time you use range(), index a list, or count occurrences, you're working with integers. They're the foundation of computational thinking—the discrete, step-by-step logic that computers excel at.
Arithmetic Operations
Calculate total price from quantity and unit cost. Determine grid dimensions. Compute elapsed time from timestamps. Scale image coordinates. Integers power these calculations.
Basic Operators
| Basic Arithmetic | |
|---|---|
- Addition:
13—combining quantities - Subtraction:
7—finding differences, remainders - Multiplication:
30—scaling values, calculating areas - Exponentiation:
1000(10³)—growth rates, compound calculations
Division: Three Types for Different Needs
Division is where integers reveal their nuances. Python provides three division operators because different problems require different behaviors:
- True division:
3.4—always returns a float, even if the result is a whole number - Floor division:
3—rounds down to the nearest integer (useful for pagination, chunking) - Modulo:
2—returns the remainder after division (essential for cycling, even/odd checks)
Why three operators? Different problems need different behaviors:
| Operator | Name | When to Use | Example Use Case |
|---|---|---|---|
/ |
True division | Need decimal precision | Calculating averages, percentages |
// |
Floor division | Need integer result, round down | Pagination (items per page), splitting into chunks |
% |
Modulo | Need remainder | Checking even/odd, cycling through lists, time calculations |
True Division Always Returns a Float
Even if the division is "clean," / returns a float:
If you need an integer result, use // or wrap in int().
Floor Division with Negative Numbers
Floor division always rounds toward negative infinity—not toward zero. This catches programmers familiar with other languages:
| Floor Division with Negatives | |
|---|---|
- Returns
3—rounds down from 3.4 as expected - Returns
-4—rounds down from -3.4 (toward negative infinity, not toward zero!) - Returns
-4—same behavior with negative divisor
This is mathematically consistent but surprises those expecting truncation toward zero.
The Modulo Operator in Real Use
Check if a number is even or odd. Cycle through array indices. Convert 24-hour to 12-hour time. Implement round-robin task assignment. Modulo powers all these patterns:
- Even/odd check—if statement tests if remainder is 0 when divided by 2
- Returns
2—converts 14:00 (2 PM) to 12-hour format - Divisibility test—remainder of 0 means evenly divisible
- For loop with range—common pattern for iteration
- Cycles through colors:
i % 3wraps indices 0,1,2,0,1,2... regardless of how largeigets
Operator Precedence
Calculate a discount with tax. Compute compound interest. Convert units with multiple steps. Complex formulas fail when operators execute in the wrong order. Understanding precedence prevents subtle bugs in mathematical expressions:
| Order of Operations | |
|---|---|
- Returns
14, not 20—multiplication happens before addition - Returns
20—parentheses override precedence - Returns
512—exponentiation is right-to-left: 3² = 9, then 2⁹ = 512 - Returns
5—subtraction is left-to-right: (10 - 3) - 2 = 7 - 2 = 5
| Priority | Operators | Description |
|---|---|---|
| 1 (highest) | ** |
Exponentiation |
| 2 | +x, -x |
Unary plus/minus |
| 3 | *, /, //, % |
Multiplication, division, modulo |
| 4 (lowest) | +, - |
Addition, subtraction |
When in Doubt, Use Parentheses
Even if you know the precedence rules, parentheses make your intent clear:
Useful Integer Functions
Find the largest score in a game. Calculate total sales from a list. Get the distance between two points regardless of direction. These common operations appear in nearly every program—Python provides built-in functions so you don't reinvent them:
- Returns
42—abs()converts negative to positive (useful for distances, differences) - Returns
1024—pow(x, y)is equivalent tox ** y - Returns
24—three-argument form:(2¹⁰) % 100(efficient for cryptography, large numbers) - Returns
1—finds minimum value (works with any number of arguments or an iterable) - Returns
15—adds all values in a list - Returns both quotient (3) and remainder (2) in one operation—more efficient than using
//and%separately
Number Systems
Parse network packets. Set file permissions on Unix. Define colors for web design. Work with memory addresses. Process bit flags. Different number bases aren't academic—they're practical tools for systems programming, web development, and data processing.
Why Number Bases Matter
- Binary (base 2): Bit manipulation, flags, permissions, low-level protocols
- Hexadecimal (base 16): Colors (
#FF5733), memory addresses, MAC addresses, hashing - Octal (base 8): Unix file permissions (
chmod 755)
Python lets you write integers in any of these bases:
| Different Number Bases | |
|---|---|
- Base 10 (decimal)—the default, what we use daily
- Base 2 (binary)—prefix
0b—useful for bit operations - Base 8 (octal)—prefix
0o—used in Unix permissions - Base 16 (hexadecimal)—prefix
0x—common in web colors, memory addresses - Returns
True—all represent 255, just in different notations
Converting Between Bases
| Base Conversion | |
|---|---|
- Returns
'0b11111111'—binary string representation - Returns
'0o377'—octal string representation - Returns
'0xff'—hexadecimal string representation - Parse binary string to integer by specifying base 2 as second argument
- Hexadecimal parsing is case-insensitive—
'FF'and'ff'both work
Real-World Number Base Examples
Web development—RGB colors:
# RGB color as hex
red = 0xFF
green = 0x57
blue = 0x33
print(f"#{red:02X}{green:02X}{blue:02X}") # #FF5733
Systems programming—Unix permissions:
Python's Unlimited Integer Size
Calculate factorial of 100. Process credit card numbers. Work with cryptographic keys. Handle astronomical calculations. Generate large prime numbers. In other languages, these tasks hit integer overflow—values wrap around or crash. Python just works:
| Arbitrarily Large Integers | |
|---|---|
- A googol (10¹⁰⁰)—100 digits long! Python handles this without overflow
- Returns a 158-digit number—no special "big integer" library needed
No Integer Overflow
Languages like C or Java use fixed-size integers (32-bit, 64-bit) that overflow when values get too large. Python automatically switches to arbitrary-precision arithmetic—you'll never see integer overflow, just potentially slower calculations with very large numbers.
Converting To and From Integers
Parse user input from a form. Read numeric data from CSV files. Round measurements down to whole units. Display counts in messages. Data arrives in various types—strings from files, floats from calculations, booleans from logic. Converting between types is constant in real programs:
- Parse string to integer—essential for processing user input, file data
- Returns
3(not 4!)—int()truncates toward zero, doesn't round (see floats for precision) - Returns
1—booleans convert to 0 and 1 (useful in calculations) - F-strings handle conversion automatically—cleaner than
str(count)concatenation - Returns
True—isinstance()checks type (note:42.0is float, not int)
int() Truncates, Not Rounds
int() always truncates toward zero—different from round() or floor division:
Practice Problems
Practice Problem 1: Division Types
What's the difference between 17 / 5, 17 // 5, and 17 % 5?
Practice Problem 2: Modulo for Even/Odd
Write code to determine if a number stored in variable n is even or odd using the modulo operator.
Practice Problem 3: Number Bases
What decimal number do these represent: 0b1010, 0o12, 0xA?
Practice Problem 4: Floor Division Trap
What does print(-17 // 5) output, and why might it be surprising?
Answer
It outputs -4, not -3.
print(-17 / 5) # -3.4
print(-17 // 5) # -4 (rounds DOWN toward negative infinity)
print(int(-17 / 5)) # -3 (truncates toward zero)
Floor division (//) always rounds toward negative infinity, so -3.4 rounds down to -4. This differs from truncation toward zero, which would give -3.
Key Takeaways
| Concept | What to Remember |
|---|---|
| Division types | / (float), // (floor), % (modulo) |
| True division | Always returns a float, even for 10 / 2 |
| Floor division | Rounds toward negative infinity, not zero |
| Modulo | Great for even/odd, cycling, divisibility |
| Precedence | ** → * / // % → + - (use parentheses!) |
| Number bases | 0b (binary), 0o (octal), 0x (hex) |
| No overflow | Python integers can be arbitrarily large |
| int() truncates | Toward zero, not rounding |
Further Reading
- Python Integer Documentation - Official reference for integer operations
- PEP 237 – Unifying Long Integers and Integers - How Python removed integer overflow
- Bitwise Operations - Advanced integer operations for low-level programming
- Python's Data Model - Deep dive into how integers work internally
- Computational Thinking - Problem-solving patterns using discrete mathematics
- What is Computer Science? - Understanding how computers process discrete values
Integers are the foundation of computational logic. From counting loop iterations to indexing arrays, from checking divisibility to converting between number systems, integers power the discrete mathematics that computers excel at.
Python's integer implementation removes the complexity found in other languages—no overflow errors, no separate "long" types, automatic precision scaling. This lets you focus on solving problems rather than managing numeric representation.
Master integers, and you master the building blocks of algorithmic thinking.