Python Notes and Examples

Python Language Basics

Truthiness and Falsiness

(), [], {}, set(), '', 0, 0.0, False, and None are all Falsey. Everything else is Truthy.

Equality and comparing

If they’re of the same container type, Python compares them item-by-item, and if they contain a data structure, Python dives in and compares recursively. Works for dicts and sets as well.

If two objects are of the same user-defined class, then they’re o1 == o2 only if they’re the same object.

Scoping

Python only has file/module scope (“global”), and function scope. for loops and if’s do not have their own scope.

Inside a function, use global if you need to change a global.

Inside a nested function, use nonlocal if you need to change an outer variable.

Naming Conventions

Flow Control

Notes:

  • you can chain comparisons: 2 < x < 4
  • / is true division. Use // for truncating/integer division
  • //, and % (for remainder), or use divmod() to get both together
  • exponentiation (**) has higher precedence than unary +/-, so use parens to clarify if a negative base is involved.
  • loops support break and continue
  • For empty functions and classes you can use a docstring instead of pass.

Attributes and Items

Objects can have attributes and items:

Attributes and items can be callable. Callable attributes are “methods”.

Regarding attributes, see also the functions: getattr, hasattr, setattr, and delattr.