Int vs Float in Python: Key Differences and Usage Guide
int represents whole numbers without decimals, while float represents numbers with decimals (floating-point). int is exact for whole values, and float is used for approximate decimal values.Quick Comparison
Here is a quick side-by-side comparison of int and float types in Python.
| Feature | int | float |
|---|---|---|
| Type of number | Whole numbers (no decimals) | Decimal numbers (with fractions) |
| Example values | 5, -10, 0 | 3.14, -0.001, 2.0 |
| Memory size | Typically smaller | Typically larger |
| Precision | Exact for whole numbers | Approximate, can have rounding errors |
| Operations | Supports integer math | Supports floating-point math |
| Use case | Counting, indexing | Measurements, calculations with fractions |
Key Differences
int in Python stores whole numbers exactly without any decimal part. It can be positive, negative, or zero. Python integers can be very large without losing precision because Python automatically manages their size.
float stores numbers with decimal points using a fixed number of binary digits. This means floats can represent fractions but may introduce small rounding errors because they approximate decimal values in binary form.
When you perform math, int operations give exact results for whole numbers, while float operations can result in slight inaccuracies due to how decimals are stored. Also, mixing int and float in operations usually converts int to float to keep decimal precision.
Code Comparison
Here is how you use int in Python to work with whole numbers:
a = 10 b = 3 sum_int = a + b product_int = a * b print("Sum (int):", sum_int) print("Product (int):", product_int)
Float Equivalent
Here is the same example using float to work with decimal numbers:
a = 10.0 b = 3.0 sum_float = a + b product_float = a * b print("Sum (float):", sum_float) print("Product (float):", product_float)
When to Use Which
Choose int when you need exact whole numbers, such as counting items, indexing lists, or working with discrete values. Use float when you need to represent measurements, percentages, or any values that require decimals and fractions.
Remember that float can introduce small rounding errors, so avoid it for money calculations where exact precision is critical; instead, use specialized libraries for that.
Key Takeaways
int for exact whole numbers without decimals.float for numbers with decimals and fractional parts.int operations are exact; float operations may have rounding errors.int to float in mixed operations.int for counting and indexing, float for measurements and calculations.