When integers (int) and floating-point numbers (float) appear together in an expression, Python automatically performs a type promotion — converting the integer to a float.
This ensures the operation is accurate and no data is lost during computation.
In other words, Python promotes the smaller data type (int) to a higher one (float) whenever both types are mixed in arithmetic operations.
<
Example: Automatic Conversion from int to float
num1 = 10 # int
num2 = 3.5 # float
result = num1 * num2
print(result) # Output: 35.0
print(type(result)) # Output:
Explanation:
Here’s what happens step-by-step:
- num1 is an integer (10).
- num2 is a floating-point number (3.5).
- During multiplication, Python converts num1 to 10.0
- automatically to match num2’s data type.
- The operation then becomes 10.0 * 3.5, resulting in 35.0.
This behavior guarantees precision and ensures that the final output remains of the most suitable type — in this case, a float.
Why Python Promotes int to float
Python’s automatic type conversion helps maintain mathematical accuracy and prevents data loss during computations involving decimals.
It’s especially useful in scenarios where:
- Calculations involve currency or measurements.
- Programs handle averages, ratios, or percentages.
- Both integers and floats are used in scientific or data analysis operations.
Real-World Example
price = 250 # int
tax_rate = 0.08 # float
final_price = price + (price * tax_rate)
print(final_price) # Output: 270.0
Explanation:
Here, Python promotes price (250 → 250.0) before calculating tax, resulting in a precise floating-point total.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut elit tellus, luctus nec ullamcorper mattis, pulvinar dapibus leo.
Leave a Reply