Lesson 02: Numbers, Operators, Expressions & Engineering Unit Hygiene
The “Boring Stuff” Problem: Manual Unit Conversions and Formula Order Bugs
Think about the last time you solved a Thin-Walled Pressure
Vessel problem or a Pipe Head Loss calculation
by hand. You probably had pressure in bar or
psi, wall thickness in mm, diameter in
cm, and Young’s modulus in GPa—and one
forgotten factor of 1000 or one misplaced pair of
parentheses on a calculator turned a 4.2 mm deflection into
4200 mm.
In Python, we treat variables like precision instrument tags
(pressure_bar, pressure_pa) and let
expressions evaluate reliably with exact operator rules.
Python’s Data Types for Numbers
Python has three core numeric/logical types you will use every single day:
| Type | Name | Engineering Examples | How Python Recognizes It |
|---|---|---|---|
int |
Integer | num_fins = 12,
bolt_count = 8, rpm = 1800 |
No decimal point |
float |
Floating-Point | k_copper = 385.0,
E = 200e9, pi = 3.14159 |
Has . or scientific
e |
bool |
Boolean | is_turbulent = True,
cavitation_ok = False |
True or False
(capitalized!) |
The Seven
Arithmetic Operators (Do Not Guess / vs
//!)
| Operator | Operation | Expression | Evaluates To | Mechanical Engineering Use |
|---|---|---|---|---|
** |
Exponent | 2 ** 3 |
8 |
Cube of height \(h^3\), \(T^4\) radiation |
* |
Multiply | 3 * 4 |
12 |
Stress \(\times\) Area |
/ |
True Division | 7 / 2 |
3.5 |
Always returns a float (even
8 / 2 = 4.0) |
// |
Floor Division | 7 // 2 |
3 |
Whole gear teeth / whole batch packs |
% |
Remainder (Modulo) | 7 % 2 |
1 |
Leftover bolts after packing boxes |
+ |
Addition | 25 + 273.15 |
298.15 |
Celsius to Kelvin shift |
- |
Subtraction | T_s - T_inf |
float/int | Temperature difference \(\Delta T\) |
Order of Operations (Precedence): Python evaluates
expressions strictly in PEMDAS order: Parentheses
() first, then Exponents ** (note:
right-to-left!), then Multiplication/Division/Modulo (*,
/, //, %) left-to-right, then
Addition/Subtraction (+, -) left-to-right.
Golden Rule of Engineering Readability: Even when PEMDAS handles it, use parentheses around denominators like
h_f = f * (L / D) * (V**2 / (2 * g)). Nobody ever lost points for clear parentheses; thousands of engineers have made bugs by omitting them (V**2 / 2 * gevaluates as(V**2 / 2) * g—off by \(g^2 \approx 96\times\)!).
# Interactive Expression Tracing: Inspecting Types and Precedence
bolts_total = 53
bolts_per_flange = 8
flanges_complete = bolts_total // bolts_per_flange # Floor division: whole assemblies
bolts_leftover = bolts_total % bolts_per_flange # Modulo: spare bolts
exact_ratio = bolts_total / bolts_per_flange # True division: always float
print("type(bolts_total) =", type(bolts_total))
print("type(exact_ratio) =", type(exact_ratio))
print(f"Complete 8-bolt flanges: {flanges_complete}, Leftover spare bolts: {bolts_leftover}")
# Watch out for denominator traps in kinetic energy / velocity head!
V = 12.0 # m/s
g = 9.81 # m/s^2
wrong_head = V**2 / 2 * g # Evaluates (V**2 / 2) * g !!
right_head = V**2 / (2 * g) # True velocity head V^2 / (2g)
print(f"Wrong (missing parens): {wrong_head:.2f} m vs Right V^2/(2g): {right_head:.2f} m")type(bolts_total) = <class 'int'>
type(exact_ratio) = <class 'float'>
Complete 8-bolt flanges: 6, Leftover spare bolts: 5
Wrong (missing parens): 706.32 m vs Right V^2/(2g): 7.34 m
Real Multi-Course Engineering Case Studies
Let’s apply exact numeric operations to three classic problems
directly drawn from your Thermodynamics
(ME 200), Fluid Mechanics, and
Heat Transfer / Solid Mechanics courses.
Watch Out! Classic Numeric Gotchas in Python
- Floating-Point Representation
(
0.1 + 0.2 == 0.30000000000000004): Computers store decimals in binary (base-2). Tiny \(10^{-16}\) rounding residuals are normal—that’s why later in Control Flow we compare floats with a tolerance (abs(a - b) < 1e-9) instead of exact==. - Radians vs. Degrees: Python’s
math.sin(),math.cos(), andmath.tan()expect radians, NOT degrees! Always wrap angles withmath.radians(angle_deg). - Never Omit Units in Variable Names: Treat
12_000(underscores in numeric literals make large numbers readable—E = 200_000_000_000or200e9!) as base SI unless a suffix explicitly says_mm,_kpa, or_degc.
import math
# Case 1 (Solids & Pressure Vessels): Thin-Walled ASME Cylindrical Compressed Gas Tank
P_bar = 24.0 # Internal gauge pressure [bar]
P_pa = P_bar * 1e5 # 1 bar = 100,000 Pa
D_mm = 600.0 # Mean inner diameter [mm]
r_m = (D_mm / 1000.0) / 2.0 # Inner radius [m]
t_mm = 8.0 # Wall thickness [mm]
t_m = t_mm / 1000.0
sigma_y_mpa = 275.0 # Steel yield strength [MPa]
# Thin-walled check: r/t >= 10
sigma_hoop_mpa = (P_pa * r_m / t_m) / 1e6
sigma_axial_mpa = sigma_hoop_mpa / 2.0
fos_hoop = sigma_y_mpa / sigma_hoop_mpa
print("=== Thin-Walled Pressure Vessel Analysis ===")
print(f"r/t Ratio : {r_m / t_m:.1f} (Thin-walled valid if >= 10)")
print(f"Hoop Stress : {sigma_hoop_mpa:.2f} MPa")
print(f"Axial Stress : {sigma_axial_mpa:.2f} MPa")
print(f"Safety Factor : {fos_hoop:.2f}")=== Thin-Walled Pressure Vessel Analysis ===
r/t Ratio : 37.5 (Thin-walled valid if >= 10)
Hoop Stress : 90.00 MPa
Axial Stress : 45.00 MPa
Safety Factor : 3.06
# Case 2 (Heat Transfer — Stefan-Boltzmann + Conduction): Solar Absorber Plate Net Radiation
# Cross-references Renewable Energy I (Ch. 5/6) & Heat and Mass Transfer (Module 7)
sigma_sb = 5.670374419e-8 # Stefan-Boltzmann constant [W/(m^2*K^4)]
emissivity = 0.18 # Selective black-chrome coating epsilon [-]
T_plate_c = 115.0 # Absorber plate temperature [degC]
T_sky_c = 12.0 # Effective sky temperature [degC]
area_m2 = 2.0 # Collector aperture area [m^2]
T_p_k = T_plate_c + 273.15
T_s_k = T_sky_c + 273.15
# Note: (T_p^4 - T_s^4) is COMPLETELY DIFFERENT from (T_p - T_s)^4 !!
Q_rad_correct = emissivity * sigma_sb * area_m2 * (T_p_k**4 - T_s_k**4)
Q_rad_bug = emissivity * sigma_sb * area_m2 * ((T_p_k - T_s_k)**4)
print("=== Selective Solar Absorber Radiation Loss ===")
print(f"True Q_rad (T_p^4 - T_s^4) : {Q_rad_correct:7.2f} W")
print(f"Fatal Bug ((T_p - T_s)^4) : {Q_rad_bug:7.2f} W <-- Always remember 4th power BEFORE subtracting!")=== Selective Solar Absorber Radiation Loss ===
True Q_rad (T_p^4 - T_s^4) : 328.39 W
Fatal Bug ((T_p - T_s)^4) : 2.30 W <-- Always remember 4th power BEFORE subtracting!
Practice Questions (Concept Check)
- What is the exact data type and value of
10 / 2vs10 // 2vs10 % 3? - Why does
2 ** 3 ** 2equal512instead of64in Python? - What does
1_250_000represent in Python code, and why use underscores instead of commas (1,250,000)? - Why is
math.sin(30)wrong for \(\sin(30^\circ)\), and how do you fix it?
Guided
Practice Problem 1 (Worked Self-Check): Hydrostatic Inclined Gate Force
(Fluid Mechanics)
From Fluid Mechanics Module 1, a rectangular gate of width \(w = 2.5\text{ m}\) and height \(b = 1.6\text{ m}\) is submerged in water (\(\rho = 998\text{ kg/m}^3\), \(g = 9.81\text{ m/s}^2\)) inclined at \(\theta = 55^\circ\) to the horizontal. Its top edge lies at vertical depth \(h_{\text{top}} = 3.0\text{ m}\). Write Python expressions to compute:
- Vertical depth of the centroid \(h_C = h_{\text{top}} + \frac{b}{2}\sin\theta\)
- Resultant hydrostatic force \(F_R = \rho g h_C A\) in \(\text{kN}\)
- Inclined distance from surface to center of pressure \(y_P = y_C + \frac{I_{xx,c}}{y_C A}\) where \(y_C = h_C/\sin\theta\) and \(I_{xx,c} = \frac{w b^3}{12}\).
Hint: Convert 55° to Radians Before Calling math.sin()
Use theta_rad = math.radians(55.0). Every length is in
meters, so divide \(F_R\) by
1000.0 at print time for kN.
# Worked Practice Problem 1 Solution: Inclined Reservoir Gate Hydrostatics
rho = 998.0
g = 9.81
w = 2.5
b = 1.6
h_top = 3.0
theta_deg = 55.0
theta = math.radians(theta_deg)
A = w * b
h_C = h_top + 0.5 * b * math.sin(theta)
y_C = h_C / math.sin(theta)
I_xx_c = (w * (b ** 3)) / 12.0
F_R_kN = (rho * g * h_C * A) / 1000.0
y_P = y_C + I_xx_c / (y_C * A)
print(f"Centroid Depth h_C : {h_C:.3f} m (y_C = {y_C:.3f} m)")
print(f"Resultant Force F_R: {F_R_kN:.2f} kN")
print(f"Center of Pressure : y_P = {y_P:.4f} m (offset y_P - y_C = {(y_P - y_C)*1000:.2f} mm below C)")Centroid Depth h_C : 3.655 m (y_C = 4.462 m)
Resultant Force F_R: 143.15 kN
Center of Pressure : y_P = 4.5101 m (offset y_P - y_C = 47.81 mm below C)
End-of-Chapter Practice Problems (Try Yourself!)
- Combined-Cycle Net Efficiency
(
ME 300): Given an air-standard Brayton cycle efficiency \(\eta_B = 1 - r_p^{-(k-1)/k}\) with pressure ratio \(r_p = 18.0\), \(k = 1.40\), and a bottoming Rankine cycle efficiency \(\eta_R = 0.365\), compute the combined-cycle efficiency \(\eta_{CC} = \eta_B + \eta_R - \eta_B\eta_R\) and the net power output \(\dot{W}_{\text{net}}\) (MW) if fuel input is \(\dot{Q}_{\text{in}} = 750\text{ MW}\). - Helical Coil Spring Stiffness & Deflection
(
Machine Design): Using steel shear modulus \(G = 79.3\text{ GPa}\), wire diameter \(d = 10\text{ mm}\), mean coil diameter \(D = 80\text{ mm}\), and \(N_a = 12\) active coils, calculate spring rate \(k = \frac{G d^4}{8 D^3 N_a}\) in \(\text{N/mm}\) and Wahl curvature-corrected maximum shear stress \(\tau_{\max} = K_w \frac{8 F D}{\pi d^3}\) under \(F = 1200\text{ N}\), where \(C = D/d\) and \(K_w = \frac{4C - 1}{4C - 4} + \frac{0.615}{C}\). - Thermal Expansion Interference Fit
(
Solid Mechanics): A bronze bushing (\(\alpha = 18.0 \times 10^{-6}\text{ K}^{-1}\)) with room-temperature bore \(D_0 = 50.000\text{ mm}\) at \(20^\circ\text{C}\) must slide over a \(50.080\text{ mm}\) shaft. Compute the expanded bore at \(T = 135^\circ\text{C}\) using \(\Delta D = \alpha D_0 \Delta T\) and check the radial clearance.