0
0
PythonComparisonBeginner · 3 min read

Int vs Float in Python: Key Differences and Usage Guide

In Python, 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.

Featureintfloat
Type of numberWhole numbers (no decimals)Decimal numbers (with fractions)
Example values5, -10, 03.14, -0.001, 2.0
Memory sizeTypically smallerTypically larger
PrecisionExact for whole numbersApproximate, can have rounding errors
OperationsSupports integer mathSupports floating-point math
Use caseCounting, indexingMeasurements, 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:

python
a = 10
b = 3
sum_int = a + b
product_int = a * b
print("Sum (int):", sum_int)
print("Product (int):", product_int)
Output
Sum (int): 13 Product (int): 30
↔️

Float Equivalent

Here is the same example using float to work with decimal numbers:

python
a = 10.0
b = 3.0
sum_float = a + b
product_float = a * b
print("Sum (float):", sum_float)
print("Product (float):", product_float)
Output
Sum (float): 13.0 Product (float): 30.0
🎯

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

Use int for exact whole numbers without decimals.
Use float for numbers with decimals and fractional parts.
int operations are exact; float operations may have rounding errors.
Python automatically converts int to float in mixed operations.
Choose int for counting and indexing, float for measurements and calculations.