Introduction to While Loops
Iteration is the act of repeating a mathematical or computational process. Each repeated step in iteration is also called an iteration.
While Loops
While loops are our very first iteration statements that we can incorporate into our program. It behaves very similar to an if statement; however, a while loop will repeat its code block when its condition evaluates to True.
We can use while loops to complete repetitive tasks, generate ranges of values, and express algorithms.
When a while loop reaches the end of its code block, it will always re-evaluate its Boolean condition.
If the condition is
True
, it will execute its code block againIf the condition is
False
, it will ignore the code block and continue on with the flow of the program.
Example: Printing Factors of a Number
Code Explanation:
We only repeat the while loop’s code block if divisor is less or equal to num.
During every iteration, we are checking a condition
If the condition is
True
, we output the factor
To make sure we exit the loop eventually, we are modifying divisor variable so that the while loop’s condition will evaluate to
False
Python Specific: While … Else Structure
There is no elif
for while loops, but we can add an else
statement to make sure to execute certain code block when the while loop’s condition evaluates to False.
Examine the while loop’s condition.
Currently
num
is an odd number; therefore,num % 2 == 0
will never be True.In this situation, we go into the
else
statement to execute the code block
The code above has a while loop that starts with its condition evaluating to
True
.This allows the while loop to execute its code block until the condition evaluates to
False
.Once the condition becomes
False
, we execute theelse
code block as well.
Last updated