CWIIP study materials
CWIIP study resources

CWIIP: Python Programming Fundamentals

CWIIP · Work through your exam, one topic at a time.

All guide sections

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.3 in 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 with is (reserve is for None).
  • Slicing seq[a:b:c] excludes b; negative indices count from the end; seq[::-1] reverses.
  • Truthiness: 0, "", [], {}, set(), None and False are falsy.

Functions and scope

  • Default arguments are evaluated once at definition time. def add(x, items=[]) shares one list across calls - use items=None then items = items or [].
  • *args collects positional extras as a tuple, **kwargs collects 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 bare except. else runs when no exception occurred; finally always runs.
  • with open(...) as f guarantees closing. json.dumps/json.loads for 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.
  • is used 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.