๐ Phase 1: Programming Fundamentals
๐ Topic 5: Python Loops ("for" & "while")
Welcome back! ๐
In the previous lesson, you learned how Python makes decisions using if, elif, and else. Now it's time to learn how to repeat tasks automatically using loops.
Loops are one of the most powerful concepts in Python. Instead of writing the same code multiple times, you can use loops to execute a block of code repeatedly.
In Data Science, loops are commonly used to process datasets, automate repetitive tasks, iterate through lists, and build machine learning workflows.
๐น 1. What is a Loop?
A loop is used to execute a block of code multiple times until a condition is met.
Without loops:
print("Hello")
print("Hello")
print("Hello")
print("Hello")
print("Hello")Using a loop:
for i in range(5):
print("Hello")
Both produce the same output, but the loop is much shorter and easier to maintain.
๐น 2. Types of Loops in Python
Python provides two main types of loops:
โ "for" Loop
โ "while" Loop
๐น 3. The "for" Loop โญ
A "for" loop is used when you know how many times you want to repeat a task.
Syntax
for variable in sequence:
# Code to execute
Example
for i in range(5):
print(i)
Output:
0
1
2
3
4
Notice that
range(5) generates numbers from 0 to 4.๐น 4. The "range()" Function โญ
The
range() function generates a sequence of numbers.Example 1
for i in range(5):
print(i)
Output:
0 1 2 3 4Example 2
for i in range(1, 6):
print(i)
Output:
1 2 3 4 5Example 3
for i in range(2, 11, 2):
print(i)
Output:
2 4 6 8 10 The third argument is called the step size.
๐น 5. Looping Through a List
fruits = ["Apple", "Banana", "Mango"]
for fruit in fruits:
print(fruit)
Output:
Apple
Banana
Mango
๐น 6. The "while" Loop โญ
A "while" loop continues executing as long as the condition remains True.
Syntax
while condition:
# Code
Example
count = 1
while count <= 5:
print(count)
count += 1
Output:
1 2 3 4 5๐น 7. Infinite Loop
Be careful when using "while" loops.
while True:
print("Hello")
This loop never stops unless interrupted.
Always ensure the condition eventually becomes False.
๐น 8. Loop Control Statements โญ
"break" - Stops the loop immediately
for i in range(10):
if i == 5:
break
print(i)
Output:
0 1 2 3 4"continue" - Skips the current iteration
for i in range(5):
if i == 2:
continue
print(i)
Output:
0 1 3 4"pass" - Acts as a placeholder
for i in range(5):
pass
Useful when writing incomplete code.
๐น 9. Nested Loops
A loop inside another loop.
for i in range(3):
for j in range(2):
print(i, j)
Output:
0 0
0 1
1 0
1 1
2 0
2 1
๐น 10. Real-World Data Science Example
Calculate the total sales.