Python Notes and Examples

Python Language Basics

John Gabriele

2023-12

Truthiness and Falsiness

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

Equality and comparing

>>> ('a', 'b', 'c') == ['a', 'b', 'c']
False

>>> list(('a', 'b', 'c')) == ['a', 'b', 'c']
True

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.

>>> a = [1, 2, [11, 12], 100]
>>> b = [1, 2, [11, 12], 100]
>>> a == b
True
>>> a[2][1] = 122
>>> a
[1, 2, [11, 122], 100]
>>> a == b
False

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

some_var = 1
someVar  = 2  # Also common.

class SomeClass:
    pass

# Implementation detail. Clients shouldn't use this variable.
_yo = 42

# Private. Compiler helps you a little here by obfuscating
# the name to avoid clients accidentally using it.
__za = 88

Flow Control

Notes:

# Ternary operator:
x = expr1 if some_condition else expr2

Attributes and Items

Objects can have attributes and items:

# Access an attribute:
a.x  # `x` is the attribute name.

# Access an item:
a[x] # `x` is the index or key, and `a` is the item's container.

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

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