Programming Fundamentals with PythonIntroductionMechanical engineers increasingly use computation to evaluate designs, process experimental data, automate repetitive calculations, and communicate technical results. Python is particularly suitable for these tasks because its syntax is readable, its numerical ecosystem is extensive, and programs can be developed incrementally. A useful engineering program is not merely a sequence of arithmetic operations. It must represent physical quantities clearly, preserve units, validate inputs, express assumptions, and produce results that can be checked. This chapter develops the Python concepts required to write such programs: variables, data types, operators, expressions, input and output, selection, iteration, functions, scope, modules, and standard libraries. Python does not automatically understand whether a number represents metres, seconds, or pascals. The programmer is responsible for unit consistency. A program may execute successfully while producing a physically meaningless answer if incompatible units are combined. Learning ObjectivesBy the end of this chapter, you should be able to: - Define variables using appropriate Python data types.
- Construct arithmetic, comparison, and logical expressions.
- Develop clear input and output interactions.
- Use conditionals and loops to model engineering decisions and repeated calculations.
- Design functions with appropriate parameters, return values, and scope.
- Import and use modules from the Python standard library.
- Write unit-consistent mechanical engineering calculations.
- Identify common programming errors and apply professional coding practices.
1. Python Programs and Computational ThinkingA program is an ordered set of instructions that transforms inputs into outputs. Engineering problem solving can be expressed as: physical model → algorithm → implementation → verification → interpretation The physical model supplies relationships such as force, mass, acceleration, stress, or power. The algorithm specifies the calculation sequence. Python implements that algorithm. Verification checks the code and numerical result, while interpretation determines whether the answer is physically reasonable. For example, the normal stress in a uniform tensile member is: σ = F/A where σ is normal stress in pascals (Pa), F is axial force in newtons (N), and A is cross-sectional area in square metres (m²). The relationship assumes a uniform load distribution and an area perpendicular to the applied force. If force is entered in kilonewtons and area in square millimetres, conversion is required before using SI units. A Python implementation might be: force_kN = 12.0
area_mm2 = 600.0
force_N = force_kN * 1000
area_m2 = area_mm2 * 1e-6
stress_Pa = force_N / area_m2
stress_MPa = stress_Pa / 1e6
print(f"Stress = {stress_MPa:.2f} MPa")The result is 20.00 MPa. The explicit conversions make the unit assumptions visible and reduce the likelihood of a factor-of-one-million error. 2. Variables, Names, and Data TypesA variable is a name bound to a value. Python determines the data type at runtime, so explicit type declarations are usually unnecessary. mass = 18.5 # float
number_of_parts = 12 # int
material = "aluminium" # str
is_safe = True # bool The principal built-in types used in engineering programs are: | Type | Meaning | Example |
|---|
int | whole number | 25 | float | real-valued approximation | 3.14159 | bool | logical value | True | str | character sequence | "steel" | list | ordered, mutable collection | [10, 20, 30] | tuple | ordered, immutable collection | (0.1, 0.2) |
Variable names should describe physical meaning. Names such as diameter_m, temperature_C, and force_N communicate both quantity and unit. Python is case-sensitive: force_N and force_n are different names. Assignment uses the equals sign: velocity = 4.0
velocity = velocity + 2.0 The second statement evaluates the right-hand side and then stores the result in velocity. It does not assert a mathematical equality in the usual algebraic sense. Multiple assignment can be useful: length_m, width_m = 0.80, 0.25 Constants are commonly written with uppercase names by convention: GRAVITY_M_S2 = 9.80665 Python permits dynamic reassignment, but changing a variable from one conceptual type to another can reduce clarity and cause errors. Prefer one stable meaning for each variable. 3. Operators and ExpressionsAn expression combines values, variables, and operators to produce a result. | Operator | Meaning | Example |
|---|
+ | addition | a + b | - | subtraction | a - b | * | multiplication | a * b | / | true division | a / b | // | floor division | 7 // 2 gives 3 | % | remainder | 7 % 2 gives 1 | ** | exponentiation | r ** 2 |
Parentheses should be used when they improve readability. Python follows conventional precedence: exponentiation before multiplication and division, and multiplication and division before addition and subtraction. For example, a + b c means a + (b c). Comparison operators produce Boolean values: ==, !=, <, <=, >, and >=. Logical operators combine conditions: and, or, and not. Floating-point values are approximations. Therefore, direct equality comparisons can be unsafe: abs(calculated - expected) < 1e-9 The appropriate tolerance depends on the scale and required accuracy of the engineering problem. 4. Input, Output, and ValidationThe print() function displays information. Formatted strings, called f-strings, are effective for engineering reports: power_W = 1532.678
print(f"Power = {power_W:.1f} W")The format specification .1f displays one digit after the decimal point. The input() function always returns a string. Conversion is therefore necessary: mass_kg = float(input("Enter mass in kg: "))
count = int(input("Enter number of components: "))Input should be validated before calculation. A simple validation loop is: while True:
diameter_mm = float(input("Enter diameter in mm: "))
if diameter_mm > 0:
break
print("Diameter must be positive.")For larger programs, invalid text should also be handled with try and except: try:
load_N = float(input("Enter load in N: "))
except ValueError:
print("The load must be numeric.")A robust engineering interface states units, acceptable ranges, and assumptions explicitly. 5. Conditional ExecutionA conditional selects actions according to a Boolean condition. stress_MPa = 82.0
yield_strength_MPa = 250.0
if stress_MPa >= yield_strength_MPa:
status = "Yield criterion exceeded"
elif stress_MPa >= 0.8 * yield_strength_MPa:
status = "Close to yield strength"
else:
status = "Below screening limit"
print(status)The order of conditions matters. Once one branch is true, subsequent branches are skipped. Conditions should represent engineering criteria precisely. For example, a factor of safety is commonly defined as: n = Sallow / σworking where n is the factor of safety, S_allow is the allowable or limiting stress in Pa, and σ_working is the calculated working stress in Pa. The formula applies only when the selected allowable stress is appropriate for the material, loading mode, temperature, life, and design code. It should not be treated as a complete failure theory. allowable_MPa = 160.0
working_MPa = 82.0
factor_of_safety = allowable_MPa / working_MPa
if factor_of_safety >= 2.0:
print("Meets the screening requirement")
else:
print("Requires review")6. Repetition with LoopsLoops automate repeated operations. A for loop is appropriate when iterating over a known collection or sequence: loads_N = [1000, 1500, 2000]
for load in loads_N:
print(f"Load = {load} N")range(start, stop, step) generates integer values, including start but excluding stop:
for trial in range(1, 6):
print(trial)A while loop repeats while a condition remains true. It is suitable for input validation or iterative calculations, but the condition must eventually become false. An engineering example calculates the total mass of components: masses_kg = [2.4, 1.8, 3.1, 0.9]
total_mass = 0.0
for mass in masses_kg:
total_mass += mass
print(f"Total mass = {total_mass:.2f} kg")The break statement exits a loop, while continue skips to the next iteration. These statements can be useful, but excessive use may obscure the algorithm. A loop can approximate a total quantity. For a constant-force displacement process, work is: W = F∆x where W is work in joules, F is constant force in newtons, and ∆x is displacement in metres. For a variable force, numerical summation can approximate the integral: W ≈ ∑ᵢ Fᵢ∆x where each Fᵢ is a representative force over a small displacement interval ∆x. The approximation improves as the interval becomes smaller, provided the force data and numerical method are appropriate. 7. Functions and Modular DesignA function is a named, reusable block that performs a focused task. Functions improve readability, testing, and reuse. def circular_area(diameter_m):
"""Return area of a circle in square metres."""
if diameter_m <= 0:
raise ValueError("Diameter must be positive")
radius_m = diameter_m / 2
return 3.141592653589793 * radius_m ** 2
area = circular_area(0.02)The function accepts a parameter and returns a value. A function should generally avoid hidden dependence on global variables. Its documentation should state units, assumptions, and possible errors. Default arguments and keyword arguments can improve clarity: def kinetic_energy(mass_kg, velocity_m_s=0.0):
return 0.5 * mass_kg * velocity_m_s ** 2
energy_J = kinetic_energy(mass_kg=12.0, velocity_m_s=3.0)The kinetic-energy relationship is: Ek = ½mv² where E_k is energy in joules, m is mass in kilograms, and v is velocity in metres per second. It applies to classical mechanics for a particle or translational body under the stated modelling assumptions. A function may return several values: def stress_and_factor(force_N, area_m2, allowable_Pa):
stress_Pa = force_N / area_m2
factor = allowable_Pa / stress_Pa
return stress_Pa, factor8. Scope and Program StateScope describes where a name can be accessed. A local variable created inside a function normally exists only within that function. A global variable is defined outside functions and can be read more broadly, but excessive global state makes programs difficult to test and maintain. GRAVITY_M_S2 = 9.80665
def weight(mass_kg):
return mass_kg * GRAVITY_M_S2Here, the function reads the module-level constant. A better design for reusable scientific code may pass important values as parameters, making assumptions explicit: def weight(mass_kg, gravity_m_s2):
return mass_kg * gravity_m_s2The global keyword can modify a global variable inside a function, but it should be used sparingly. Prefer return values and parameters because they make data flow visible. 9. Modules and Standard LibrariesA module is a Python file containing definitions that can be imported. The standard library provides tested functionality without requiring external installation. import math
diameter_m = 0.05
area_m2 = math.pi * diameter_m ** 2 / 4 Frequently useful standard-library modules include: | Module | Typical engineering use |
|---|
math | π, square roots, trigonometric and logarithmic functions | statistics | mean, median, standard deviation for basic datasets | random | controlled random sampling and demonstrations | csv | reading and writing comma-separated data | pathlib | portable file and directory paths | datetime | dates and times |
Imports should be placed near the beginning of a file. The idiom below prevents demonstration code from running when the file is imported as a module: def main():
print("Run engineering calculation")
if __name__ == "__main__":
main()The standard library is valuable, but it does not replace engineering validation. A mathematically correct function can still be applied to an invalid physical model. 10. Worked Engineering Example: Shaft Power and TorqueProblemAn electric motor delivers 5.0 kW at 1,500 revolutions per minute. Determine the transmitted torque and assess whether it is below a specified limit of 40 N·m. Model and assumptionsFor rotational power: P = Tω where P is power in watts, T is torque in newton-metres, and ω is angular speed in radians per second. Rotational speed N in revolutions per minute is converted using: ω = 2πN/60 The motor is assumed to deliver the stated power steadily, and losses between motor and shaft are neglected. If efficiency η is known and the quoted power is input power, shaft power should instead be calculated as P_shaft = ηP_input. Python implementationimport math
power_kW = 5.0
speed_rpm = 1500.0
torque_limit_Nm = 40.0
power_W = power_kW * 1000
angular_speed_rad_s = 2 * math.pi * speed_rpm / 60
torque_Nm = power_W / angular_speed_rad_s
print(f"Angular speed = {angular_speed_rad_s:.2f} rad/s")
print(f"Torque = {torque_Nm:.2f} N·m")
if torque_Nm <= torque_limit_Nm:
print("Torque limit satisfied")
else:
print("Torque limit exceeded")The angular speed is approximately 157.08 rad/s, and the torque is approximately 31.83 N·m. Therefore, the stated 40 N·m limit is satisfied. Dimensional checking gives W ÷ (rad/s) = N·m, because the radian is dimensionless in SI. 11. Illustrative Case: Automated Bracket ScreeningBackground. A design team wants a quick screening tool for a steel bracket carrying several possible axial loads. The final design will be checked using detailed stress analysis and the relevant design code. Problem. The tool must accept load and cross-sectional area, calculate stress, compare it with an allowable stress, and reject nonphysical inputs. Approach. A function separates the engineering model from the user interface: def screen_bracket(load_kN, area_mm2, allowable_MPa):
if load_kN <= 0 or area_mm2 <= 0 or allowable_MPa <= 0:
raise ValueError("All inputs must be positive")
load_N = load_kN * 1000
area_m2 = area_mm2 * 1e-6
stress_MPa = (load_N / area_m2) / 1e6
factor_of_safety = allowable_MPa / stress_MPa
return stress_MPa, factor_of_safety
stress, factor = screen_bracket(18.0, 900.0, 160.0)
print(f"Stress = {stress:.1f} MPa")
print(f"Factor of safety = {factor:.2f}")For the illustrative inputs, stress is 20.0 MPa and the factor of safety is 8.00. The result is only a screening result: it does not account for stress concentrations, bending, buckling, fatigue, joints, residual stress, temperature, or failure criteria other than the selected allowable stress. Outcome and learning points. The case demonstrates unit conversion, validation, functions, return values, formatted output, and responsible interpretation. It also shows why a program’s numerical output must not be confused with design certification. 12. Errors, Testing, and Professional PracticePython errors commonly fall into three categories: - Syntax errors: the code violates Python grammar.
- Runtime errors: execution fails, such as division by zero or invalid conversion.
- Logical errors: the program runs but implements the wrong model or calculation.
Engineering programming requires tests at several levels. Test a function with ordinary values, boundary values, and deliberately invalid values. Use known hand calculations for verification. Check limiting behaviour: for example, stress should increase when force increases while area remains fixed. Good practice includes: - use descriptive names containing units where useful;
- keep functions short and focused;
- document assumptions and applicability;
- avoid unexplained numerical constants;
- validate ranges and physical constraints;
- use version control for important work;
- preserve input data and record program versions;
- report significant figures consistent with measurement and model accuracy;
- separate calculation, presentation, and file handling;
- never silently overwrite experimental or design data.
Python’s floating-point arithmetic is not exact for many decimal fractions. For ordinary engineering calculations, its precision is usually sufficient, but numerical conditioning, uncertainty, and rounding should be considered when results are near a decision boundary. 13. Ethical and Safety ConsiderationsA programming error in engineering can affect safety, cost, and public welfare. Engineers should not present unverified code as a validated design tool. Inputs, assumptions, material data, and software versions should be traceable. If an automated program recommends a design, a competent engineer must review the model and the result. Artificial intelligence tools can assist with code generation, explanation, and test creation, but generated code may contain incorrect formulas, unsafe assumptions, or hidden unit errors. AI-generated programs must be independently inspected, tested, and validated against authoritative engineering sources. Responsibility remains with the engineer who deploys or approves the calculation. Chapter SummaryPython provides a practical foundation for mechanical engineering computation. Variables store quantities, data types describe values, and operators construct expressions. Input and output create an interface, while validation protects calculations from invalid data. Conditional statements represent decisions, and loops automate repeated operations. Functions provide reusable, testable units and make assumptions explicit through parameters and return values. Scope governs name visibility, while modules and the standard library provide reliable general-purpose capabilities. Engineering programs must preserve unit consistency, document assumptions, test boundary conditions, and distinguish numerical execution from physical validity. A successful calculation is therefore both computationally correct and engineering-relevant. Professional practice also requires traceability, review, ethical judgment, and caution when using AI-assisted code. Key TermsVariable: A named reference to a value. Data type: A category defining how a value is represented and used. Expression: A combination of values, names, and operators that produces a result. Operator: A symbol or keyword that performs an operation. Boolean: A logical value that is either True or False. Input validation: Checking whether supplied data are correctly formed and physically acceptable. Conditional: A statement that selects execution based on a condition. Iteration: Repeated execution of a block of code. Function: A named, reusable block of instructions. Parameter: A variable specified in a function definition. Return value: Data sent from a function to its caller. Scope: The region in which a name can be accessed. Module: A file containing Python code that can be imported. Standard library: Modules distributed with Python. Floating-point number: A computer approximation to a real number. Algorithm: A finite sequence of steps for solving a problem. Unit consistency: The requirement that physical quantities be combined using compatible units. Factor of safety: The ratio of a selected limiting or allowable quantity to the working quantity. Verification: Checking whether an implementation correctly performs its intended calculation. Validation: Checking whether the model and results are suitable for the physical problem. Review QuestionsShort Answer Questions- Why should engineering variable names often include units?
- What type does Python’s
input() function return before conversion? - Distinguish between a
for loop and a while loop. - What is the purpose of a function’s return value?
- Why can direct equality comparison of floating-point values be unsafe?
Long Answer Questions- Explain how a mechanical engineering calculation should proceed from physical model to validated Python implementation.
- Discuss Python’s principal data types and give an engineering example for each.
- Explain conditional statements, comparison operators, and logical operators using a design-screening example.
- Describe local and global scope and explain why excessive global state is undesirable.
- Explain how modules and standard-library functions improve the quality of engineering programs.
Analytical / Application Questions- Write a Python function that accepts force in kN and area in mm², returns stress in MPa, and rejects nonpositive inputs. State the assumptions and unit conversions.
- A motor delivers 8.0 kW at 1,200 rpm. Develop a Python calculation for torque and determine whether a 55 N·m limit is exceeded. Show the unit conversion used.
- Design a validation and testing strategy for a program that calculates the factor of safety of a mechanical component. Include ordinary, boundary, invalid, and independent-check cases.
Multiple Choice Questions with AnswersQuestion 1Which Python expression calculates the area of a circular section with radius r_m in metres? A. 2 math.pi r_m B. math.pi r_m * 2 C. math.pi * r_m / 2 D. r_m ** 2 / math.pi Correct Answer: B. math.pi r_m 2* Question 2What type is returned directly by input()? A. int B. float C. str D. bool Correct Answer: C. str Question 3A force of 12 kN acts on an area of 600 mm². What is the normal stress? A. 2 MPa B. 20 MPa C. 200 MPa D. 20,000 MPa Correct Answer: B. 20 MPa Question 4Which operator performs exponentiation in Python? A. ^ B. // C. ** D. %% Correct Answer: C. ** Question 5For range(1, 5), which values are generated? A. 1, 2, 3, 4 B. 1, 2, 3, 4, 5 C. 0, 1, 2, 3, 4 D. 2, 3, 4, 5 Correct Answer: A. 1, 2, 3, 4 Question 6For rotational power, which relationship gives torque when power and angular speed are known? A. T = Pω B. T = P/ω C. T = ω/P D. T = P + ω Correct Answer: B. T = P/ω Question 7What is the main purpose of a function parameter? A. To terminate a loop B. To pass input data into a function C. To import a module D. To display formatted output Correct Answer: B. To pass input data into a function Question 8Which standard-library module provides math.pi? A. csv B. statistics C. math D. datetime Correct Answer: C. math Question 9Why should engineering code validate that an area is positive? A. A negative area is physically inappropriate and may invalidate the calculation B. Python cannot store zero C. Positive values automatically improve precision D. Validation changes the unit system Correct Answer: A. A negative area is physically inappropriate and may invalidate the calculation Question 10A motor delivers 5 kW at 1,500 rpm. Using P = Tω and ω = 2πN/60, which torque is closest? A. 3.18 N·m B. 31.8 N·m C. 318 N·m D. 3,180 N·m Correct Answer: B. 31.8 N·m
|