Skip to content
Tactiverge

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

  1. 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.
  2. 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.
  3. DictionariesA dictionary maps keys to values, as in {"red": 2, "green": 5}, and looks values up by key in roughly constant time.
  4. 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.
  5. 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)
  6. 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)
  7. 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
  8. 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.
  9. 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.
  10. 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.
  11. List comprehensionsA list comprehension builds a new list from an existing sequence in one expression: [f(x) for x in items if condition].
  12. 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.
  13. Operator precedencePython evaluates ** first, then unary minus, then *, /, // and %, then + and −, then comparisons, then not, and, or. Brackets override everything.
  14. 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)
  15. 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.
  16. 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.
  17. 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.
  18. while loopsA while loop repeats its body as long as its condition stays true, checking the condition before each pass.