✦ VidyaVerseOpen interactive version

← 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

CategorySyntax / example
Output, inputprint("x =", x, sep=" ", end="\n"); s = input("prompt")
Conversionint("5"), float("2.5"), str(10), round(3.142, 2)
f-stringf"{value:.2f}", f"{n:5d}", f"{name:<10}"
Operators+ − * / // % ** ; == != < > <= >= ; and or not ; in, not in
ifif c1: ... elif c2: ... else: ...
Loopsfor i in range(a, b, step): ... ; while cond: ... ; break, continue, pass
Functiondef f(a, b=2, *args, **kw): return a + b ; lambda x: x * x
ListL = [1, 2]; L.append(3); L.insert(0, 9); L.remove(2); L.pop(); L.sort(); L[1:3]
Tuplet = (3, 4); x, y = t
Dictionaryd = {"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]
Filewith open("f.txt", "w") as f: f.write("text\n")
CSVcsv.writer(f).writerows(rows); for row in csv.reader(f): ...
Exceptionstry: ... except ValueError as e: ... else: ... finally: ... ; raise
Classclass A: def __init__(self, x): self.x = x ; class B(A): super().__init__(x)
Modulesimport math as m; from random import randint
NumPynp.array, np.mean, np.std(ddof=1), np.linalg.solve, np.zeros((n, n))
Matplotlibplt.plot(x, y), plt.bar, plt.hist, plt.scatter, plt.axhline, plt.xlabel, plt.title, plt.legend, plt.grid, plt.show()
SciPy statsstats.ttest_1samp, stats.ttest_ind, stats.f_oneway
gpiozeroLED(17), Button(2), Motor(23, 24, enable=18), Robot, OutputDevice, MotionSensor(27), DistanceSensor(echo=21, trigger=20)
RPi.GPIOGPIO.setmode(GPIO.BCM); GPIO.setup(p, GPIO.OUT); GPIO.output(p, 1); GPIO.PWM(p, 1000); GPIO.cleanup()

Common errors and remedies

Error messageLikely causeRemedy
SyntaxError: expected ':'Colon missing after if/for/defAdd the colon
IndentationErrorMixed or missing indentationUse 4 spaces consistently
NameError: name 'x' is not definedSpelling/case mismatch or variable not createdCheck spelling and order
TypeError: can only concatenate strAdding string and numberConvert with str() or use f-string
ValueError: invalid literal for int()Converting text/decimal to intValidate input, use float() first
ZeroDivisionErrorDivisor is zeroCheck before dividing or use try-except
ModuleNotFoundErrorLibrary not installedpip install package / conda install
RuntimeError (DHT)Sensor timing glitchCatch and retry after 2 s
GPIO pin busy / not allowedPin used by another programStop other program, reboot, use cleanup

APPENDIX D