Python for Loop
In Python, the for
loop is used to iterate over a sequence (such as a list, tuple, string, or range) or other iterable objects. The basic syntax of a for
loop is as follows:
for variable in sequence:
# Code to be executed for each iteration
Here's a more detailed breakdown:
- The
for
keyword is used to start the loop. variable
is a variable that takes the value of the next element in thesequence
for each iteration of the loop.sequence
is the iterable object over which the loop iterates.- The indented code block following the
for
statement is the body of the loop, and it is executed for each element in the sequence.
Example with a List:
fruits = ['apple', 'banana', 'orange']
for fruit in fruits:
print(fruit)
In this example, the for
loop iterates over the list of fruits, and the print(fruit)
statement is executed for each fruit in the list.
Example with Range:
for i in range(5):
print(i)
In this example, the for
loop iterates over the range of numbers from 0 to 4, and the print(i)
statement is executed for each value of i
in the range.
Example with Strings:
word = "Python"
for char in word:
print(char)
In this example, the for
loop iterates over each character in the string "Python", and the print(char)
statement is executed for each character.
Using enumerate
for Index and Value:
fruits = ['apple', 'banana', 'orange']
for index, value in enumerate(fruits):
print(f"Index: {index}, Value: {value}")
The enumerate
function is used to iterate over both the index and value of the elements in the list.
Using break
and continue
:
fruits = ['apple', 'banana', 'orange']
for fruit in fruits:
if fruit == 'banana':
continue # Skip 'banana' and move to the next iteration
print(fruit)
if fruit == 'orange':
break # Stop the loop when 'orange' is encountered
The continue
statement skips the rest of the code in the loop for the current iteration, while the break
statement terminates the loop prematurely.
The for
loop is a powerful construct for iterating over sequences and performing repetitive tasks in a concise manner.