Iterative Statements
M3-R5.1 · Chapter 4: Operators, Expressions and Python Statements · 4 min read
Iteration Statements (Loops)
Definition
Iteration statements, also known as loops, are a fundamental concept in Python that allow you to execute a block of code repeatedly. This repetition can be based on a condition or a sequence of items.
In simpler words: Looping means repeating something over and over until a particular condition is satisfied.
Types of Loops in Python
There are two main types of loops used for iteration in Python:
Note: This chapter focuses on Type I — the while loop. The for loop are covered in later sections.
Type I: The while Loop
What is a while Loop?
The while loop in Python is used to repeat a block of code as long as a condition is True. It is used when you do not know in advance how many times the loop needs to run.
The while keyword is followed by a Boolean expression and a colon, which starts an indented block of statements. The loop iterates while the expression is True. As soon as the expression becomes False, control passes to the line immediately following the loop.
Note - The while loop is also known as: Indefinite Iteration Loop | Condition-Controlled Loop | Entry-Controlled Loop
Syntax
while expression:
statement(s) # block of code
updation # optional but important
How the while Loop Executes — Step by Step
Anatomy of a while Loop
Worked Example
Printing Numbers 1 to 5
# Initialization
number = 1
while number <= 5: # Condition
print(number) # Body
number += 1 # Update
Output-
1
2
3
4
5
Step-by-Step Explanation
- The loop starts with number = 1 (initialization).
- Before each pass, it checks if number <= 5 is True (condition check).
- If True → the loop prints the current value of number (body executes).
- Then number += 1 increases the value by 1 (update expression).
- When number becomes 6, the condition is False → loop ends.
Important Notes & Key Rules
Rule 1: Always initialize the loop variable before the loop begins. An uninitialized variable cannot be used in expressions.
Rule 2: Always update the loop variable inside the body so the condition eventually becomes False.
Rule 3: If the condition never becomes False, you get an infinite loop — the program runs forever.
Rule 4: The while loop is an entry-controlled loop — the condition is checked BEFORE entering the body. If the condition is False from the start, the body never runs.
Rule 5: The condition can be any expression. Any non-zero value is treated as True.
What is an Infinite Loop?
An infinite loop occurs when the loop condition never becomes False. This usually happens when the update expression is missing or incorrect.
# DANGER: Infinite loop — no update expression!
number = 1
while number <= 5:
print(number)
# number is never updated — loop runs forever!
Note - Always make sure your update expression changes the loop variable in a way that will eventually make the condition False. This prevents infinite loops.