π
Python For Loops (Iteration) π
For loops are used to iterate over a sequence (like a list, tuple, string, or
range) or other iterable objects. They let you execute a block of code repeatedly for each item.
π They are essential for automating tasks and processing collections of data efficiently.
πΉ
1. What is a For Loop?A for loop executes a set of statements, once for each item in a collection.
Example:
for character in "Python":
print(character)
Output:
PythonπΉ
2. Looping Through a ListThis is one of the most common uses: going through each item in a list.
Syntax:
for item in list_name:
# code to execute for each item
Example:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"I like {fruit}.")
Output:
I like apple.I like banana.I like cherry.πΉ
3. The range() FunctionThe
range() function generates a sequence of numbers, often used to loop a specific number of times.
β’
range(stop): Numbers from 0 up to (but not including)
stop.
β’
range(start, stop): Numbers from
start up to (not including)
stop.
β’
range(start, stop, step): Numbers from
start up to
stop, increasing by
step.
Example:
for i in range(3): # Loop 3 times (0, 1, 2)
print(f"Iteration {i}")
Output:
Iteration 0Iteration 1Iteration 2πΉ
4. break and continue Statementsβ’
break: Stops the loop completely, even if the iterable hasn't finished.
β’
continue: Skips the rest of the current iteration and moves to the next.
Example (
break):
for number in range(1, 6):
if number == 4:
break # Stop when number is 4
print(number)
Output:
123Example (
continue):
for item in ["A", "B", "C", "D"]:
if item == "C":
continue # Skip 'C'
print(item)
Output:
ABDπ―
Today's Goal(What you should do)βοΈ Understand what for loops are
βοΈ Iterate over lists, strings, and ranges (using your Python editor)
βοΈ Use
break and
continue to control loop flow (using your Python editor)