Course Content
Python Indentation, Comments and Variables
0/2
Object Oriented Programming in Python
0/1
Exception Handling in Python
0/1
Sending emails with Python
0/1
Unit test in python programming
0/1
Python programming (zero to advance!!!)
About Lesson

A `for` loop in Python is used to iterate over a sequence (such as a list, tuple, string, or range) and execute a block of code for each element in the sequence. The syntax of a `for` loop in Python is straightforward:

“`python
for element in sequence:
# Execute this block of code for each element in the sequence
# Indentation is crucial in Python
# Code here
“`

Here’s a breakdown of the components:
– `element`: This is a variable that represents the current element in the sequence.
– `sequence`: This is the sequence over which the loop iterates.

Here are a few examples illustrating the use of `for` loops in Python:

### Example 1: Iterating Over a List

“`python
fruits = [“apple”, “banana”, “cherry”]
for fruit in fruits:
print(fruit)
“`
Output:
“`
apple
banana
cherry
“`

### Example 2: Iterating Over a String

“`python
word = “Python”
for char in word:
print(char)
“`
Output:
“`
P
y
t
h
o
n
“`

### Example 3: Iterating Over a Range

“`python
for num in range(1, 6):
print(num)
“`
Output:
“`
1
2
3
4
5
“`

### Example 4: Using `enumerate()` to Access Index and Value

“`python
fruits = [“apple”, “banana”, “cherry”]
for index, fruit in enumerate(fruits):
print(f”Index {index}: {fruit}”)
“`
Output:
“`
Index 0: apple
Index 1: banana
Index 2: cherry
“`

These examples demonstrate how `for` loops can be used to iterate over various types of sequences in Python. They provide a convenient way to perform repetitive tasks efficiently.

Join the conversation