← Programming Concepts in Mechanical Engineering (25ME34I)
Introduction to Python and Basic Constructs
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:
• Describe Python and its development environments: Anaconda, Jupyter Notebook, Spyder and PyCharm.
• Write Python statements using correct syntax, comments, indentation and identifiers.
• Use the basic data types int, float, str and bool, and convert between them.
• Read data with input() and display results with print(), including formatted output.
• Use arithmetic, assignment, comparison and logical operators with correct precedence.
2.1 Introduction to Python
Python is a high-level, interpreted, dynamically typed, general-purpose programming language. "High-level" means it is close to human language; "interpreted" means the code is executed directly by an interpreter without a separate compile step visible to the user; "dynamically typed" means you do not declare the type of a variable – Python decides it from the value.
Fig. 2.1 How a Python program is executed
Features of Python
• Simple and easy to learn – minimal syntax, readable code.
• Free and open source – download from python.org without cost.
• Interpreted and interactive – type a statement and see the result immediately.
• Portable / platform independent – runs on Windows, Linux, macOS and Raspberry Pi OS.
• Dynamically typed – no type declarations are needed.
• Object-oriented – supports classes and objects (Chapter 7).
• Extensive standard library – math, random, statistics, csv, datetime, os, time.
• Rich third-party libraries – NumPy, Matplotlib, pandas, SciPy, gpiozero.
• Extensible and embeddable – can call C/C++ code and be embedded in other software (CAD, FEA tools such as Abaqus and FreeCAD use Python scripting).
Applications of Python in Mechanical Engineering
| Area | Typical use | Libraries |
|---|---|---|
| Design calculations | Shaft, gear, spring, beam calculations | math, NumPy |
| Data visualisation | Stress-strain curves, performance curves | Matplotlib |
| Quality control | Control charts, Cp, Cpk, hypothesis tests | statistics, SciPy, pandas |
| Spreadsheet data | Read/write Excel and CSV test data | csv, pandas, openpyxl |
| FEM and simulation | Stiffness matrices, solving equations | NumPy, SciPy |
| Automation and robotics | Motor control, sensor reading | gpiozero, RPi.GPIO |
| CAD automation | Scripting in FreeCAD, Fusion 360, Abaqus | built-in APIs |
2.2 Python Development Environments
A program can be written in any text editor, but an IDE (Integrated Development Environment) makes it easier by providing an editor, interpreter, error highlighting and debugging tools in one place.
(a) Anaconda Distribution
Anaconda is a free Python distribution for scientific computing. One installer provides the Python interpreter, the conda package manager, Jupyter Notebook, Spyder IDE and more than 250 pre-installed packages such as NumPy, pandas, Matplotlib and SciPy. The Anaconda Navigator window lets you launch these tools with a click.
Advantages: single easy installation, all engineering libraries included, conda manages versions and environments, suitable for beginners.
(b) Jupyter Notebook
Jupyter Notebook is a web-based interactive environment that runs in a browser. A notebook (.ipynb file) is made of cells: code cells, whose output appears immediately below, and markdown cells for text, equations and headings.
Fig. 2.2 Code cells and output in Jupyter Notebook
Advantages: interactive cell-by-cell execution, graphs appear inside the notebook, code + explanation + results in one document (ideal for lab records), widely used in data analysis. Google Colab is a free online Jupyter notebook that needs no installation.
(c) Spyder
Spyder (Scientific Python Development Environment) is included in Anaconda. It has a MATLAB-like layout: editor on the left, IPython console and variable explorer on the right, which shows the value of every variable – very useful while learning.
(d) PyCharm
PyCharm, by JetBrains, is a professional IDE (free Community edition). Features: intelligent code completion, real-time error detection, powerful debugger with breakpoints, project management, version control (Git) integration and virtual-environment support. It is preferred for large projects.
(e) IDLE and Thonny
IDLE is the simple editor installed with Python from python.org. Thonny is a beginner IDE pre-installed on Raspberry Pi OS; it is used in Chapters 8 and 9.
Comparison of environments
| Feature | Jupyter | Spyder | PyCharm | IDLE/Thonny |
|---|---|---|---|---|
| Type | Browser notebook | Scientific IDE | Professional IDE | Simple editor |
| Best for | Data analysis, lab records | Engineering calculations | Large projects | Beginners, Raspberry Pi |
| Graphs inline | Yes | Yes (plots pane) | In separate window | Separate window |
| Variable explorer | Limited | Yes | Debugger view | Thonny: yes |
| Installation | With Anaconda or Colab online | With Anaconda | Separate download | With Python / Pi OS |
Interactive mode and script mode
• Interactive mode: statements are typed at the >>> prompt and executed immediately. Good for testing small expressions.
• Script mode: the whole program is saved in a file with extension .py and run at once. Used for complete programs.
2.3 Basic Python Syntax
The syntax of a language is its set of grammar rules. Important Python syntax rules:
1. Case sensitive: Force, force and FORCE are three different names.
2. One statement per line; a semicolon allows several statements on a line but is rarely used.
3. Indentation defines blocks. Statements inside if, for, while, def and class are indented, normally by 4 spaces. Wrong indentation causes IndentationError.
4. Colon : ends the header line of a block (if, for, while, def, class).
5. Comments start with # and are ignored by Python. Multi-line explanations use triple quotes """ ... """ (docstrings).
6. No semicolons or braces are needed.
7. Long statements can continue on the next line inside brackets or with a backslash \.
# Program to display a welcome message
# This is a comment - Python ignores it
print("Hello Mechanical Engineers") # inline comment
print("Welcome to Python")Hello Mechanical Engineers Welcome to Python
Identifiers and keywords
An identifier is a name given to a variable, function or class. Rules:
• May contain letters (a–z, A–Z), digits (0–9) and underscore (_).
• Must not start with a digit: 2force is invalid, force2 is valid.
• No spaces or special symbols: shaft dia, load@1 are invalid; use shaft_dia.
• Must not be a keyword (reserved word).
• Use meaningful names: torque is better than t.
Python 3 has 35 keywords, for example: False None True and as assert break class continue def del elif else except finally for from global if import in is lambda nonlocal not or pass raise return try while with yield.
2.4 Variables
A variable is a named location in memory used to store a value. In Python a variable is created the moment a value is assigned to it with =.
Syntax: variable_name = value
# Variables storing machine data machine = "Lathe" # string spindle_speed = 1200 # integer (rpm) power = 7.5 # float (kW) running = True # boolean print(machine, spindle_speed, power, running)
# Multiple assignment length, breadth = 2.5, 1.2 a = b = c = 0 print(length, breadth, a, b, c)
# A variable can be re-assigned
power = 11.0
print("New power =", power)Lathe 1200 7.5 True 2.5 1.2 0 0 0 New power = 11.0
2.5 Data Types
A data type tells Python what kind of value a variable holds and what operations are allowed on it. The built-in function type() shows the data type.
| Data type | Meaning | Examples | Engineering example |
|---|---|---|---|
| int | Whole numbers, positive or negative, unlimited size | 10, −25, 1440 | Number of teeth, rpm |
| float | Real numbers with decimal point or exponent | 3.14, 2.1e5 | Stress, diameter, E = 2.1e5 N/mm² |
| str | Text, enclosed in single, double or triple quotes | "Lathe", 'EN8' | Material grade, machine name |
| bool | Logical value | True, False | Machine ON/OFF, safe/unsafe |
| compl ex | Complex numbers | 3 + 4j | Vibration, AC circuits |
teeth = 40 E = 2.1e5 material = "EN8 steel" is_safe = True z = 3 + 4j print(type(teeth), type(E), type(material)) print(type(is_safe), type(z))
<class 'int'> <class 'float'> <class 'str'> <class 'bool'> <class 'complex'>
String basics
grade = "EN24" print(len(grade)) # number of characters print(grade + " steel") # concatenation print(grade * 3) # repetition print(grade[0], grade[-1]) # indexing print(grade.lower()) # method
4 EN24 steel EN24EN24EN24 E 4 en24
Boolean data type
A boolean has only two values, True and False. Comparisons produce booleans. Booleans are used for decision making in engineering programs, for example to check whether a component is safe, whether a sensor is triggered or whether the temperature limit is exceeded.
# Is the shaft safe?
stress = float(input("Working stress (MPa): "))
allowable = float(input("Allowable stress (MPa): "))
safe = stress <= allowable
print("Shaft safe?", safe)Working stress (MPa): 120 Allowable stress (MPa): 150 Shaft safe? True
2.6 Input and Output Operations
The print() function
print() displays values on the screen. Syntax: print(value1, value2, ..., sep=' ', end='\n').
d = 25.4
print("Diameter", d, "mm")
print("A", "B", "C", sep="-")
print("No new line", end=" ... ")
print("continued")Diameter 25.4 mm A-B-C No new line ... continued
The input() function
input(prompt) displays the prompt, waits for the user to type and press Enter, and always returns a string. To use the value in calculations it must be converted with int() or float().
name = input("Enter your name: ")
age = int(input("Enter your age: "))
print("Hello", name, "- next year you will be", age + 1)Enter your name: Ravi Enter your age: 18 Hello Ravi - next year you will be 19
input() always returns a string. "10" + "20" gives "1020", not 30. Convert with int() or float() before doing arithmetic.
Formatted output
Engineers need neat results with units and fixed decimal places. Python offers f-strings (recommended), the format() method and the older % operator.
P, A = 50000, 314.16
stress = P / A
print(f"Stress = {stress:.2f} N/mm^2")
print("Stress = {:.3f} N/mm^2".format(stress))
print("Stress = %.1f N/mm^2" % stress)
print(f"{'Load':<8}{'Area':>10}")
print(f"{P:<8}{A:>10.2f}")Stress = 159.15 N/mm^2 Stress = 159.155 N/mm^2 Stress = 159.2 N/mm^2 Load Area 50000 314.16
In {stress:.2f}, .2f means a float with 2 digits after the decimal point; <8 means left-aligned in 8 spaces and >10 right-aligned in 10 spaces.
2.7 Type Conversion
Type conversion (type casting) is changing a value from one data type to another.
• Implicit conversion: done automatically by Python, e.g. 5 + 2.0 gives 7.0 (int promoted to float).
• Explicit conversion: done by the programmer using int(), float(), str(), bool().
| Function | Converts to | Example | Result |
|---|---|---|---|
| int(x) | Integer (truncates decimals) | int(7.9), int("25") | 7, 25 |
| float(x) | Floating point | float(5), float("3.5") | 5.0, 3.5 |
| str(x) | String | str(250) | '250' |
| bool(x) | Boolean (0, 0.0, "" are False) | bool(0), bool(5) | False, True |
| round(x, n) | Rounded float | round(3.14159, 2) | 3.14 |
x = input("Enter a decimal value: ") # string '7.8'
print(type(x))
f = float(x) # string -> float
i = int(f) # float -> int (truncates)
r = round(f) # nearest integer
s = str(i) + " units" # int -> string
print(f, i, r, s)
print(int("25") + 5, float(5), bool(0), bool(3))Enter a decimal value: 7.8 <class 'str'> 7.8 7 8 7 units 30 5.0 False True
If the user enters a decimal (e.g. 7.8) but an integer is needed, write n = int(float(input())). Calling int("7.8") directly raises ValueError because "7.8" is not an integer string.
n = int(float(input("Enter value: ")))
print("Integer value used =", n)Enter value: 7.8 Integer value used = 7
2.8 Operators
An operator is a symbol that performs an operation on values called operands.
Arithmetic operators
| Operato r | Name | Example (a = 17, b = 5) | Resul t |
|---|---|---|---|
| + | Addition | a + b | 22 |
| − | Subtraction | a − b | 12 |
| * | Multiplication | a * b | 85 |
| / | True division (always float) | a / b | 3.4 |
| // | Floor division | a // b | 3 |
| % | Modulus (remainder) | a % b | 2 |
| ** | Exponent (power) | a ** 2 | 289 |
a, b = 17, 5 print(a + b, a - b, a * b, a / b) print(a // b, a % b, a ** 2) print(-17 // 5, 2 ** 0.5)
22 12 85 3.4 3 2 289 -4 1.4142135623730951
-17 // 5 gives −4 because floor division rounds towards minus infinity. Modulus is useful to check divisibility (even/odd) and to find, for example, how many pieces remain after cutting bars of fixed length.
Assignment operators
| Operator | Example | Equivalent |
|---|---|---|
| = | x = 10 | assign 10 |
| += | x += 5 | x = x + 5 |
| −= | x −= 3 | x = x − 3 |
| *= | x *= 2 | x = x * 2 |
| /= | x /= 4 | x = x / 4 |
| //= | x //= 3 | x = x // 3 |
| %= | x %= 3 | x = x % 3 |
| **= | x **= 2 | x = x ** 2 |
stock = 100 # bolts in store
stock -= 30 # issued
stock += 50 # received
stock *= 2 # doubled by new order
print("Bolts in stock =", stock)Bolts in stock = 240
Comparison (relational) operators
== equal, != not equal, > greater, < less, >= greater or equal, <= less or equal. They return True or False.
Logical operators
| Operator | Result is True when | Example |
|---|---|---|
| and | both conditions are True | temp < 80 and pressure < 100 |
| or | at least one is True | overload or overheat |
| not | condition is False | not running |
Operator precedence (highest to lowest)
() → ** → unary + − → * / // % → + − → comparisons → not → and → or. Use brackets to make expressions clear.
print(2 + 3 * 4) # 14, * before + print((2 + 3) * 4) # 20 print(2 ** 3 ** 2) # 512, ** is right-associative print(10 - 4 - 3) # 3, left to right
14 20 512 3
2.9 Practice Programs (Week 2)
Program 2.1 – Arithmetic operations on two numbers
Algorithm: Start → read a and b → compute sum, difference, product, quotient, floor quotient, remainder and power → display → Stop.
# Program 2.1: Arithmetic operations
a = float(input("Enter first number : "))
b = float(input("Enter second number: "))
print("Addition =", a + b)
print("Subtraction =", a - b)
print("Multiplication =", a * b)
print("Division =", round(a / b, 4))
print("Floor division =", a // b)
print("Modulus =", a % b)
print("Power =", a ** b)Enter first number : 20 Enter second number: 6 Addition = 26.0 Subtraction = 14.0 Multiplication = 120.0 Division = 3.3333 Floor division = 3.0 Modulus = 2.0 Power = 64000000.0
Program 2.2 – Output speed and torque of a gear system
For a gear train with gear ratio G = N_in / N_out (= teeth on driven / teeth on driver), neglecting losses:
• Output speed N_out = N_in / G
• Output torque T_out = T_in × G (power is constant, P = 2πNT/60)
Algorithm: Start → read input speed, input torque and gear ratio → compute output speed and output torque → compute input and output power → display → Stop.
# Program 2.2: Gear system - output speed and torque
import math
N_in = float(input("Input speed (rpm): "))
T_in = float(input("Input torque (N.m): "))
G = float(input("Gear ratio (driven/driver): "))
N_out = N_in / G
T_out = T_in * G
P_in = 2 * math.pi * N_in * T_in / 60
P_out = 2 * math.pi * N_out * T_out / 60
print(f"Output speed = {N_out:.1f} rpm")
print(f"Output torque = {T_out:.1f} N.m")
print(f"Power in = {P_in:.1f} W, Power out = {P_out:.1f} W")Input speed (rpm): 1440 Input torque (N.m): 20 Gear ratio (driven/driver): 4 Output speed = 360.0 rpm Output torque = 80.0 N.m Power in = 3015.9 W, Power out = 3015.9 W
Explanation: a speed-reduction gear box reduces speed by the gear ratio and increases torque by the same ratio; the power remains 3015.9 W in both shafts (ideal gears). With efficiency η, T_out = T_in × G × η.
Program 2.3 – Practice on type conversions and variables
# Program 2.3: Type conversion practice
teeth = input("Number of teeth on gear: ") # str
module = input("Module in mm: ") # str
print("Before conversion:", type(teeth), type(module))
teeth = int(teeth)
module = float(module)
pcd = teeth * module # pitch circle diameter
print("After conversion :", type(teeth), type(module))
print("PCD = " + str(pcd) + " mm")
print("PCD as integer =", int(pcd), "mm")Number of teeth on gear: 45 Module in mm: 2.5 Before conversion: <class 'str'> <class 'str'> After conversion : <class 'int'> <class 'float'> PCD = 112.5 mm PCD as integer = 112 mm
Program 2.4 – Area and perimeter of a rectangular plate
length = float(input("Length of plate (mm): "))
width = float(input("Width of plate (mm): "))
area = length * width
perimeter = 2 * (length + width)
print("Area =", area, "mm^2")
print("Perimeter =", perimeter, "mm")Length of plate (mm): 120 Width of plate (mm): 80 Area = 9600.0 mm^2 Perimeter = 400.0 mm
Program 2.5 – Area of a circle and cross-section of a shaft
import math
d = float(input("Shaft diameter (mm): "))
r = d / 2
area = math.pi * r ** 2
print(f"Cross-sectional area = {area:.2f} mm^2")Shaft diameter (mm): 25 Cross-sectional area = 490.87 mm^2
Program 2.6 – Stress, strain and Young's modulus
# Program 2.6: Simple stress and strain
P = float(input("Axial load P (N): "))
A = float(input("Area A (mm^2): "))
L = float(input("Original length L (mm): "))
dL = float(input("Elongation dL (mm): "))
stress = P / A
strain = dL / L
E = stress / strain
print(f"Stress = {stress:.2f} N/mm^2")
print(f"Strain = {strain:.6f}")
print(f"Young's modulus E = {E:.0f} N/mm^2")Axial load P (N): 50000 Area A (mm^2): 314.16 Original length L (mm): 200 Elongation dL (mm): 0.16 Stress = 159.15 N/mm^2 Strain = 0.000800 Young's modulus E = 198943 N/mm^2
Program 2.7 – Power transmitted by a shaft
import math
N = float(input("Speed N (rpm): "))
T = float(input("Torque T (N.m): "))
P = 2 * math.pi * N * T / 60 # watts
print(f"Power = {P:.1f} W = {P/1000:.3f} kW")Speed N (rpm): 1440 Torque T (N.m): 50 Power = 7539.8 W = 7.540 kW
2.10 Solved Exam Questions
Q1. Explain the development environments available for writing Python programs. (6 marks)
Answer: (1) Anaconda – free distribution with Python, conda, Jupyter, Spyder and scientific libraries; easy single installation. (2) Jupyter Notebook – browser-based, cell-by-cell execution, inline graphs, combines code and notes; Google Colab is its online version. (3) Spyder – scientific IDE with editor, IPython console, variable explorer and plots pane. (4) PyCharm – professional IDE with code completion, error detection, debugger and project management. (5) IDLE/Thonny – simple editors; Thonny is pre-installed on Raspberry Pi OS.
Q2. In Python, how do you declare a variable to store a person's name and age? Which data types are appropriate and why? (6 marks)
Answer: name = "Ravi" and age = 18. No declaration keyword is needed; the variable is created on assignment. The name is text, so str is appropriate. Age is a whole number, so int is appropriate; it allows arithmetic such as age + 1. If height were stored, float would be used because it has a decimal part. Reading from the keyboard: name = input("Name: ") and age = int(input("Age: ")).
Q3. Explain the purpose of input() with an engineering example. (6 marks)
Answer: input() pauses the program, displays a prompt, reads what the user types and returns it as a string. It makes programs general: the same program works for any data. Example: computing stress for any load and area entered by the operator: P = float(input("Load in N: ")), A = float(input("Area in mm2: ")), print("Stress =", P/A). The float() conversion is necessary because input() returns text.
Q4. Discuss the boolean data type. In which engineering problems is it used? (6 marks)
Answer: The bool type has only two values, True and False, produced by comparison and logical operators. It is used for decision making: checking whether a design is safe (stress <= allowable), whether a machine is running, whether a sensor detects an object, whether a part is within tolerance (LSL <= d <= USL) and whether an alarm should be triggered. Booleans control if statements and while loops, so the program can take different actions automatically.
Q5. Explain type conversion with examples. (6 marks)
Answer: Refer Section 2.7. Implicit conversion is automatic (3 + 2.5 = 5.5). Explicit conversion uses int(), float(), str() and bool(). Example of handling decimal input when an integer is required: n = int(float(input())).
Q6. List the arithmetic operators of Python with examples.
Answer: Refer the table in Section 2.8. Key points: / always gives float, // gives floor quotient, % gives remainder and ** gives power.
Q7. What are the rules for naming identifiers? Give valid and invalid examples.
Answer: Refer Section 2.3. Valid: shaft_dia, F1, _temp, maxLoad. Invalid: 1force (starts with digit), shaft dia (space), load% (special character), class (keyword).
2.11 Multiple Choice Questions
1. Which of the following is a valid variable name? a) 2load b) load_2 c) load-2 d) for
Answer: (b) Reason: Names may contain letters, digits and underscore but cannot start with a digit, contain "-" or be a keyword like for.
2. The output of print(7 / 2) is a) 3 b) 3.5 c) 4 d) 3.0
Answer: (b) Reason: The / operator always performs true division and returns a float.
3. The output of print(7 // 2) is a) 3.5 b) 3 c)4 d)1
Answer: (b) Reason: // is floor division; it discards the fractional part.
4. The output of print(17 % 5) is a)3 b)2 c) 3.4 d) 85
Answer: (b) Reason: % gives the remainder: 17 = 5 × 3 + 2.
5. input() returns data of type a) int b) float c) str d) bool
Answer: (c) Reason: input() always returns a string, which must be converted for arithmetic.
6. type(2.1e5) is a) int b) float c) str d) complex
Answer: (b) Reason: Numbers written with a decimal point or exponent (e) are floats.
7. Which symbol starts a single-line comment in Python? a) // b) /* c) # d) --
Answer: (c) Reason: Python ignores everything after # on that line.
8. int(9.99) gives a) 10 b) 9 c) 9.9 d) Error
Answer: (b) Reason: int() truncates the decimal part; it does not round.
9. Which IDE is pre-installed on Raspberry Pi OS and is beginner friendly? a) PyCharm b) Thonny c) Visual Studio d) Eclipse
Answer: (b) Reason: Thonny comes with Raspberry Pi OS and shows variables step by step.
10. Jupyter Notebook files have the extension a) .py b) .ipynb c) .jpy d) .txt
Answer: (b) Reason: IPython notebook files use .ipynb; plain scripts use .py.
11. The value of 2 3 2 is a) 64 b) 512 c) 36 d) 12
Answer: (b) Reason: is right-associative: 3 2 = 9 first, then 2 ** 9 = 512.
12. x=10;x+=5;x*=2givesx= a) 25 b) 30 c) 20 d) 15
Answer: (b) Reason: x becomes 15 and then 15 × 2 = 30.
13. Python decides the type of a variable at run time. This is called a) Static typing b) Dynamic typing c) Strong typing d) Casting
Answer: (b) Reason: In dynamic typing no declaration is required; the type follows the assigned value.
14. Which of the following is NOT a Python keyword? a) elif b) lambda c) then d) pass
Answer: (c) Reason: Python has no "then"; the colon ends the if header.
15. print("5" + "3") outputs a) 8 b) 53 c) Error d) 15
Answer: (b) Reason: + joins two strings (concatenation) rather than adding numbers.
16. bool(0) returns a) True b) False c) 0 d) None
Answer: (b) Reason: Zero, empty string and empty collections are treated as False.
17. Which distribution provides Python, Jupyter and Spyder together? a) PyPI b) Anaconda c) Django d) Flask
Answer: (b) Reason: Anaconda bundles the interpreter, IDEs and scientific libraries.
18. The f-string f"{12.3456:.2f}" produces a) 12.34 b) 12.35 c) 12.3456 d) 12
Answer: (b) Reason: .2f rounds to two decimal places.
2.12 Exercises
1. Write a program to read the diameter and length of a cylinder and compute its volume and mass (density 7850 kg/m³).
2. Write a program to convert a speed in rpm into angular velocity in rad/s (ω = 2πN/60).
3. Write a program to compute the cutting speed V = πDN/1000 (m/min) for given D (mm) and N (rpm).
4. Predict the output: print(int("12") + float("2.5"), str(4) * 3, 15 // 4, -15 % 4).
5. Write a program to find the kinetic energy of a flywheel, E = ½Iω².