Introduction to Python For Loops
Python For Loops
A for
loop is used to iterate over a sequence (such as a list, tuple, string, or range) or any iterable object.
It allows you to execute a block of code for each item in the sequence.
Here's the basic syntax of a for loop:
for item in sequence:
# code block to be executed for each item
Here's an example that demonstrates the for
loop:
`fruits` = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
print("Loop finished")
In this example:
- The
for
loop iterates over each item in thefruits
list. -In each iteration, the current item is assigned to the variablefruit
, and the code inside the loop prints the value offruit
. - After iterating over all the items, the loop finishes, and the program continues with the statement after the loop, which prints "Loop finished".
The for
loop can also be used with other iterable objects like strings, tuples, and ranges. Here are a
Iterating over a string
name = "John"
for character in name:
print(character)
Iterating over a tuple
coordinates = (3, 4, 5)
for value in coordinates:
print(value)
Iterating over a range
for num in range(1, 6):
print(num)
- The
range(start, stop)
function is used to generate a sequence of numbers fromstart
(inclusive) tostop
(exclusive). In this example, the loop will iterate from 1 to 5.
You can also use the enumerate()
function to iterate over a sequence and access both the index and value of each item.
As an example:
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print("Index:", index, "Fruit:", fruit)
The enumerate()
function returns an iterator that produces tuples containing the index and value of each item in the sequence.
The break
and continue
with for
loop
You can use control statements like break
and continue
within a for
loop, similar to the while loop.
- The
break
statement is used to exit the loop prematurely. When encountered, it immediately terminates the loop and transfers the control to the statement after the loop.
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
if fruit == "banana":
break
- The
continue
statement is used to skip the rest of the current iteration and move to the next iteration of the loop.
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
if fruit == "banana":
continue
print(fruit)
In both examples:
- The loop will terminate or skip the rest of the iterations based on the condition.