Iteration Statements in Python
Suppose we write a program to read students' marks, process the marks,
and print the result.
In such a program, reading and processing marks is a repeated task.
To perform such repeated operations, programming languages provide
loop structures.
In this topic, we will learn about such loop structures.
Iteration (Loop) Statements in Python
A loop is a control structure.
It is used to execute a block of code repeatedly.
That is, when the same task needs to be performed again and again,
we use loops instead of repeating code manually.
For example, let us see how a loop can be used
to find the sum of numbers from 1 to 100.
Example: Finding the sum of the first 100 natural numbers
sum = 1 + 2 + 3 + ............. + 100
If we write this directly in a program:
Step 1: Start
Step 2: sum = 0
Step 3: sum = sum + 1
Step 4: sum = sum + 2
Step 5: sum = sum + 3
...
Step 101: sum = sum + 99
Step 102: sum = sum + 100
Step 103: Print sum
Step 104: Stop
Using a loop, we can write it as:
Step 1: Start
Step 2: i = 1
Step 3: sum = 0
Step 4: Repeat Steps 5 and 6 while i <= 100
Step 5: sum = sum + i
Step 6: i = i + 1
Step 7: Print sum
Step 8: Stop
Important Parts of a Loop
-
Initialization:
Assigning an initial value to the control variable before the loop starts
(in our example,
i = 1). -
Condition:
A condition that decides how long the loop should repeat
(in our example,
i <= 100). -
Update:
Updating the control variable inside the loop
(in our example,
i = i + 1). -
Body:
The statements that need to be executed repeatedly
(in our example,
sum = sum + i).
Flowchart
Types of Loop Statements in Python
Python provides two types of loop statements:
- while loop
- for loop
What We Have Learned So Far
- Learned the basic concepts of loop statements
- while loop will be covered in the next topic