Intermediate·18 min·0/47 done

Keywords, operators, and exceptions reference

Reserved keywords, operators worth knowing, and which exceptions to catch.

Why it matters: Clear exception types and correct operators keep training and API wrappers from failing silently.

Basics

Keywords to remember

Reserved names cannot be variables: if, for, def, class, try, with, yield, async, await, and more.

  • pass - empty block placeholder
  • assert - debug only; stripped with python -O (do not use for security checks)
  • with - guaranteed cleanup
  • yield - makes a generator

match / case are soft keywords (3.10+).

Tiny example

pass and an is not None check.

value = 0
if value is not None:
    pass
print("zero is falsy:", not value)

Basics

Operators

Arithmetic: + - * / // % **. Comparisons chain: 0 <= x <= 1.

Use is only with None, True, False. Use == for values.

Walrus := assigns inside an expression: if (n := len(xs)) > 3:.

When unsure about precedence, add parentheses.

Tiny example

== compares values; is compares identity.

a = [1, 2]
b = [1, 2]
print(a == b, a is b)
print(2 + 3 * 4)

Basics

Exceptions

Catch Exception, not BaseException (that would swallow Ctrl+C).

Common: ValueError, TypeError, KeyError, IndexError, AttributeError, FileNotFoundError, TimeoutError.

Catch specific types. Use raise ... from err when wrapping. Define RetryableError vs fatal errors for flaky LLM APIs.

Tiny example

Catch ValueError from a bad float parse.

raw = "hot"
try:
    print(float(raw))
except ValueError as err:
    print("caught", type(err).__name__)

Then AI / ML

AI / ML examples

Same idea, used in real AI work. Press Try in lab to run it.

AI / ML example

AI / ML: retryable vs fatal errors

Mark what is safe to retry.

In AI / ML: LLM clients separate 429/5xx from 401/400.

example.py

Python

class RetryableError(Exception):
    pass

class FatalError(Exception):
    pass

def call_model(status):
    if status == 429:
        raise RetryableError("rate limited")
    if status == 401:
        raise FatalError("bad key")
    return {"ok": True}

for status in [200, 429, 401]:
    try:
        print(status, call_model(status))
    except RetryableError as err:
        print(status, "RETRY", err)
    except FatalError as err:
        print(status, "ABORT", err)

AI / ML example 2

AI / ML: walrus in a length check

Assign and test in one expression.

In AI / ML: Batch-size guards and context-window checks use this pattern.

example.py

Python

values = [3, 14, 7, 22, 5]
if (count := len(values)) > 3:
    print(f"{count} values")
filtered = [y for x in values if (y := x * 2) > 10]
print(filtered)

Takeaways

  • 1Use is only with None/True/False; use == for values.
  • 2Never use assert for real validation.
  • 3Catch specific exceptions and mark what is retryable.
Certificate