← Programming Concepts in Mechanical Engineering (25ME34I)
Functions and Modules
Programming Concepts in Mechanical Engineering (25ME34I) · C-25 Diploma Mechanical, Semester III
Read with diagrams, search and self-test
After studying this chapter you will be able to:
• Define and call functions with parameters and return values.
• Use default, keyword and variable-length arguments.
• Explain the scope of variables (local and global) and the global keyword.
• Write lambda functions and use them with map(), filter() and sorted().
• Distinguish built-in and user-defined functions.
• Import and use modules such as math, random and statistics, and create your own module.
4.1 What is a Function?
A function is a named, reusable block of code that performs a specific task. It runs only when it is called. Functions are the tools in a programmer's toolbox: once a function to calculate stress is written, it can be used again and again without rewriting the formula.
Why functions?
• Reusability: write once, use many times.
• Modularity: a big program is divided into small, manageable parts (top-down design).
• Readability: a well-named function such as shaft_power() explains itself.
• Easy testing and debugging: each function can be tested separately.
• Reduced code size: repeated code is avoided.
4.2 Defining and Calling a Function
def function_name(parameters):
"""docstring - what the function does"""
statement(s)
return value # optional• def is the keyword that starts a function definition.
• The function name follows identifier rules.
• Parameters (optional) are placed in brackets; the header ends with a colon.
• The body is indented.
• return sends a result back to the caller. A function without return gives None.
Fig. 4.1 Parts of a Python function
def greet():
print("Welcome to the Mechanical Workshop")greet() # calling the function greet() # can be called any number of times
Welcome to the Mechanical Workshop Welcome to the Mechanical Workshop
4.3 Parameters and Arguments
A parameter is the variable named in the function definition. An argument is the actual value passed when the function is called.
def stress(load, area): # load, area: parameters
print("Stress =", load / area, "N/mm^2")stress(20000, 400) # 20000, 400: arguments stress(load=9000, area=150) # keyword arguments
Stress = 50.0 N/mm^2 Stress = 60.0 N/mm^2
Types of arguments
| Type | Description | Example |
|---|---|---|
| Positional | Matched by position | power(1440, 50) |
| Keyword | Matched by name; order does not matter | power(T=50, N=1440) |
| Default | Parameter has a default value used when argument is omitted | def area(d, n=1) |
| Variable-length *args | Any number of positional arguments as a tuple | def total(*loads) |
| Keyword variable **kwargs | Any number of keyword arguments as a dictionary | def specs(**data) |
def cutting_speed(D, N, unit="m/min"):
import math
V = math.pi * D * N / 1000
return f"{V:.2f} {unit}"def total_load(*loads):
return sum(loads)print(cutting_speed(50, 600))
print(cutting_speed(N=600, D=80))
print("Total load =", total_load(1200, 800, 450, 2550), "N")94.25 m/min 150.80 m/min Total load = 5000 N
4.4 Return Values
The return statement ends the function and sends a value back to the place of call, where it can be stored in a variable, printed or used in further calculation. A function can return several values as a tuple.
import math
def shaft_power(N, T):
"""Return power in kW for speed N (rpm), torque T (N.m)"""
return 2 * math.pi * N * T / 60000def circle_props(d):
area = math.pi * d ** 2 / 4
perimeter = math.pi * d
return area, perimeter # two valuesP = shaft_power(1440, 50)
print(f"Power = {P:.2f} kW")
a, c = circle_props(20)
print(f"Area = {a:.2f} mm^2, Circumference = {c:.2f} mm")Power = 7.54 kW Area = 314.16 mm^2, Circumference = 62.83 mm
print() versus return
| print() | return |
|---|---|
| Displays the value on the screen | Sends the value back to the caller |
| Value cannot be used further | Value can be stored and reused |
| Function returns None | Function returns the given value |
| Used for showing results to the user | Used for calculations inside programs |
4.5 Scope of Variables
The scope of a variable is the part of the program where it can be accessed.
• Local variable: created inside a function; exists only while the function runs; cannot be used outside.
• Global variable: created outside all functions; can be read inside any function.
• To modify a global variable inside a function, declare it with the global keyword.
Fig. 4.2 Global and local scope
g = 9.81 # global constant
def weight(m):
w = m * g # w is local; g is read from global
return wprint("Weight of 50 kg =", weight(50), "N")
try:
print(w)
except NameError as e:
print("Error:", e)Weight of 50 kg = 490.5 N Error: name 'w' is not defined
count = 0 # global counter of parts produced
def produce():
global count # needed to modify the global
count += 1for _ in range(5):
produce()
print("Parts produced =", count)Parts produced = 5
| Local variable | Global variable |
|---|---|
| Declared inside a function | Declared outside all functions |
| Accessible only inside that function | Accessible throughout the program |
| Created when function is called, destroyed when it ends | Exists until the program ends |
| Safer, avoids accidental changes | Shared data; changes affect all functions |
When to use which: use a global for constants shared by many functions (g = 9.81, E = 200 GPa, material density). Use locals for intermediate results of a calculation (temporary stress, area) so that functions do not interfere with each other. Avoid modifying globals unnecessarily.
4.6 Lambda Functions
A lambda function is a small anonymous (nameless) function written in one line with the lambda keyword. It can take any number of arguments but contains only one expression, whose value is returned automatically.
Syntax: lambda arguments : expression
square = lambda x: x * x area_rect = lambda l, b: l * b f_to_c = lambda f: (f - 32) * 5 / 9 print(square(6), area_rect(12, 5), round(f_to_c(212), 1))
36 60 100.0
Lambdas are most useful with map(), filter() and sorted():
dia = [24.98, 25.01, 25.04, 24.95, 25.00]
in_tol = list(filter(lambda d: 24.98 <= d <= 25.02, dia))
radii = list(map(lambda d: d / 2, dia))
print("Within tolerance:", in_tol)
print("Radii:", radii)
parts = [("gear", 450), ("shaft", 1200), ("key", 30)]
print(sorted(parts, key=lambda p: p[1]))Within tolerance: [24.98, 25.01, 25.0]
Radii: [12.49, 12.505, 12.52, 12.475, 12.5]
[('key', 30), ('gear', 450), ('shaft', 1200)]| Normal function (def) | Lambda function |
|---|---|
| Has a name | Anonymous |
| Can contain many statements | Only one expression |
| Uses return statement | Returns expression value automatically |
| Can have docstring | No docstring |
| For larger reusable logic | For short, one-time operations |
4.7 Built-in Functions vs User-defined Functions
Built-in functions are always available in Python without importing anything: print() input() len() type() int() float() str() abs() round() max() min() sum() range() sorted() pow() divmod().
User-defined functions are written by the programmer with def (or lambda) for a specific task.
loads = [1200, 850, 1600, 975, 1430]
print("Count:", len(loads), " Max:", max(loads), " Min:", min(loads))
print("Sum:", sum(loads), " Mean:", sum(loads) / len(loads))
print("abs(-7.5) =", abs(-7.5), " pow(2,10) =", pow(2, 10))
print("divmod(17,5) =", divmod(17, 5))Count: 5 Max: 1600 Min: 850 Sum: 6055 Mean: 1211.0 abs(-7.5) = 7.5 pow(2,10) = 1024 divmod(17,5) = (3, 2)
| Built-in function | User-defined function |
|---|---|
| Pre-defined in Python | Defined by the programmer using def |
| Ready to use, no definition needed | Must be defined before calling |
| Highly optimised (written in C) | Speed depends on programmer's code |
| Examples: len(), max(), sum() | Examples: shaft_power(), stress() |
Example where a built-in function is more efficient: finding the largest load in a list. max(loads) is one call, tested and fast; a user-defined loop needs 5–6 lines and may contain errors. User-defined functions are still necessary because Python has no built-in function for engineering formulas like shaft diameter or bolt stress; they also make code reusable and readable.
def my_max(values): # user-defined equivalent
largest = values[0]
for v in values[1:]:
if v > largest:
largest = v
return largestdata = [1200, 850, 1600, 975, 1430] print(my_max(data), max(data))
1600 1600
4.8 Modules
A module is a Python file (.py) containing functions, classes and variables that can be used in other programs. A collection of modules is a package (e.g. NumPy, Matplotlib). The standard library has hundreds of modules: math, random, statistics, csv, time, datetime, os.
Ways of importing
| Statement | Usage |
|---|---|
| import math | math.sqrt(16) |
| import math as m | m.sqrt(16) (alias) |
| from math import sqrt, pi | sqrt(16), pi (no prefix) |
| from math import * | imports everything (not recommended) |
The math module
| Function/constant | Meaning | Example → result |
|---|---|---|
| math.pi, math.e | π, e | 3.141592..., 2.718281... |
| math.sqrt(x) | Square root | sqrt(144) → 12.0 |
| math.pow(x, y) | x to the power y (float) | pow(2, 3) → 8.0 |
| math.sin/cos/tan(x) | Trig functions, x in radians | sin(pi/6) → 0.5 |
| math.radians/degrees | Angle conversion | radians(180) → 3.1416 |
| math.asin/acos/atan(x) | Inverse trig, result in radians | degrees(atan(1)) → 45.0 |
| math.log(x), log10(x) | Natural and base-10 log | log10(1000) → 3.0 |
| math.exp(x) | e to the power x | exp(1) → 2.718 |
| math.ceil, floor | Round up, round down | ceil(4.2) → 5 |
| math.factorial(n) | n! | factorial(5) → 120 |
| math.gcd(a, b) | Greatest common divisor | gcd(24, 36) → 12 |
| math.hypot(x, y) | √(x² + y²) | hypot(3, 4) → 5.0 |
The random module
| Function | Meaning |
|---|---|
| random.random() | Float in [0.0, 1.0) |
| random.randint(a, b) | Integer from a to b (both included) |
| random.uniform(a, b) | Float between a and b |
| random.choice(seq) | Random item from a sequence |
| random.shuffle(list) | Shuffles a list in place |
| random.sample(seq, k) | k unique random items |
| random.seed(n) | Makes random results repeatable |
import random
random.seed(1)
print(random.randint(1, 6), round(random.uniform(24.9, 25.1), 3))
print(random.choice(["lathe", "milling", "drilling"]))
batch = list(range(1, 21))
print("Sample of 5 parts for inspection:", random.sample(batch, 5))2 25.014 lathe Sample of 5 parts for inspection: [9, 4, 16, 15, 18]
Random numbers are used in engineering to simulate measurement data, select random samples for inspection (sampling plans) and perform Monte-Carlo simulations.
The statistics module
import statistics as st
d = [25.02, 24.98, 25.01, 25.00, 24.99]
print("Mean =", round(st.mean(d), 4))
print("Median =", st.median(d))
print("Stdev =", round(st.stdev(d), 5))Mean = 25.0 Median = 25.0 Stdev = 0.01581
Creating your own module
Save the following as mechcalc.py in the same folder:
# mechcalc.py - a user-defined module import math E_STEEL = 200000 # N/mm^2
def stress(P, A):
return P / Adef torque_from_power(P_kW, N):
return 60000 * P_kW / (2 * math.pi * N)Then use it from another program:
import mechcalc as mc print(mc.stress(50000, 400)) # 125.0 print(round(mc.torque_from_power(7.5, 1440), 2)) # 49.74 print(mc.E_STEEL) # 200000
4.9 Practice Programs (Week 4)
Program 4.1 – Function to calculate the area of a circle
Algorithm: Start → define function area_circle(r) returning π r² → read r → call function → display → Stop.
# Program 4.1: Area of circle using a function import math
def area_circle(r):
"""Return area of a circle of radius r"""
return math.pi * r ** 2radius = float(input("Enter radius (mm): "))
print(f"Area of circle = {area_circle(radius):.2f} mm^2")Enter radius (mm): 5 Area of circle = 78.54 mm^2
Program 4.2 – GCD of two numbers using a function
Euclid's algorithm: GCD(a, b) = GCD(b, a mod b), and GCD(a, 0) = a. Example: GCD(48, 18) → GCD(18, 12) → GCD(12, 6) → GCD(6, 0) = 6. In gears, GCD is used to find the hunting tooth frequency: two gears with teeth T1 and T2 repeat the same tooth contact after LCM(T1, T2) = T1·T2 / GCD(T1, T2) tooth engagements.
# Program 4.2: GCD using Euclid's algorithm
def gcd(a, b):
while b != 0:
a, b = b, a % b
return ax = int(input("Enter first number : "))
y = int(input("Enter second number: "))
g = gcd(x, y)
print("GCD =", g)
print("LCM =", x * y // g)Enter first number : 48 Enter second number: 18 GCD = 6 LCM = 144
Recursive version (a function calling itself):
def gcd_r(a, b):
return a if b == 0 else gcd_r(b, a % b)
print(gcd_r(40, 25))5
Program 4.3 – Lambda one-liners
square = lambda x: x ** 2
cube = lambda x: x ** 3
is_even = lambda x: x % 2 == 0
n = int(input("Enter a number: "))
print("Square =", square(n), " Cube =", cube(n), " Even?", is_even(n))
nums = [1, 2, 3, 4, 5]
print("Squares using map:", list(map(lambda v: v * v, nums)))Enter a number: 6 Square = 36 Cube = 216 Even? True Squares using map: [1, 4, 9, 16, 25]
Program 4.4 – Trigonometric calculations using the math module
# Program 4.4: Trigonometry with math module
import math
deg = float(input("Enter angle in degrees: "))
rad = math.radians(deg)
print(f"sin({deg}) = {math.sin(rad):.4f}")
print(f"cos({deg}) = {math.cos(rad):.4f}")
print(f"tan({deg}) = {math.tan(rad):.4f}")
print(f"{deg} deg = {rad:.4f} rad")Enter angle in degrees: 30 sin(30.0) = 0.5000 cos(30.0) = 0.8660 tan(30.0) = 0.5774 30.0 deg = 0.5236 rad
Engineering application – resolving a force:
import math
F = float(input("Force F (N): "))
theta = float(input("Angle with horizontal (deg): "))
Fx = F * math.cos(math.radians(theta))
Fy = F * math.sin(math.radians(theta))
R = math.hypot(Fx, Fy)
print(f"Fx = {Fx:.2f} N, Fy = {Fy:.2f} N, check R = {R:.1f} N")Force F (N): 500 Angle with horizontal (deg): 30 Fx = 433.01 N, Fy = 250.00 N, check R = 500.0 N
Program 4.5 – Function library for a shaft
import math
def torque(P_kW, N):
return 60e6 * P_kW / (2 * math.pi * N) # N.mmdef shaft_dia(T, tau):
return (16 * T / (math.pi * tau)) ** (1 / 3)T = torque(15, 720)
d = shaft_dia(T, 40)
print(f"Torque = {T:.0f} N.mm, Required dia = {d:.2f} mm")
print("Select standard diameter =", math.ceil(d / 5) * 5, "mm")Torque = 198944 N.mm, Required dia = 29.37 mm Select standard diameter = 30 mm
Program 4.6 – Factorial: iterative, recursive and math module
import math
def fact_loop(n):
f = 1
for i in range(2, n + 1):
f *= i
return f
def fact_rec(n):
return 1 if n <= 1 else n * fact_rec(n - 1)
print(fact_loop(7), fact_rec(7), math.factorial(7))5040 5040 5040
4.10 Solved Exam Questions
Q1. Describe the role of function parameters and return values. Give an example where a function takes different parameters to calculate the cost of various materials. (6 marks)
Answer: Parameters are the inputs of a function: they make it general, so the same code works for different data. The return value is the output sent back to the caller for further use.
def material_cost(length_m, area_mm2, density, rate):
vol = length_m * area_mm2 * 1e-6 # m^3
mass = vol * density # kg
return mass * rate # rupeesprint("MS bar :", round(material_cost(6, 314.16, 7850, 65), 2))
print("Al bar :", round(material_cost(6, 314.16, 2700, 240), 2))
print("Cu bar :", round(material_cost(6, 314.16, 8960, 780), 2))MS bar : 961.8 Al bar : 1221.45 Cu bar : 13173.61
Q2. Differentiate between built-in and user-defined functions. Give an example where a built-in function is more efficient. (6 marks)
Answer: See the table in Section 4.7. Example: max(loads) versus a 6-line loop my_max(); the built-in is shorter, already tested and faster because it is implemented in C.
Q3. Explain why user-defined functions are often necessary even when built-in functions are available. (6 marks)
Answer: Built-in functions perform only general tasks (sum, max, length). Engineering problems need specific formulas – shaft diameter, bending stress, gear ratio, efficiency – which are not built in. User-defined functions (1) implement such domain logic, (2) avoid repeating code, (3) divide large programs into modules, (4) make programs readable through meaningful names, (5) allow independent testing and (6) can be collected in a module and shared.
Q4. Differentiate between local and global variables. Give an example of when each is appropriate in an engineering application. (6 marks)
Answer: See the table in Section 4.5. Global: acceleration due to gravity g = 9.81 or E = 200000 used by many functions. Local: w = m * g inside weight(), or intermediate stress inside a design function; local variables prevent accidental interference between functions.
Q5. What is a lambda function? Explain with an example.
Answer: An anonymous one-line function: lambda arguments: expression. Example: square = lambda x: x * x; square(5) gives 25. Used with map/filter/sorted for short operations.
Q6. What is a module? Explain different ways of importing modules with examples.
Answer: See Section 4.8.
4.11 Multiple Choice Questions
1. Which keyword is used to define a function? a) function b) def c) define d) fun
Answer: (b) Reason: def starts every function definition in Python.
2. A function without a return statement returns a) 0 b) None c) Empty string d) Error
Answer: (b) Reason: Python automatically returns None when return is absent.
3. Values passed to a function at the time of call are called a) Parameters b) Arguments c) Keywords d) Modules
Answer: (b) Reason: Parameters are names in the definition; arguments are the actual values passed.
4. A variable declared inside a function is a) global b) local c) static d) constant
Answer: (b) Reason: It exists only within that function's scope.
5. Which keyword lets a function modify a global variable? a) nonlocal b) global c) extern d) static
Answer: (b) Reason: global tells Python that assignment refers to the module-level variable.
6. lambda x, y: x + y is a) a loop b) an anonymous function c) a module d) a class
Answer: (b) Reason: lambda creates a small unnamed function with one expression.
7. math.sqrt(81) returns a) 9 b) 9.0 c) 81 d) Error
Answer: (b) Reason: math.sqrt always returns a float.
8. math.sin() expects the angle in a) degrees b) radians c) grads d) any unit
Answer: (b) Reason: Convert degrees with math.radians() before calling sin, cos or tan.
9. random.randint(1, 6) can return a)0to6 b)1to5 c) 1 to 6 inclusive d) only floats
Answer: (c) Reason: randint includes both end points.
10. Which import lets you write sqrt(25) without a prefix? a) import math b) from math import sqrt c) import sqrt d) using math
Answer: (b) Reason: from ... import brings the name directly into the program.
11. GCD of 24 and 36 is a) 6 b) 12 c) 72 d) 4
Answer: (b) Reason: 12 is the largest number dividing both 24 and 36.
12. Which is a built-in function? a) shaft_power() b) len() c) gcd() defined by user d) area_circle()
Answer: (b) Reason: len() is available in Python without definition or import.
13. def f(a, b=5): return a*b; f(3) returns a) 8 b) 15 c) Error d) 3
Answer: (b) Reason: b takes its default value 5, so 3 × 5 = 15.
14. *args in a function definition collects extra arguments as a a) list b) tuple c) dictionary d) set
Answer: (b) Reason: Variable positional arguments are packed into a tuple.
15. A file containing Python definitions that can be imported is a a) package b) module c) library card d) loop
Answer: (b) Reason: Any .py file can act as a module; a folder of modules is a package.
16. math.radians(180) is approximately a) 1.57 b) 3.1416 c) 6.283 d) 180
Answer: (b) Reason: 180° equals π radians.
4.12 Exercises
1. Write a function bolt_stress(P, d) that returns the tensile stress in a bolt of core diameter d.
2. Write a function returning both the volume and surface area of a sphere.
3. Using lambda and filter, select all loads greater than 1000 N from a list.
4. Write a module units.py with functions for mm→inch, N→kgf and kW→hp conversions and use it.
5. Write a recursive function to find the sum of digits of a number.