Lesson 09 of 55
8 mins readPython While Loops & State Iteration
In Plain English
Execute code repeatedly while a boolean condition remains true. Essential for numerical convergence, iterative algorithms, and search procedures.
Deep Dive: How It Works
While Syntax: while condition ... end executes the body as long as condition evaluates to true.
Scope of Variables: In Julia, loops introduce a local variable scope. When mutating outer variables, understand global or function-local variable bindings.
Numerical Convergence: Repeatedly iterate until an approximation error abs(curr - prev) falls below a tolerance threshold ϵ.
Core Rules to Remember

Condition-Driven Iteration: Ideal when the exact number of iterations is not known in advance.

Convergence Testing: Compute numerical approximations (e.g. Newton-Raphson square root).
Live Interactive Example
Hit Run Code to see it liveNewton-Raphson Square Root Approximation
Python 3.12
1
2
3
4
5
6
7
8
9
10
11
12
Output Console
Click "Run Code" to view the rendered output.
How it works: The while loop iteratively refines x until abs(x^2 - 25) <= 1e-7.
Your Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Micro Exercise
Countdown Simulation
Define a function `countdown(start_val)` that initializes `count = start_val`.
Use a `while count > 0` loop to decrement `count` and finally print `"Liftoff!"`.
Run `countdown(3)`.
1
2
3
4
5
6
7
8
9
10
Sandbox Output
Click "Run & Check" to test your solution.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.