Home > Python > Introduction to Python

Ch. 1.6 While Loop

Chapters Index
Program 1

While Loop

Python 3.11 Ready

                                
Click "Run Code" to execute script and render figures.

Mathematical Problem Formulation

Understanding While Loops in Python

Initialize a Variable:

The variable i is set to 1.

While Loop:

The loop runs as long as condition is True i.e. in current case i is less than or equal to 5.

Print Statement:

It prints the current iteration number (e.g., "This is iteration number 1").

Increment:

The value of i increases by 1 in each iteration to prevent an infinite loop.

Program 2

While Loop

Python 3.11 Ready

                                
Click "Run Code" to execute script and render figures.
Program 3

While Loop

Python 3.11 Ready

                                
Click "Run Code" to execute script and render figures.
Program 4

While Loop

Python 3.11 Ready

                                
Click "Run Code" to execute script and render figures.
Theoretical Principles & Computational Physics Guide

While Loop: Indefinite Iteration & Convergence Thresholds

Dr. Alorika Chatterjee & Dr. Anirban Shaw Science & Physics Learners Python 3 / NumPy / SciPy

1. Core Principles & Theoretical Framework

Convergence Control: Repeats calculations until an error tolerance $|x_{k+1} - x_k| < \epsilon_{\text{tol}}$ is satisfied.
Stopping Conditions: Ideal for root-finding, iterative relaxation, and trajectory termination (e.g. projectile ground impact).
Safety Guards: Includes iteration caps (max_iter) to prevent infinite loops when convergence fails.

2. Mathematical Formulation & Algorithmic Pipeline

Convergence criterion for iterative scientific algorithms:

$$ |x_{k+1} - x_k| < \epsilon_{\text{tol}} \quad \text{or} \quad \frac{|x_{k+1} - x_k|}{|x_{k+1}|} < \epsilon_{\text{rel}} $$

3. Numerical Mechanics & Implementation Logic

  • State Initialization: Define initial guess $x_0$, tolerance $\epsilon$, and loop counter $k = 0$.
  • Iterative Advancement: Compute $x_{k+1} = g(x_k)$ and calculate absolute/relative discrepancy.
  • Break Condition: Exit when tolerance is reached or iteration limit $k \ge k_{\max}$ is exceeded.

4. Relevant Computational Practice Exercises

Exercise 1
Implement the Babylonian method to find $\sqrt{S}$ using $x_{k+1} = \frac{1}{2}(x_k + S/x_k)$ until $|x_{k+1} - x_k| < 10^{-10}$.
Exercise 2
Simulate radioactive decay $N(t + \Delta t) = N(t) - \lambda N(t) \Delta t$, continuing until $N(t) \le 0.01 N_0$.
Exercise 3
Compute projectile flight time under quadratic air drag, stopping when height $y(t) \le 0$.
Standard Literature & References:
  • William H. Press et al., "Numerical Recipes", Cambridge University Press (2007).