The for
loop in Python is used to iterate over a sequence (like a list, tuple, string, or range) and execute a block of code for each item in the sequence. It’s a great tool when you know how many times you need to loop.
Syntax of a For Loop
for variable in sequence:
# Code block to execute
variable
: Represents the current item in the sequence. The loop will assign each value from the sequence to this variable in each iteration.sequence
: This is the collection you want to loop over (e.g., a list, string, or range).
How a For Loop Works
- The
for
loop starts by taking the first item from the sequence. - It runs the code inside the loop using that item.
- Then, it moves to the next item in the sequence and repeats the process.
- When the sequence is exhausted, the loop ends.
Example 1: For Loop with a List
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry
Explanation:
- The loop iterates over each item in the
fruits
list and prints it.
Example 2: For Loop with a String
word = "hello"
for letter in word:
print(letter)
Output:
h
e
l
l
o
Explanation:
- The loop goes through each character in the string
"hello"
and prints it.
Example 3: For Loop with a Range
The range()
function generates a sequence of numbers, which is often used with for
loops.
for i in range(1, 6):
print(i)
Output:
1
2
3
4
5
Explanation:
- The
range(1, 6)
generates numbers from 1 to 5 (note that 6 is excluded).
Example 4: For Loop with a Step
You can also specify a step size when using range()
.
for i in range(0, 10, 2):
print(i)
Output:
0
2
4
6
8
Explanation:
- The
range(0, 10, 2)
generates numbers starting from 0 up to 9 with a step of 2.
Example 5: Nested For Loops
You can also have one for
loop inside another. This is called a nested for loop.
for i in range(1, 4):
for j in range(1, 4):
print(i, j)
Output:
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
Explanation:
- The outer loop iterates over numbers 1 to 3.
- For each iteration of the outer loop, the inner loop also iterates over numbers 1 to 3.
Example 6: Using a For Loop with a Break Statement
You can use the break
statement to exit a loop early.
for i in range(1, 6):
if i == 3:
break
print(i)
Output:
1
2
Explanation:
- The loop stops when
i
equals 3, so it only prints 1 and 2.
Example 7: Using a For Loop with Continue
You can use the continue
statement to skip the current iteration and move to the next.
for i in range(1, 6):
if i == 3:
continue
print(i)
Output:
1
2
4
5
Explanation:
- When
i
equals 3, thecontinue
statement skips that iteration, so 3 is not printed.
Key Points to Remember
- The
for
loop is ideal when you know the number of iterations or are iterating over a sequence. - You can iterate over lists, strings, ranges, dictionaries, and other sequences.
- Use
break
to exit a loop early andcontinue
to skip to the next iteration. range()
is commonly used to generate numbers for looping.