Loops and Iteration in Python
Foundations of Loops and Repeated Steps
Concept of Repeated Steps:
In computer programming, loops facilitate repetitive execution of statements until a termination condition is satisfied.
Code execution flows sequentially into the loop, executes a designated body of code, checks an expression, and repeats or branches away based on the result.
Iteration Variables:
Loops (repeated steps) rely on iteration variables that change each time through a loop.
These variables frequently progress through a defined numerical sequence to track progress and regulate execution count.
Countdown while Loop Implementation:
A countdown program demonstrates repeated execution using the
whileconstruct:python n = 5 while n > 0 : print(n) n = n - 1 print('Blastoff!') print(n) Step-by-step trace of variable state and terminal output:
Initial state: .
Evaluation 1: () is
True; prints5; decrements to .Evaluation 2: () is
True; prints4; decrements to .Evaluation 3: () is
True; prints3; decrements to .Evaluation 4: () is
True; prints2; decrements to .Evaluation 5: () is
True; prints1; decrements to .Evaluation 6: () evaluates to
False; loop terminates.Exiting the loop triggers
print('Blastoff!')followed byprint(n), which outputs0.Complete program console output:
text 5 4 3 2 1 Blastoff! 0

Indefinite Loops and Edge Cases
Definition of Indefinite Loops:
whileloops are designated as "indefinite loops" because they keep executing iteratively until a governing logical condition evaluates toFalse.In contrast to loops with a fixed count, their runtime duration depends on changing conditions within the program.
While many simple loops can be verified for termination upon inspection, determining whether an indefinite loop will ultimately terminate or run perpetually can become non-trivial in complex logic.
Infinite Loops:
An infinite loop occurs when the loop condition never transitions to
False.Code demonstrating an infinite loop:
python n = 5 while n > 0 : print('Lather') print('Rinse') print('Dry off!') Flaw analysis:
The variable is initialized to .
The loop condition continuously evaluates to
Truebecause neitherprint('Lather')norprint('Rinse')alters the state of .Because never changes, the condition never becomes
False, and execution never escapes toprint('Dry off!').

Zero-Iteration (Zero-Trip) Loops:
A loop does not execute its body even once if the initial test evaluates to
False.Code demonstrating a zero-iteration loop:
python n = 0 while n > 0 : print('Lather') print('Rinse') print('Dry off!') Behavior analysis:
is assigned the value .
Upon initial evaluation, () is immediately
False.The body containing
print('Lather')andprint('Rinse')is bypassed entirely.Control branches directly to
print('Dry off!').

Loop Control Statements: break and continue
The break Statement:
The
breakstatement immediately terminates the active loop and jumps execution directly to the statement immediately following the loop body.It serves as a dynamic loop escape test that can be situated at any location within the body of the loop, rather than strictly at the top.
Implementation of an interactive prompt using
while Trueandbreak:python while True: line = input('> ') if line == 'done': break print(line) print('Done!') Interactive execution transcript:
Prompt:
> hello thereOutput:hello therePrompt:
> finishedOutput:finishedPrompt:
> doneLoop terminates immediately, skippingprint(line)and executingprint('Done!')Output:Done!

The continue Statement:
The
continuestatement prematurely ends the current iteration and immediately jumps to the top of the loop to re-evaluate the loop test and begin the next iteration.Unlike
break,continuedoes not terminate the loop entirely.Combined implementation using
continue(to ignore comment lines starting with#) andbreak(usinginputor legacyraw_input):python while True: line = input('> ') # or raw_input('> ') if line[0] == '#': continue if line == 'done': break print(line) print('Done!') Step-by-step trace of user interaction:
Prompt:
> hello thereFirst character is not'#'; condition is not'done'; outputshello there.Prompt:
> # don't print thisConditionline[0] == '#'evaluates toTrue; triggerscontinue; execution abandons remaining lines in the body and cycles back to the top of the loop.Prompt:
> print this!Evaluates standard flow; outputsprint this!.Prompt:
> doneTriggersbreak; exits loop; outputsDone!.

Definite Loops and the for Construct
Characteristics of Definite Loops:
Definite loops are designed to run an exact, predetermined number of times.
They operate over finite sets, collections, lists of items, or lines within a data file.
Python utilizes the
forconstruct to implement definite loops.Core operational maxim: "Definite loops iterate through the members of a set."
Numerical Definite Loop Example:
Definite loops can iterate directly over a list of literal values:
for i in [5, 4, 3, 2, 1]: print(i) print('Blastoff!') ``` - Terminal output sequence:text 5 4 3 2 1 Blastoff! ```
String Definite Loop Example:
Iterating over an ordered collection of string objects:
friends = ['Joseph', 'Glenn', 'Sally'] for friend in friends: print('Happy New Year:', friend) print('Done!') ``` - Console output:text Happy New Year: Joseph Happy New Year: Glenn Happy New Year: Sally Done! ```
Mechanics of Iteration Variables and the in Keyword:
Definite loops utilize explicit iteration variables (e.g., ,
friend) that automatically advance each time through the loop.The iteration variable "iterates" through the sequence (an ordered set).
The block (body) of code executes once for every individual value present in the sequence.
The variable moves through all items sequentially until every element has been processed, after which the loop condition (
Done?) evaluates toYesand execution exits the construct.
