Loops
Loops are an essential part of programming that allow us to execute a block of code multiple times without writing it repeatedly. Instead of manually repeating tasks, loops help automate repetitive actions efficiently.
Python provides two main types of loops:
- for loop - Used for iterating over a sequence (such as a list, tuple, dictionary, string, or range).
- while loop - Executes a block of code as long as a condition is true.
In this section, we will focus on the for
loop, as it is one of the most commonly used loops in Python.
Understanding for
Loops
A for
loop in Python is used to iterate over a sequence (like a list or string). Unlike traditional C-style loops (which rely on an index variable), Python's for
loop directly iterates over elements in a sequence.
Syntax of a for
Loop
for item in sequence:
# Code block to execute
item
takes the value of each element in the sequence, one at a time.- The loop continues until all elements in the sequence are processed.
- The colon (:) is required after the
for
statement. - The indented block under
for
is executed for each item.
Example: Looping Through a List
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry
Looping Through a String
A string is a sequence of characters, so we can iterate through it using a for
loop.
for letter in "Python":
print(letter)
Output:
P
y
t
h
o
n
Using for
Loop with range()
The range()
function generates a sequence of numbers, which is useful when we need to loop a specific number of times.
for i in range(5):
print("Iteration", i)
Output:
Iteration 0
Iteration 1
Iteration 2
Iteration 3
Iteration 4
We'll explore range()
in more detail in the next lesson.
Nested for
Loops
We can use a loop inside another loop to iterate over multiple sequences.
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: 1
break
and continue
break
: Stops the loop entirely.continue
: Skips the current iteration and moves to the next one.
Example: Using break
for num in range(10):
if num == 5:
break
print(num)
Output:
0
1
2
3
4
Example: Using continue
for num in range(5):
if num == 2:
continue
print(num)
Output:
0
1
3
4
Exercise: Try It Yourself!
- Write a
for
loop that prints the numbers from 1 to 10. - Modify the loop to skip number 5 using
continue
. - Create a
for
loop that iterates over the word "Python" and prints each letter in uppercase. - Use
break
to stop the loop when it encounters the letter "t" in "Python".