% class-3 talking points repetition.py for for ...: draws an element from a collection at start of each iteration range(n) is [0, ..., n-1] Use 'for' when you know in advance how many times (which elements) you want to iterate. Example: counters, process all the items in a collection 'Guaranteed' to terminate (almost...) Note *= idiom. while while ...: tests condition at start of each iteration Use while when you do *not* know how many times (which elements) you want to iteration. Examples: successive approximation (square root in textbook) while is more general than for (can always express 'for' as 'while', but not always vice-versa) while is more error-prone, requires some care to terminate, loop body must make progress, potential error: infinite loops (demo) recursion Most general - we don't need loops at all, could always express any repetition by recursion - "functional programming" You must have a base case to break the recursion! recursive case must make progress toward base case, potential error: infinite recursion (demo) Recursion is most helpful with nested data structures - we'll see in a few weeks (after the quiz) Debugger Debugger tool is alternative to print statements 'Debugging' *activity* is much more than using the debugger *tool*. Texbook has lots of good advice about debugging, nothing about debugger. Demo: IDLE debugger, also python debugger pdb: import pdb, pdb.run('...'), s (step) p (print) h (help) Occasionally useful but I usually resort to print statements, finer control Assertions are also useful -- we'll discuss after the break (after break) assertions.py This is CS foundations, not just Python How do they come up with those amazing algorithms? We'll look at simple example - integer division (like in Python) (demo) this is actually necessary on some small uP - 8-bit and embedded have sw div. Use assertions - Boolean expressions that are intended to be true at some point Preconditions (before, inputs), postconditions (after, outputs w.r.to inputs) Invariants (relation among variables remains true *despite* changes in values) Can design loops from template based around assertions Pre/Post comprise a *formal specification* pre => post (no guarantees if not pre, show quotient example, demo) assert is a python statement! (uncomment pre assert, show it explains problem) use python -O to turn off assertion checking (demo in command window) asserts are built-in run-time checks (like test cases but can be more powerful)