Python Language Basics
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
= 1
some_var = 2 # Also common.
someVar
class SomeClass:
pass
# Implementation detail. Clients shouldn't use this variable.
= 42
_yo
# Private. Compiler helps you a little here by obfuscating
# the name to avoid clients accidentally using it.
= 88 __za
Flow Control
Notes:
- you can chain comparisons:
2 < x < 4
/
is true division. Use//
for truncating/integer division//
, and%
(for remainder), or usedivmod()
to get both together- exponentiation (
**
) has higher precedence than unary+
/-
, so use parens to clarify if a negative base is involved. - loops support
break
andcontinue
- For empty functions and classes you can use a docstring instead of
pass
.
# Ternary operator:
= expr1 if some_condition else expr2 x
Attributes and Items
Objects can have attributes and items:
# Access an attribute:
# `x` is the attribute name.
a.x
# Access an item:
# `x` is the index or key, and `a` is the item's container. a[x]
Attributes and items can be callable. Callable attributes are “methods”.
Regarding attributes, see also the functions: getattr
, hasattr
, setattr
, and delattr
.