Lesson 3.2: Loops – for Loop
Introduction:
Loops allow programs to execute a block of code repeatedly, saving time and effort. The for loop in Python is used to iterate over sequences such as lists, tuples, strings, or ranges. Mastering loops is essential for automating repetitive tasks and building efficient programs.
1. The for Loop Syntax:
Explanation:
-
variabletakes each value from the sequence one by one -
The block of code under the loop executes for each item in the sequence
2. Example – Iterating over a List:
Output:
3. Example – Using range() with for Loop:
-
range()generates a sequence of numbers.
Output:
-
Using
range(start, stop, step)
Output:
4. Nested for Loops:
-
A
forloop inside anotherforloop is called a nested loop.
Practical Tips:
-
Loops can be combined with conditional statements for more complex logic.
-
Use descriptive variable names for better readability.
-
Avoid infinite loops with proper sequence or range limits.
Learning Outcome of This Lesson:
-
Understand the purpose and syntax of the
forloop -
Iterate over sequences like lists, strings, and ranges
-
Use nested loops for advanced scenarios
-
Automate repetitive tasks efficiently in Python
