← Programming Concepts in Mechanical Engineering (25ME34I)
Python Quick Reference
Programming Concepts in Mechanical Engineering (25ME34I) · C-25 Diploma Mechanical, Semester III
Read with diagrams, search and self-test
| Category | Syntax / example |
|---|---|
| Output, input | print("x =", x, sep=" ", end="\n"); s = input("prompt") |
| Conversion | int("5"), float("2.5"), str(10), round(3.142, 2) |
| f-string | f"{value:.2f}", f"{n:5d}", f"{name:<10}" |
| Operators | + − * / // % ** ; == != < > <= >= ; and or not ; in, not in |
| if | if c1: ... elif c2: ... else: ... |
| Loops | for i in range(a, b, step): ... ; while cond: ... ; break, continue, pass |
| Function | def f(a, b=2, *args, **kw): return a + b ; lambda x: x * x |
| List | L = [1, 2]; L.append(3); L.insert(0, 9); L.remove(2); L.pop(); L.sort(); L[1:3] |
| Tuple | t = (3, 4); x, y = t |
| Dictionary | d = {"E": 200}; d["G"] = 80; d.get("nu", 0.3); del d["E"]; d.items() |
| Comprehension | [x**2 for x in range(5) if x % 2 == 0] |
| File | with open("f.txt", "w") as f: f.write("text\n") |
| CSV | csv.writer(f).writerows(rows); for row in csv.reader(f): ... |
| Exceptions | try: ... except ValueError as e: ... else: ... finally: ... ; raise |
| Class | class A: def __init__(self, x): self.x = x ; class B(A): super().__init__(x) |
| Modules | import math as m; from random import randint |
| NumPy | np.array, np.mean, np.std(ddof=1), np.linalg.solve, np.zeros((n, n)) |
| Matplotlib | plt.plot(x, y), plt.bar, plt.hist, plt.scatter, plt.axhline, plt.xlabel, plt.title, plt.legend, plt.grid, plt.show() |
| SciPy stats | stats.ttest_1samp, stats.ttest_ind, stats.f_oneway |
| gpiozero | LED(17), Button(2), Motor(23, 24, enable=18), Robot, OutputDevice, MotionSensor(27), DistanceSensor(echo=21, trigger=20) |
| RPi.GPIO | GPIO.setmode(GPIO.BCM); GPIO.setup(p, GPIO.OUT); GPIO.output(p, 1); GPIO.PWM(p, 1000); GPIO.cleanup() |
Common errors and remedies
| Error message | Likely cause | Remedy |
|---|---|---|
| SyntaxError: expected ':' | Colon missing after if/for/def | Add the colon |
| IndentationError | Mixed or missing indentation | Use 4 spaces consistently |
| NameError: name 'x' is not defined | Spelling/case mismatch or variable not created | Check spelling and order |
| TypeError: can only concatenate str | Adding string and number | Convert with str() or use f-string |
| ValueError: invalid literal for int() | Converting text/decimal to int | Validate input, use float() first |
| ZeroDivisionError | Divisor is zero | Check before dividing or use try-except |
| ModuleNotFoundError | Library not installed | pip install package / conda install |
| RuntimeError (DHT) | Sensor timing glitch | Catch and retry after 2 s |
| GPIO pin busy / not allowed | Pin used by another program | Stop other program, reboot, use cleanup |
APPENDIX D