Exercise 2: A while Loop Whose Body Never Runs — Possible Solution ==================================================================== THE PROGRAM ------------------------------ var i = 10; while (i < 5) { print 1 / 0; } print "after"; RESULT ------------------------------ ['after'] No error. The division by zero inside the loop body never happens. WHY THIS WORKS ------------------------------ def visit_while_stmt(self, stmt): while is_truthy(stmt.condition.accept(self)): stmt.body.accept(self) Python's own `while` construct checks its condition BEFORE running the loop body for the first time -- this is true of Python's `while` regardless of what's inside `visit_while_stmt`, and Wisp's own while loop inherits that behavior for free by being implemented as a real Python while loop. `stmt.condition.accept(self)` evaluates `i < 5`, which is `10.0 < 5.0` -- False. `is_truthy(False)` is False. The loop condition of the Python `while` statement itself is therefore False on the very first check, so `stmt.body.accept(self)` -- the line that would evaluate `print 1 / 0;` -- is never reached. Not "reached and somehow safe," but genuinely never executed at all. WHY THIS IS THE SAME PRINCIPLE AS if AND Logical ------------------------------ All three control-flow constructs in this chapter share one property: the code they're guarding is written down in the AST, fully parsed, completely valid -- and yet may never actually run, depending on a condition checked first. `if`'s else-branch, `Logical`'s right-hand operand, and `while`'s own loop body are all "reachable in the source text" without being "guaranteed to execute." A crash hiding inside any of them is invisible until the specific condition that would trigger it actually occurs -- which is exactly why Chapter 6's own short- circuit verification and this exercise both work the same way: put something that would obviously fail on the side that's supposed to be skippable, then confirm the failure never happens. If it had crashed here, that would mean visit_while_stmt was evaluating the body before checking the condition, or checking it with the wrong sense (running while the condition is FALSE instead of while it's TRUE) -- either would be a real, structural bug in the interpreter, not a fluke of this particular program's numbers.