Python Looping Statements
Nafeesath Shamuda K
Grade : 12
Introduction to Loops
Definition Purpose
Loops are programming They help automate and
constructs that allow simplify tasks that require
repetition of a set of repeated execution,
statements multiple times reducing code redundancy
based on a condition. and improving efficiency.
Types in Python
Python primarily uses two types of loops: 'for' loops and 'while'
loops, each suited for different scenarios.
For Loop
Definition Syntax
The 'for' loop in Python is used to iterate over a sequence for item in sequence:
(such as a list, tuple, string) or other iterable objects. It # code block to be executed
executes a block of code for each item in the sequence.
For Loop Flowchart
1 Start
Begin the loop process
2 Initialize Loop Variable
Set the initial value for the loop variable
3 Check Condition
Verify if there are more items in the sequence
4 Execute Code Block
If condition is true, execute the loop body
5 Increment
Move to the next item in the sequence
6 End
Exit the loop when no more items are left
For Loop Example
Scenario Code Output
Printing squares of numbers from 1
for i in range(1, 6): 1 squared is 1
to 5 print(f"{i} squared is 2 squared is 4
{i**2}") 3 squared is 9
4 squared is 16
5 squared is 25
While Loop
Definition Syntax
The 'while' loop in Python repeatedly executes a block of while condition:
code as long as a given condition is true. It's particularly # code block to be executed
useful when the number of iterations is unknown
beforehand.
While Loop Flowchart
1 Start
Begin the loop process
2 Check Condition
Evaluate the loop condition
3 Execute Code Block
If condition is true, execute the loop body
4 Update Condition
Modify the condition-controlling variable
5 Repeat
Go back to condition check
6 End
Exit the loop when condition becomes false
While Loop Example
Scenario Code Output
Countdown from 5 to 1
count = 5 5
while count > 0: 4
print(count) 3
count -= 1 2
print("Blastoff!") 1
Blastoff!
Conclusion and Key
Takeaways
1 Versatility 2 For Loop Usage
Both 'for' and 'while' loops Ideal for iterating over
offer powerful iteration sequences with a known
capabilities in Python, each number of iterations.
suited for different
scenarios.
3 While Loop Usage 4 Practice
Perfect for situations Regular practice with both
where the number of loop types will enhance
iterations is unknown and your programming skills
depends on a condition. and problem-solving
abilities.
Any Questions?
Ask Now