Python Programming Fundamentals
What this domain tests
CWIIP checks that you can read and write the Python that actually appears in IoT integration code: data structures, functions, exceptions, files, JSON and time handling. Expect short code-reading questions where one subtle detail decides the answer.
Data types and mutability
- int is arbitrary precision;
/yields float,//floor division,%modulo,**power.0.1 + 0.2 != 0.3in float; compare with tolerance. - Immutable: int, float, str, tuple, frozenset. Mutable: list, dict, set. Mutables passed to functions can be changed in place.
- Compare values with
==, identity withis(reserveisforNone). - Slicing
seq[a:b:c]excludesb; negative indices count from the end;seq[::-1]reverses. - Truthiness:
0,"",[],{},set(),NoneandFalseare falsy.
Functions and scope
- Default arguments are evaluated once at definition time.
def add(x, items=[])shares one list across calls - useitems=Nonethenitems = items or []. *argscollects positional extras as a tuple,**kwargscollects keywords as a dict.- LEGB lookup: local, enclosing, global, builtin. Closures over loop variables bind late - capture with a default argument or
functools.partial. - Comprehensions build lists/dicts concisely; generators (
yield) stream data without holding it all in memory.
Errors, files and data
try/except/else/finally; catch specific exceptions, never a bareexcept.elseruns when no exception occurred;finallyalways runs.with open(...) as fguarantees closing.json.dumps/json.loadsfor payloads.- Use timezone-aware UTC datetimes (
datetime.now(timezone.utc)); naive timestamps cause ordering bugs across devices. - Never mutate a list while iterating it; iterate a copy or build a new list.
Worked example
def record(reading, log=[]):
log.append(reading)
return log
record(1) returns [1], and record(2) returns [1, 2] - not [2]. The default list is created once when the function object is defined, so every call without an explicit log reuses it. Fix: def record(reading, log=None): log = [] if log is None else log. This bug is dangerous in IoT because a batch buffer silently accumulates across devices.
Traps
- Mutable default arguments.
isused to compare strings or numbers.- Integer division surprises when converting raw ADC values.
- Bare
except:hiding a broker connection failure. - Iterating and removing from the same list.