Python Master Course V2 — 006. Numbers and Numeric Types
Module 01 · Python foundations · Lesson 006 / 200
Numbers and Numeric Types
Learn to represent numbers accurately, calculate with confidence, understand precision, format numeric output, and build a reliable invoice calculator using the right data type for the job.
Study plan: 60–90 minutes of explanation + 30–45 minutes of coding practice. Requirements: Python 3.10+ recommended; the examples use standard-library features.
In this lesson · 17 sections + self-check
- 🎬 Video Lesson — 006
- Learning Outcomes
- 1. Why Numeric Types Matter
- 2. Integers (int): Exact Whole Numbers
- 3. Floating-Point Numbers (float)
- 4. Complex Numbers (complex)
- 5. Operators and Their Exact Meanings
- 6. Numeric Conversion and Input Validation
- 7. Decimal Arithmetic for Money
- 8. The math Module and Useful Numeric Functions
- 9. Professional Mini-Project — Decimal Invoice Calculator
- 10. Common Mistakes and Debugging Guide
- 11. Guided Practice: Predict, Run, Explain
- 12. Independent Exercises
- 13. Advanced Challenge — Choose the Right Numeric Model
- 14. Knowledge Check
- 15. Key Takeaways
- Interactive self-check
🎬 Video Lesson — 006
Video coming soon. This dedicated area is reserved for the Lesson 006 video player or link.
Video URL: Not assigned yet. When the lesson video is available, replace this placeholder with an accessible video embed and an ordinary link for learners who cannot play embedded media.
Learning Outcomes
After this lesson, you should be able to:
- Distinguish
int,float,complex,bool, anddecimal.Decimaland explain their appropriate uses. - Use arithmetic operators, integer division, remainders, powers, and numeric literals correctly.
- Explain why binary floating-point cannot represent some decimal fractions exactly.
- Compare approximate floating-point values with appropriate tolerances instead of direct equality.
- Validate and convert numeric input without crashing on common errors.
- Round, format, and display numbers clearly.
- Develop and test a reusable invoice calculator with exact decimal arithmetic.
Prerequisites
Finish Lessons 001–005, especially Python expressions, variables, assignment, print(), and running a .py file. You may copy every example into lesson_006.py and run it locally.
1. Why Numeric Types Matter
In ordinary conversation, a number seems simple. In software, you must decide whether a value is a whole-number count, a measured quantity, a financial amount, or a complex value used in engineering. That decision determines how calculations behave, how much precision is available, and which errors are possible.
Example scenarios: the number of students should normally be an int; a sensor temperature may be a float; an invoice amount should normally use Decimal or a carefully designed integer-minor-unit representation; and an electrical signal can use complex.
Example 1 — Inspect different numeric objects
students = 38
temperature_c = 28.75
signal = 3 + 4j
is_paid = True
print(type(students).__name__) # int
print(type(temperature_c).__name__) # float
print(type(signal).__name__) # complex
print(type(is_paid).__name__) # bool
The type() function reports the runtime type. Boolean values are conceptually logical values, but in Python bool is also a subclass of int. This is why type checks sometimes require care, particularly when counting or validating inputs.
2. Integers (int): Exact Whole Numbers
An integer represents a whole number with no fractional component. Python’s integers have arbitrary precision in the sense that their size is not restricted to a fixed 32-bit or 64-bit integer range; practical limits are available memory and computation resources. Use integers for counters, inventory quantities, IDs that truly represent numeric values, and monetary minor units where the application’s currency rules permit.
Example 2 — Integer literals and large exact calculations
visitors = 12_500 # underscores aid readability
balance_cents = 1_250_075
giant = 10 ** 30
print(visitors) # 12500
print(balance_cents) # 1250075
print(giant + 1) # precise, even at this size
print(type(giant).__name__) # int
Separators like 12_500 do not affect the numeric value. The expression 10 ** 30 means ten to the power thirty.
Example 3 — Binary, octal, and hexadecimal notation
binary_value = 0b1010
octal_value = 0o12
hex_value = 0x0A
print(binary_value, octal_value, hex_value) # 10 10 10
print(bin(26)) # 0b11010
print(hex(26)) # 0x1a
Different notations express the same underlying integer. These forms matter when interpreting permissions, bitmasks, protocols, color channels, and low-level formats.
3. Floating-Point Numbers (float)
Python float values generally use IEEE 754 double-precision binary floating-point. They are effective for many measurements and scientific calculations, but most decimal fractions are represented approximately. That is not a Python-specific bug; it follows from storing a finite approximation using a base-two representation.
Example 4 — The classic decimal precision surprise
result = 0.1 + 0.2
print(result) # 0.30000000000000004
print(result == 0.3) # False
print(1.5 + 2.25) # 3.75
Why is the final example exact? Values like 1.5 and 2.25 have finite binary expansions, whereas decimal 0.1 and 0.2 do not. You should not infer that every floating-point result is wrong; the key is to understand approximation and acceptable tolerance.
Example 5 — Compare approximate values responsibly
import math
measured = 0.1 + 0.2
expected = 0.3
print(math.isclose(measured, expected)) # True
print(math.isclose(0.0000001, 0.0, abs_tol=1e-6)) # True
math.isclose(a, b) is a useful approximate comparison. The default relative tolerance is not always appropriate near zero, so specify a meaningful abs_tol when zero or very small magnitudes are expected. A tolerance should reflect your domain requirements—measurement error, physical units, or permitted deviation—not be chosen blindly.
Example 6 — Finite and non-finite values
import math
values = [1.5, float("inf"), float("nan")]
for value in values:
print(value, "finite?", math.isfinite(value))
print(float("nan") == float("nan")) # False
inf signifies infinity and nan means “not a number.” They can appear in numerical pipelines. Validate them before aggregation, serialization, or applying financial business rules.
4. Complex Numbers (complex)
A complex number has a real part and an imaginary part: a + bj. Python uses the suffix j, not i. Complex numbers arise in signal processing, electrical engineering, mathematics, and some scientific models.
Example 7 — Work with a complex number
z = 3 + 4j
print(z.real) # 3.0
print(z.imag) # 4.0
print(abs(z)) # 5.0 (magnitude)
print(z.conjugate()) # (3-4j)
abs(z) calculates the magnitude. Many standard math functions accept real numbers only; use cmath where complex-valued mathematics is required.
5. Operators and Their Exact Meanings
Arithmetic operators look familiar, but the result type and treatment of negative operands can be surprising.
| Operation | Meaning | Example | Result |
|---|---|---|---|
+ | Addition | 7 + 3 | 10 |
- | Subtraction | 7 - 3 | 4 |
* | Multiplication | 7 * 3 | 21 |
/ | True division | 7 / 2 | 3.5 |
// | Floor division | 7 // 2 | 3 |
% | Remainder | 7 % 2 | 1 |
** | Exponentiation | 2 ** 5 | 32 |
Example 8 — Floor division and the remainder identity
number = -17
divisor = 5
quotient = number // divisor
remainder = number % divisor
print(quotient) # -4
print(remainder) # 3
print(divisor * quotient + remainder) # -17
print(divmod(number, divisor)) # (-4, 3)
Floor division rounds toward negative infinity, not toward zero. For a positive divisor, Python’s remainder is nonnegative. The relationship a == b * (a // b) + (a % b) holds for integer operands with nonzero divisor.
Example 9 — Precedence and parentheses
print(2 + 3 * 4) # 14
print((2 + 3) * 4) # 20
print(-2 ** 2) # -4
print((-2) ** 2) # 4
print(2 ** 3 ** 2) # 512: 2 ** (3 ** 2)
When the expression communicates business logic, use parentheses even when you know the formal precedence rules. Clarity is usually more important than brevity.
6. Numeric Conversion and Input Validation
Text from input() is a string until you convert it. Unvalidated conversion can raise ValueError, and dividing by zero raises ZeroDivisionError. Correct software predicts these cases and responds with useful messages.
Example 10 — Convert deliberately
print(int("42")) # 42
print(float("3.75")) # 3.75
print(int(3.99)) # 3: truncates toward zero
print(int(-3.99)) # -3
print(float(8)) # 8.0
int("3.99") is invalid, even though int(3.99) is valid. For data supplied as a string, decide whether you require an integer or accept a decimal; do not silently coerce an unexpected value.
Example 11 — Defensive conversion
raw = input("Enter a whole-number quantity: ")
try:
quantity = int(raw)
if quantity < 0:
print("Quantity must not be negative.")
else:
print("Quantity accepted:", quantity)
except ValueError:
print("Please enter a valid whole number, such as 12.")
The try/except statement will be explored in depth later. For now, notice that it handles invalid user text without displaying an unhelpful traceback to the end user.
7. Decimal Arithmetic for Money
Use the standard-library Decimal type when predictable decimal arithmetic is required, especially for financial values. Create a Decimal from a string, not from a floating-point value that may already be approximate. Decimal is not a substitute for business rules: you must still decide how and when to round taxes, discounts, line totals, and invoices.
Example 12 — Exact decimal addition
from decimal import Decimal
a = Decimal("0.1")
b = Decimal("0.2")
total = a + b
print(total) # 0.3
print(total == Decimal("0.3")) # True
print(Decimal(0.1)) # shows float's exact stored value
Example 13 — Business rounding with quantize
from decimal import Decimal, ROUND_HALF_UP
value = Decimal("12.345")
rounded = value.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
print(rounded) # 12.35
print(round(2.5)) # 2
print(round(3.5)) # 4
Python’s built-in round() uses round-to-nearest with ties to even for exact halfway cases. Many invoicing rules instead specify a decimal rounding mode such as ROUND_HALF_UP. Your organization or jurisdiction’s accounting rules must determine which one is correct; neither should be substituted without checking.
Choosing integer minor units versus Decimal
Representing ₹25.50 as 2550 paise can provide exact addition and subtraction. But currencies can have different minor-unit definitions, and tax/percentage calculations still require a documented rounding policy. Decimal is usually easier for teaching a general invoice calculator.
8. The math Module and Useful Numeric Functions
Example 14 — Scientific helpers and numeric formatting
import math
radius = 2.5
area = math.pi * radius ** 2
print(f"Area: {area:.2f}") # Area: 19.63
print(math.sqrt(81)) # 9.0
print(math.ceil(4.2)) # 5
print(math.floor(-4.2)) # -5
print(abs(-19)) # 19
print(f"{1234567.8:,.2f}") # 1,234,567.80
Fixed decimal formatting, such as :.2f, controls the displayed representation; it does not make floating-point calculations exact. In the math module, sqrt() rejects a negative real input. Complex-valued square roots require cmath.
Performance note
Choose correctness and clear units before micro-optimizing. Integer arithmetic, float arithmetic, and decimal arithmetic have different performance profiles. Avoid converting large integer identifiers into floating-point types because that may discard exact digits.
9. Professional Mini-Project — Decimal Invoice Calculator
Business requirement: Accept a unit price, a whole-number quantity, a percentage discount, and a percentage tax. Reject invalid negative prices and quantities and percentages outside 0–100. Compute the amount before and after discount, tax on the discounted amount, and final amount. Show all displayed currency values to two decimal places.
Design policy for this instructional project: carry full decimal precision through intermediate calculations and round for display. In production, agree whether rounding occurs on each line, each tax category, or the final total and ensure the invoice components reconcile under that policy.
Complete runnable project — invoice_calculator.py
from decimal import Decimal, InvalidOperation, ROUND_HALF_UP
CENT = Decimal("0.01")
HUNDRED = Decimal("100")
def read_decimal(prompt):
"""Read a finite decimal value from the user."""
text = input(prompt).strip()
try:
value = Decimal(text)
except InvalidOperation as exc:
raise ValueError("Enter a valid decimal number.") from exc
if not value.is_finite():
raise ValueError("Infinity and NaN are not allowed.")
return value
def money(amount):
"""Return a two-decimal-place string using the chosen policy."""
rounded = amount.quantize(CENT, rounding=ROUND_HALF_UP)
return f"{rounded:,.2f}"
def calculate_invoice(unit_price, quantity, discount_pct, tax_pct):
"""Return an invoice breakdown as exact Decimal values."""
for label, value in (("Unit price", unit_price),
("Discount", discount_pct),
("Tax", tax_pct)):
if not isinstance(value, Decimal) or not value.is_finite():
raise ValueError(f"{label} must be a finite Decimal.")
if type(quantity) is not int:
raise ValueError("Quantity must be a whole-number integer.")
if unit_price < 0:
raise ValueError("Unit price cannot be negative.")
if quantity < 0:
raise ValueError("Quantity cannot be negative.")
if not (0 <= discount_pct <= HUNDRED):
raise ValueError("Discount must be between 0 and 100.")
if not (0 <= tax_pct <= HUNDRED):
raise ValueError("Tax must be between 0 and 100.")
subtotal = unit_price * quantity
discount = subtotal * discount_pct / HUNDRED
taxable_amount = subtotal - discount
tax = taxable_amount * tax_pct / HUNDRED
total = taxable_amount + tax
return {
"subtotal": subtotal,
"discount": discount,
"taxable_amount": taxable_amount,
"tax": tax,
"total": total,
}
def main():
try:
price = read_decimal("Unit price: ")
quantity = int(input("Quantity (whole number): "))
discount = read_decimal("Discount percentage: ")
tax_rate = read_decimal("Tax percentage: ")
invoice = calculate_invoice(
price, quantity, discount, tax_rate
)
print("\n--- INVOICE ---")
print(f"Subtotal: {money(invoice['subtotal'])}")
print(f"Discount: {money(invoice['discount'])}")
print(f"After discount: {money(invoice['taxable_amount'])}")
print(f"Tax: {money(invoice['tax'])}")
print(f"TOTAL: {money(invoice['total'])}")
except (ValueError, InvalidOperation) as error:
print("Input error:", error)
if __name__ == "__main__":
main()
Worked example and expected output
Try unit price = 19.95, quantity = 3, discount = 10, and tax = 5. Under the project’s carry-precision-then-display policy, the unrounded values are subtotal 59.85, discount 5.985, discounted amount 53.865, tax 2.69325, and final total 56.55825.
--- INVOICE ---
Subtotal: 59.85
Discount: 5.99
After discount: 53.87
Tax: 2.69
TOTAL: 56.56
Important: These are display-rounded components, not necessarily independently posted accounting entries. A real invoice must adopt an explicit component-rounding and reconciliation rule. The example demonstrates accurate arithmetic and a declared display policy, not jurisdiction-specific tax compliance.
Professional project test
from decimal import Decimal
case = calculate_invoice(
Decimal("20.00"), 2, Decimal("10"), Decimal("5")
)
assert case["subtotal"] == Decimal("40.00")
assert case["discount"] == Decimal("4.00")
assert case["taxable_amount"] == Decimal("36.00")
assert case["tax"] == Decimal("1.80")
assert case["total"] == Decimal("37.80")
print("Invoice test passed.")
Run this test after the function definitions in the same file, or import the functions from the module in another file. Later lessons will replace ad hoc assertions with a systematic testing suite.
Rounding contract: This model carries unrounded Decimal values through the calculation and rounds each displayed line with HALF_UP. Adding the separately rounded displayed components can differ from the displayed final total by a cent. A production invoice must specify whether components are rounded before they are totalled; this exercise uses display-only rounding.
The assertion snippet uses calculate_invoice from the project. Save it below that definition in the same local script before running the tests.
10. Common Mistakes and Debugging Guide
| Problem | Why it happens | Professional fix |
|---|---|---|
0.1 + 0.2 == 0.3 is false | Binary floating-point approximation | Use math.isclose with meaningful tolerance, or Decimal for decimal-domain quantities. |
10 / 0 | Undefined division | Validate the divisor and handle ZeroDivisionError where appropriate. |
int("4.5") | Integer parser rejects a fractional string | Clarify requirements; parse a decimal/float or reject the entry. |
-7 // 2 gives -4 | Floor division rounds down, not toward zero | Use the operator consciously and add negative-number tests. |
Decimal(0.1) looks unexpected | Float approximation was captured | Use Decimal("0.1") or a direct decimal string from input. |
round(2.5) gives 2 | Ties-to-even rounding | Use an explicitly specified rounding policy. |
| Incorrect comma/decimal formatting | Formatting and arithmetic are different steps | Calculate correctly first, then format for display. |
Unexpected nan/inf | Non-finite numeric value entered or produced | Validate with is_finite() or math.isfinite(). |
Debugging workflow: reproduce the issue with the smallest possible input; inspect values with print(repr(value), type(value)); confirm what operation and type you expected; isolate conversion and rounding stages; write an assertion for the corrected behavior; and test edge cases, especially zero, negative numbers, very large values, and invalid text.
11. Guided Practice: Predict, Run, Explain
Lab A — Operator reasoning
a = 23
b = 5
print(a / b)
print(a // b)
print(a % b)
print(divmod(a, b))
Before running: predict 4.6, 4, 3, and (4, 3); then verify the identity a == b * (a // b) + a % b.
Lab B — Compare floating-point numbers
import math
actual = sum([0.1, 0.2, 0.3])
expected = 0.6
print(actual == expected)
print(math.isclose(actual, expected, rel_tol=1e-12))
Observe the difference between exact equality and approximate equality. Explain why tolerances are not a license to ignore meaningful calculation errors.
Lab C — Decimal money representation
from decimal import Decimal
prices = [Decimal("10.10"), Decimal("0.20"), Decimal("2.70")]
print(sum(prices, Decimal("0"))) # 13.00
Add a fourth price, then change a price to a negative value. Should your real application allow refunds? Notice how data validation depends on business context rather than the data type alone.
Lab B explanation
Hint
Inspect the two Boolean results independently.
Show answer and explanation
The usual outputs are False then True. The sum has a tiny binary floating-point difference; isclose accepts it under the explicitly chosen relative tolerance. A large numerical error still fails that tolerance.
Lab C explanation
Hint
Separate the numeric representation from the business rule.
Show answer and explanation
The original sum is exactly 13.00. Adding a fourth positive price increases it by that amount. A negative Decimal is representable; an application must decide whether negative entries represent valid refunds or invalid input, and enforce that rule.
12. Independent Exercises
1. Create variables for population, average temperature, price, and an imaginary-number signal. Display their types and explain each choice.
Hint
Match exact counts, approximate measurements, decimal prices, and complex signals to types.
Show answer and explanation
Use int for a population count, float for an approximate temperature, Decimal constructed from text for the price, and complex for a signal with real and imaginary components.
from decimal import Decimal
values = (1200, 23.5, Decimal("12.50"), 2 + 3j)
for value in values:
print(type(value).__name__)2. Calculate the number of full cartons formed from 137 items when each carton holds 12. Then calculate the remaining loose items and the number of cartons required to store every item.
Hint
Division gives full cartons and a remainder.
Show answer and explanation
divmod(137, 12) gives 11 full cartons and 5 loose items. Storing every item requires 12 cartons, with the last partly filled. Distinguish a full-carton count from total storage capacity.
items = 137
capacity = 12
full_cartons, loose_items = divmod(items, capacity)
cartons_required = full_cartons + (loose_items != 0)
print(full_cartons, loose_items, cartons_required)3. Convert the hexadecimal integer 0xFF to decimal and binary. Explain your result.
Hint
Hexadecimal uses base 16.
Show answer and explanation
0xFF equals 15 times 16 plus 15, or 255. Its binary representation has eight one bits; the 0b prefix denotes binary.
value = 0xFF
print(value)
print(bin(value))4. Find -23 // 4 and -23 % 4 by reasoning, then verify in Python.
Hint
Use floor division and then the remainder identity.
Show answer and explanation
The quotient is -6 and remainder 1. Check -23 == 4 * -6 + 1; the floor is below -5.75 rather than toward zero.
print(-23 // 4, -23 % 4)5. Compare 0.1 * 3 and 0.3 with exact equality and math.isclose(). Explain any difference.
Hint
Choose a tolerance appropriate to this demonstration.
Show answer and explanation
Exact equality is False; the approximate comparison is True. The tolerance recognizes a tiny representation difference, not an arbitrary business discrepancy.
import math
actual = 0.1 * 3
print(actual == 0.3)
print(math.isclose(actual, 0.3, rel_tol=1e-12))6. Use Decimal to add 12.15, 4.80, and 0.05.
Hint
Construct all three Decimal values from strings.
Show answer and explanation
The exact sum is 17.00. Starting the sum from Decimal(“0”) keeps the accumulator in the same numeric model.
from decimal import Decimal
values = [Decimal("12.15"), Decimal("4.80"), Decimal("0.05")]
print(sum(values, Decimal("0")))7. Create a program that accepts radius and displays a circle’s area to three decimal places. Validate that radius is not negative.
Hint
Reject nonfinite values as well as negative values.
Show answer and explanation
For a radius of 3, the area display is 28.274. A full input program should catch float-conversion ValueError, then enforce finiteness and nonnegativity before this calculation.
import math
radius = 3.0
if not math.isfinite(radius) or radius < 0:
raise ValueError("Radius must be finite and nonnegative")
area = math.pi * radius ** 2
print(f"Area: {area:.3f}")8. Extend the invoice calculator to accept a fixed shipping fee, disallow negative shipping charges, and show the revised total.
Hint
State whether shipping is added before or after tax.
Show answer and explanation
For this extension, add a finite nonnegative Decimal shipping fee after the existing invoice total. The illustration changes 37.80 to 39.80. Tax treatment of shipping needs an explicit rule in a real application.
from decimal import Decimal
invoice_total = Decimal("37.80")
shipping = Decimal("2.00")
if not shipping.is_finite() or shipping < 0:
raise ValueError("Shipping must be finite and nonnegative")
print(f"Revised total: {invoice_total + shipping:.2f}")9. Implement an invoice discount rule with a maximum percentage of 25% and write tests for 0%, 25%, and 26%.
Hint
The upper boundary is inclusive.
Show answer and explanation
Accept 0 and 25; reject 26. Convert decimal input and validate that it is finite before testing 0 <= percentage <= 25. Test both boundaries and one value beyond the allowed interval.
10. Write three edge-case tests for the invoice calculator and explain why they matter.
Hint
Cover an ordinary boundary, a rejected value, and a nonfinite value.
Show answer and explanation
A zero quantity is accepted by this lesson’s contract and gives zero subtotal and total. A negative price must raise ValueError. Decimal(“NaN”) must raise ValueError for a nonfinite amount rather than reaching comparison or rounding. Test these through the actual project function; its quantity contract also rejects True and fractional quantities.
13. Advanced Challenge — Choose the Right Numeric Model
Design a price comparison tool for three vendors. Each vendor has a quoted decimal unit price, quantity, and discount. Your program must reject invalid inputs, rank vendors by final payable amount, and print a clear comparison table. Extend it with a shipping charge and explain where the rounding policy should be applied. Test with an equal-price tie, a zero quantity, and a high-precision percentage. Avoid a float-based money comparison.
Acceptance criteria: readable functions, descriptive variable names, at least five assertions, predictable formatting, and a documented rounding policy. This challenge leads toward functions, collections, and testing in later modules.
14. Knowledge Check
1. Which built-in type is best suited to an exact count of books?
Hint
Counts are whole numbers.
Show answer and explanation
Use int for an exact book count. Choose a nonnegative-count contract and validate it; being an integer alone does not prevent a negative count.
2. Why can 0.1 + 0.2 differ from 0.3 in floating-point arithmetic?
Hint
Decimal fractions and finite binary storage do not always align.
Show answer and explanation
Many decimal fractions have no exact finite binary representation. Their stored approximations make 0.1 + 0.2 == 0.3 False in the usual float calculation. Choose tolerances for approximate domains and Decimal or integer minor units for exact decimal amounts.
3. What is the value of -17 // 5?
Hint
Flooring moves toward negative infinity.
Show answer and explanation
It is -4: -17 divided by 5 is -3.4, and flooring selects -4. Truncation toward zero would give a different result. The remainder identity is -17 == 5 * (-4) + 3.
4. What does math.isclose() help with?
Hint
Approximate equality needs a domain-specific tolerance.
Show answer and explanation
math.isclose() compares values using relative and absolute tolerances. Choose tolerances from the required accuracy; near zero, a suitable absolute tolerance can matter. It does not repair an incorrect formula.
5. How should you normally construct a Decimal for money from typed decimal text?
Hint
Keep the original decimal characters.
Show answer and explanation
Construct from text, such as Decimal("12.34"). Converting a binary float can preserve its approximation rather than recover the intended original decimal value. Validate finiteness and range afterward.
6. What does round(2.5) produce, and why?
Hint
This exact halfway case uses ties to even.
Show answer and explanation
round(2.5) produces 2, while round(3.5) produces 4. Both halfway cases choose the even integer. Decimal quantization allows a chosen policy such as HALF_UP when the domain requires it.
7. Why must an invoice specify a rounding policy?
Hint
Decide both the rule and the stage where it applies.
Show answer and explanation
Specify precision, tie handling, and whether rounding happens per component, per line, or on the final total. Otherwise independent implementations may disagree by a cent even when using Decimal. Follow the stated contract consistently.
8. What happens if a user enters abc and your program executes int("abc")?
Hint
Conversion can reject malformed text.
Show answer and explanation
int("abc") raises ValueError. Catch that specific error at the input boundary and ask for a valid integer; do not replace arbitrary failures silently with zero.
15. Key Takeaways
Integers give exact whole-number arithmetic. Floats are useful for approximate measurement and scientific calculations. Complex values handle two-dimensional mathematical quantities. Decimal is useful when exact base-ten arithmetic and explicit financial rounding are required. Operators, input conversion, edge cases, formatting, and tests all contribute to numerically trustworthy software.
Professional rule: choose your number representation according to the domain, validate inputs at the boundary, document rounding and units, and test cases where errors tend to hide.
Apply what you learned
Interactive self-check
Choose an answer for each question, then check your work. You will see the correct answer and why it is correct.
This is a practice quiz. Results are saved on this browser when storage is available.
Finish the exercises and mastery checkpoint before marking this lesson complete. Completion and quiz results are stored on this browser.