Section 03 of 10 · 18 entries
Python reference
The parts of Python that engineering scripts lean on, with the small traps that catch everyone at least once.
Entries in Python reference
- Classes and objectsA class is a blueprint that bundles data (attributes) and behaviour (methods). Each object made from it has its own copy of the data; self refers to that object inside a method.
- Comparisons and Boolean expressionsComparisons such as a < b give True or False; and, or and not combine them. Python allows chained comparisons like 0 <= x < 10.
- DictionariesA dictionary maps keys to values, as in {"red": 2, "green": 5}, and looks values up by key in roughly constant time.
- Exceptions: try and exceptWhen something goes wrong, Python raises an exception. A try block runs risky code and an except block handles a named kind of exception instead of crashing.
- Floating-point rounding and comparisonMost decimal fractions cannot be stored exactly in binary floating point, so tiny rounding errors appear and == between floats is unreliable.|a − b| ≤ max(rel_tol × max(|a|, |b|), abs_tol)
- Floor division and moduloa // b divides and rounds down to the nearest whole number; a % b gives the remainder, so that a == (a // b) * b + a % b always holds.a = (a // b) × b + (a % b)
- for loops and rangeA for loop runs its body once for each item of a sequence. range(start, stop, step) produces whole numbers from start up to but not including stop.number of values in range(a, b, s) = ceil((b − a) / s) for b > a, s > 0
- Functions and return valuesdef name(parameters): defines a reusable block of code. Calling it runs the body with the given arguments, and return sends a value back to the caller.
- if, elif and elseif runs a block only when its condition is true; elif tests another condition if earlier ones were false; else catches everything left.
- int and floatPython's int holds whole numbers of any size exactly; float holds real numbers approximately, in 64-bit binary floating point with about 15 to 16 significant digits.
- List comprehensionsA list comprehension builds a new list from an existing sequence in one expression: [f(x) for x in items if condition].
- Lists and indexingA list is an ordered, changeable collection written in square brackets. Items are numbered from 0, and negative indices count back from the end.
- Operator precedencePython evaluates ** first, then unary minus, then *, /, // and %, then + and −, then comparisons, then not, and, or. Brackets override everything.
- SlicingA slice seq[start:stop:step] takes items from start up to but not including stop, moving step at a time; any part can be left out.number of items in seq[a:b] = b − a (for 0 ≤ a ≤ b ≤ len)
- Strings and f-stringsAn f-string, written f"…", replaces each {expression} inside it with that expression's value, optionally formatted, as in {voltage:.2f} for two decimal places.
- The math modulePython's built-in math module provides constants such as pi and e and functions such as sqrt, sin, cos, atan2, log10, hypot, radians and degrees.
- Variables and assignmentAn assignment such as speed = 2.5 makes the name speed refer to the value 2.5. The right-hand side is worked out first, then the name is attached to the result.
- while loopsA while loop repeats its body as long as its condition stays true, checking the condition before each pass.