Flow control

The While loop

A while loop is used to repeatedly execute a block of code as long as a given condition is True. The condition is evaluated before each iteration, and if it is True, the loop's body is executed. If the condition becomes False, the loop stops.

while condition:
    # code block to be executed

  • condition: A boolean expression that is checked before each iteration. If it evaluates to True, the loop continues; otherwise, it stops.
  • code block: The set of statements that are executed repeatedly as long as the condition is True.

Example:

i = 1
while i <= 5:
    print(i)
    i += 1  # Increment i by 1 in each iteration

Explanation:
1. The variable i is initialized to 1.
2. The loop checks if i is less than or equal to 5. If true, the block of code inside the loop is executed (in this case, print(i)).
3. After printing i, the value of i is incremented by 1 using i += 1.
4. This process repeats until i becomes 6, at which point the condition i <= 5 becomes False and the loop stops.

Output:

1
2
3
4
5


Infinite Loop

A while loop can run indefinitely if the condition never becomes False. For example:

while True:
    print("This will print forever")

To prevent infinite loops, make sure that something in the loop eventually makes the condition False.


When to use a while Loop

When the number of iterations is unknown: If you need to repeat something an indeterminate number of times until a condition changes, a while loop is suitable.

It's time to take a quiz!

Test your knowledge and see what you've just learned.

What is the basic structure of a while loop in Python?

for condition in range: code block
while condition: code block
while code block: condition
do while condition: code block
Check Answer

When is the condition evaluated in a while loop?

At the end of the loop
After the loop is executed
Before each iteration of the loop
Only once at the start
Check Answer

What can cause a while loop to run indefinitely?

The condition never becomes False
The condition becomes True
The loop body is empty
The loop counter is decremented
Check Answer

How can you prevent an infinite loop in a while statement?

Always set the condition to True
Ensure the loop modifies the condition
Avoid using break statements
Use a for loop instead
Check Answer

When should you use a while loop?

When you want to iterate over a sequence
When you want to break out of a loop
When the number of iterations is unknown
When you need a fixed number of iterations
Check Answer