1. Numeric Computing in Python
Numerical computation is at the heart of computer programming, powering everything from web application logic and financial calculations to graphics rendering and machine learning models.
Python provides robust built-in support for numerical processing across integer (int), floating-point (float), and complex (complex) data types. In this lesson, we will explore Python's full set of arithmetic and comparison operators, master operator precedence, evaluate built-in numerical functions, and leverage Python's standard math module for advanced mathematical algorithms.
2. Complete Analysis of Python Operators
1. Arithmetic Operators
Arithmetic operators perform standard mathematical operations on numeric operands.
| Operator | Operation Name | Example Expression | Evaluated Result | Behavioral Nuance |
|---|---|---|---|---|
+ |
Addition | 15 + 4 |
19 |
Sums integers or floats. Also used for string/sequence concatenation. |
- |
Subtraction | 15 - 4 |
11 |
Subtracts right operand from left operand. Also acts as unary negation (-x). |
* |
Multiplication | 15 * 4 |
60 |
Multiplies operands. Also acts as sequence repetition ("A" * 3). |
/ |
True Division | 15 / 4 |
3.75 |
Always returns a float, even if operands divide evenly (e.g., 12 / 3 → 4.0). |
// |
Floor Division | 15 // 4 |
3 |
Divides and rounds result down toward negative infinity. |
% |
Modulus | 15 % 4 |
3 |
Returns the integer remainder of division: remainder = a - (b * (a // b)). |
** |
Exponentiation | 2 ** 4 |
16 |
Raises left operand to the power of right operand ($2^4$). Higher precedence than unary minus. |
/) always yields a float. Floor division (//) truncates to the nearest lower integer. Watch out for negative numbers: -7 // 2 evaluates to -4 (not -3), because floor division rounds down toward negative infinity on the number line.
2. Comparison (Relational) Operators
Comparison operators evaluate the relationship between two operands and always return a Boolean result (True or False).
| Operator | Meaning | Example | Result |
|---|---|---|---|
== |
Equal to | 10 == 10.0 |
True |
!= |
Not equal to | 10 != 5 |
True |
> |
Greater than | 15 > 20 |
False |
< |
Less than | 5 < 8 |
True |
>= |
Greater than or equal to | 10 >= 10 |
True |
<= |
Less than or equal to | 7 <= 3 |
False |
=), which is the assignment operator, with the double equal sign (==), which is the comparison operator. Writing if x = 10: raises a SyntaxError.
3. Logical Operators (`and`, `or`, `not`)
Logical operators combine conditional statements and evaluate based on truth values:
and: ReturnsTrueonly if both operands evaluate toTrue. (Uses short-circuiting: if the left operand isFalse, the right operand is not evaluated).or: ReturnsTrueif at least one operand evaluates toTrue. (Short-circuits if the left operand isTrue).not: Unary logical operator that inverts the truth value of its operand.
3. Code Demonstration: Arithmetic and Modulus Logic
# Converting total seconds into hours, minutes, and remaining seconds
total_seconds = 3675
hours = total_seconds // 3600
remaining_seconds = total_seconds % 3600
minutes = remaining_seconds // 60
seconds = remaining_seconds % 60
print(f"Total Seconds: {total_seconds}")
print(f"Time: {hours} Hour(s), {minutes} Minute(s), {seconds} Second(s)")
Total Seconds: 3675 Time: 1 Hour(s), 1 Minute(s), 15 Second(s)
4. Operator Precedence and Associativity Rules
When an expression contains multiple operators, Python follows strict rules of operator precedence and associativity to determine the order in which operations are evaluated.
Precedence Order Hierarchy (Highest to Lowest)
- Parentheses
()(Grouped sub-expressions evaluate first) - Exponentiation
** - Unary operators
+x,-x,~x - Multiplication
*, Division/, Floor Division//, Modulus% - Addition
+, Subtraction- - Comparison operators (
==,!=,>,<,>=,<=,is,in) - Logical
not - Logical
and - Logical
or
**), which evaluates from Right to Left.For example:
2 ** 3 ** 2 is evaluated as 2 ** (3 ** 2) → 2 ** 9 → 512 (NOT (2 ** 3) ** 2 → 64).
# Expression without explicit parentheses
result_a = 10 + 5 * 2 ** 3 / 4
# Step-by-step evaluation:
# 1. Exponentiation: 2 ** 3 = 8
# 2. Multiplication: 5 * 8 = 40
# 3. Division: 40 / 4 = 10.0
# 4. Addition: 10 + 10.0 = 20.0
# Expression with explicit grouping parentheses
result_b = ((10 + 5) * 2) ** (3 / 4)
print("Result A (Natural Precedence):", result_a)
print("Result B (Grouped Precedence):", round(result_b, 4))
Result A (Natural Precedence): 20.0 Result B (Grouped Precedence): 8.409
5. Built-in Numerical Functions
Python provides several built-in functions for numerical calculations that do not require importing external modules:
abs(x): Returns the absolute value (magnitude) of a number $x$.round(number, ndigits): Rounds a number to a specified number of decimal places. Uses banker's rounding (round-to-even) logic to minimize statistical bias.pow(base, exp, mod): Raises base to exp ($base^{exp}$). If optional 3rd argumentmodis supplied, efficiently computes $(base^{exp}) \pmod{mod}$.divmod(a, b): Returns a tuple containing the quotient and remainder simultaneously:(a // b, a % b).min(arg1, arg2, ...)/max(arg1, arg2, ...): Returns the smallest or largest value among inputs.
# divmod demonstration
quotient, remainder = divmod(29, 5)
print(f"29 / 5 -> Quotient: {quotient}, Remainder: {remainder}")
# Banker's Rounding check (rounds to nearest even integer for exact .5 cases)
print("round(2.5):", round(2.5)) # Outputs 2
print("round(3.5):", round(3.5)) # Outputs 4
# pow with modulus parameter (used in cryptography)
cipher_calc = pow(7, 3, 13) # (7^3) % 13 = 343 % 13 = 5
print("pow(7, 3, 13):", cipher_calc)
29 / 5 -> Quotient: 5, Remainder: 4 round(2.5): 2 round(3.5): 4 pow(7, 3, 13): 5
6. Deep Dive: The Python `math` Module
For advanced mathematical computation, trigonometry, logarithms, and scientific calculations, Python includes the built-in math module. To use its functions, import it at the beginning of your script using import math.
1. Essential Mathematical Constants
math.pi: Mathematical constant $\pi = 3.141592653589793...$math.e: Euler's number $e = 2.718281828459045...$math.tau: Circle constant $\tau = 2\pi = 6.283185307179586...$math.inf: Floating-point positive infinity (-math.inffor negative infinity).math.nan: Floating-point "Not a Number" (used for undefined numeric representations).
2. Rounding and Truncation Functions
| Function | Description | Example | Result |
|---|---|---|---|
math.ceil(x) |
Rounds $x$ up to the nearest integer. | math.ceil(4.1) |
5 |
math.floor(x) |
Rounds $x$ down to the nearest integer. | math.floor(4.9) |
4 |
math.trunc(x) |
Truncates decimal digits, leaving whole integer part. | math.trunc(-4.9) |
-4 |
3. Power, Exponential, and Logarithmic Functions
math.sqrt(x): Returns the square root of $x$ ($\sqrt{x}$). $x$ must be $\ge 0$.math.isqrt(n): Returns the integer square root of non-negative integer $n$ (rounded down).math.log(x, [base]): Computes logarithm of $x$. If base is omitted, calculates natural logarithm ($\ln(x) = \log_e(x)$).math.log10(x): Computes base-10 logarithm ($\log_{10}(x)$).math.log2(x): Computes base-2 logarithm ($\log_2(x)$).
4. Trigonometric and Angle Functions
Note: Trigonometric functions in the math module expect angles in radians, not degrees.
math.sin(x),math.cos(x),math.tan(x): Sine, cosine, and tangent of $x$ radians.math.radians(degrees): Converts angle from degrees to radians.math.degrees(radians): Converts angle from radians to degrees.
import math
# Calculating hypotenuse of a right-angled triangle (a^2 + b^2 = c^2)
side_a = 3.0
side_b = 4.0
hypotenuse = math.hypot(side_a, side_b)
print(f"Hypotenuse (3, 4): {hypotenuse}")
# Trigonometry conversion
angle_degrees = 45.0
angle_radians = math.radians(angle_degrees)
sin_val = math.sin(angle_radians)
print(f"sin(45 degrees): {sin_val:.4f}")
# Factorials and GCD
print("Factorial of 5 (5!):", math.factorial(5)) # 5 * 4 * 3 * 2 * 1 = 120
print("GCD of 48 and 18:", math.gcd(48, 18)) # Greatest Common Divisor = 6
Hypotenuse (3, 4): 5.0 sin(45 degrees): 0.7071 Factorial of 5 (5!): 120 GCD of 48 and 18: 6
7. Floating-Point Precision Issues and Solutions
Because computers represent floating-point numbers in base-2 (binary) fractions according to IEEE 754 standards, certain base-10 decimals cannot be represented exactly in binary.
# Surprising floating-point representation quirk
val = 0.1 + 0.2
print("0.1 + 0.2 =", val)
print("0.1 + 0.2 == 0.3 ->", val == 0.3)
0.1 + 0.2 = 0.30000000000000004 0.1 + 0.2 == 0.3 -> False
How to Handle Float Comparisons Safely
1. Use `math.isclose()` for Approximate Comparison:
import math # Safe comparison with a small tolerance threshold print(math.isclose(0.1 + 0.2, 0.3)) # Returns True
2. Use the `decimal` Module for Financial Exactness:
When computing monetary totals where floating-point inaccuracy cannot be tolerated, use Python's built-in decimal module:
from decimal import Decimal
price1 = Decimal('0.1')
price2 = Decimal('0.2')
total = price1 + price2
print(total) # Outputs exactly Decimal('0.3')
8. Frequently Asked Interview Questions with Answers
/) performs True Division and always returns a floating-point number (e.g., 10 / 2 → 5.0). The double slash (//) performs Floor Division, truncating the fractional part and rounding down to the nearest lower whole integer (e.g., 10 // 3 → 3).
**) is the only arithmetic operator in Python that exhibits Right-to-Left associativity. Therefore, 2 ** 3 ** 2 is evaluated as 2 ** (3 ** 2) → 2 ** 9 → 512.
math.floor(-3.7) rounds down to -4 (toward negative infinity), whereas math.trunc(-3.7) simply strips off decimal digits to return -3 (truncates toward zero).
0.1 and 0.2 cannot be stored with exact precision in binary, resulting in a tiny representation error (0.30000000000000004). To compare floats safely, use math.isclose().
.5) to the nearest even integer rather than always rounding up. Consequently, round(2.5) evaluates to 2, while round(3.5) evaluates to 4. This minimizes statistical bias over large datasets.
9. Homework & Practical Assignment
Task 1: Precedence Order Trace
Manually evaluate the expressions below on paper, write down your predicted output, then write a script named precedence_check.py to verify:
result1 = 10 + 3 * 4 ** 2 // 8result2 = (10 + 3) * (4 ** (2 // 8))result3 = 50 - 20 % 3 * 5 + 2
Task 2: Geometry Calculator Script
Create a script named geometry_calculator.py inside your lesson_07 folder:
- Prompt the user to input the radius ($r$) of a circle as a float.
- Calculate Area using
math.pi * (r ** 2). - Calculate Circumference using
2 * math.pi * r. - Print both calculated values rounded to 3 decimal places using
round().
Task 3: Quadratic Equation Solver
Write a script named quadratic_solver.py to solve roots of $ax^2 + bx + c = 0$ using the quadratic formula $x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}$:
- Define coefficients
a = 1,b = -5,c = 6. - Calculate discriminant $d = b^2 - 4ac$.
- Use
math.sqrt(d)to compute two distinct roots ($x_1, x_2$) and print the solution.
10. File & Workspace Directory Structure
Standard Course Directory Structure:
Ensure all exercise files are stored inside their corresponding lesson directories:
python_mastery_course/
│
├── lesson_01/
├── lesson_02/
├── lesson_03/
├── lesson_04/
├── lesson_05/
├── lesson_06/
│
└── lesson_07/
├── arithmetic_ops.py
├── precedence_demo.py
├── builtin_numeric.py
├── math_module_demo.py
├── float_precision.py
├── precedence_check.py
├── geometry_calculator.py
└── quadratic_solver.py
11. What We Will Learn Next
```
OnlineCBT