This guide explains Working with Numbers in Real Programs through a focused example and practical reasoning. No prior knowledge of this specific operation is required.
Understanding the Concept
Numbers represent quantities, measurements, prices, counts and durations. A useful program usually names each input, performs a calculation, then displays a result with units. Choose integer values for exact counts and floating-point values for approximate measurements.
When You Would Use This
A delivery quote combines a fixed booking fee with a charge for each kilometer. Keeping those numbers in variables makes the calculation easy to inspect and modify.
Step-by-Step Example
booking_fee = 8
travel_distance_km = 14.5
price_per_km = 2.4
final_price = booking_fee + travel_distance_km * price_per_km
print(f"Delivery price: {final_price:.2f}")
How the Example Works
Python multiplies distance by the rate before adding the fee. The :.2f format displays two decimal places; it does not change the stored number. The result is Delivery price: 42.80.
Example Output
Delivery price: 42.80
Important Details
For real billing, the decimal.Decimal type or integer minor units can prevent many binary floating-point rounding surprises.
Try It Yourself
Change the distance to 22 km and predict the new quote before running the script.
Common Beginner Mistakes
- Mixing units, such as meters and kilometers, without conversion.
- Using a floating-point amount as though it represented exact financial cents.
- Displaying an unlabelled number that leaves readers guessing what was calculated.
Key Takeaways
- Numbers represent quantities, measurements, prices, counts and durations.
- Python multiplies distance by the rate before adding the fee.
- Avoid this mistake: Mixing units, such as meters and kilometers, without conversion.