Day 3: Loops (for and while)
Welcome to Day 3 of your 180-day AI and Machine Learning journey! Today, we’ll explore loops in Python, which allow you to repeat a block of code multiple times. Loops are essential for automating repetitive tasks, such as processing data, training models, or iterating through lists. By the end of this article, you’ll understand how to use for and while loops effectively.
What Are Loops?
Loops are used to execute a block of code repeatedly until a certain condition is met. There are two main types of loops in Python:
forloops: Iterate over a sequence (e.g., a list, tuple, or string).whileloops: Repeat a block of code as long as a condition isTrue.
The for Loop
The for loop is used to iterate over a sequence (like a list or string) and execute a block of code for each item in the sequence.
Syntax:
for item in sequence:
# Code to execute for each itemExample:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)Output:
apple
banana
cherryThe loop iterates over each item in the
fruitslist and prints it.
Using range() in for Loops
The range() function generates a sequence of numbers, which is useful for iterating a specific number of times.
Example:
for i in range(5):
print(i)Output:
0
1
2
3
4range(5)generates numbers from 0 to 4 (5 is not included).
You can also specify a start, stop, and step:
for i in range(2, 10, 2):
print(i)Output:
2
4
6
8This loop starts at 2, ends at 10 (exclusive), and increments by 2.
The while Loop
The while loop repeats a block of code as long as a condition is True.
Syntax:
while condition:
# Code to execute while condition is TrueExample:
count = 0
while count < 5:
print("Count:", count)
count += 1Output:
Count: 0
Count: 1
Count: 2
Count: 3
Count: 4The loop continues until
countis no longer less than 5.
Loop Control Statements
Python provides control statements to modify the behavior of loops:
break: Exits the loop immediately.continue: Skips the rest of the code in the current iteration and moves to the next iteration.pass: A placeholder that does nothing (used when syntax requires a statement but no action is needed).
Example of break:
for i in range(10):
if i == 5:
break
print(i)Output:
0
1
2
3
4The loop stops when
iequals 5.
Example of continue:
for i in range(5):
if i == 2:
continue
print(i)Output:
0
1
3
4The loop skips printing
2.
Example of pass:
for i in range(3):
if i == 1:
pass # Do nothing
print(i)Output:
0
1
2The
passstatement is a placeholder and does nothing.
Nested Loops
You can place one loop inside another to create nested loops. This is useful for working with multi-dimensional data, such as matrices.
Example:
for i in range(3):
for j in range(2):
print(f"i={i}, j={j}")Output:
i=0, j=0
i=0, j=1
i=1, j=0
i=1, j=1
i=2, j=0
i=2, j=1The outer loop runs 3 times, and for each iteration, the inner loop runs 2 times.
Practice Exercise
Write a
forloop to print all even numbers between 1 and 20.Write a
whileloop to calculate the sum of numbers from 1 to 10.Use a nested loop to print the following pattern:
*
**
***
****
*****Solution:
Print even numbers:
for i in range(2, 21, 2):
print(i)Calculate the sum of numbers from 1 to 10:
total = 0
i = 1
while i <= 10:
total += i
i += 1
print("Sum:", total)Print a pattern:
for i in range(1, 6):
for j in range(i):
print("*", end="")
print()Key Takeaways
Use
forloops to iterate over sequences like lists, strings, or ranges.Use
whileloops to repeat code as long as a condition isTrue.Control loop behavior with
break,continue, andpass.Nested loops are useful for working with multi-dimensional data.
What’s Next?
Tomorrow, we’ll dive into functions, which allow you to organize your code into reusable blocks. Functions are essential for writing clean, modular, and efficient programs.
Congratulations on completing Day 3! You’re making great progress. Keep practicing, and see you tomorrow! 🚀


