Python For Loops

Python is a high-level, object-oriented programming language that is popular for its simplicity and ease of use. One of the key features of Python is its ability to iterate over collections of data, which is accomplished using the “for loop” construct. In this blog, we will discuss Python for loops and provide example code snippets to demonstrate their usage.

The for loop is used to iterate over a sequence, such as a list, tuple, or string. The syntax for a for loop in Python is as follows:

for variable in sequence:
    # Code block to execute for each iteration

The variable in this case is a new variable that is created for the purpose of the loop, and it takes on the value of each element in the sequence during each iteration. The code block within the loop is executed once for each element in the sequence.

Let’s take a look at some example code snippets to better understand how for loops work in Python.

Example 1: Iterating over a List

fruits = ["apple", "banana", "orange", "kiwi"]

for fruit in fruits:
    print(fruit)

Output:

apple
banana
orange
kiwi

In this example, we have a list of fruits, and we use a for loop to iterate over each element in the list. During each iteration, the variable “fruit” takes on the value of each fruit in the list, and the print statement is executed with the value of the variable.

Example 2: Iterating over a String

sentence = "The quick brown fox jumps over the lazy dog"

for letter in sentence:
    print(letter)

Output:

T
h
e

q
u
i
c
k

b
r
o
w
n

f
o
x

j
u
m
p
s

o
v
e
r

t
h
e

l
a
z
y

d
o
g

In this example, we have a string with a sentence, and we use a for loop to iterate over each letter in the string. During each iteration, the variable “letter” takes on the value of each letter in the string, and the print statement is executed with the value of the variable.

Example 3: Iterating with a Range

for i in range(5):
    print(i)

Output:

0
1
2
3
4

In this example, we use the range function to create a sequence of numbers from 0 to 4, and then we use a for loop to iterate over each number in the sequence. During each iteration, the variable “i” takes on the value of each number in the sequence, and the print statement is executed with the value of the variable.

In conclusion, for loops are a powerful and versatile construct in Python that allows you to easily iterate over collections of data. Whether you’re working with lists, strings, or other data structures, for loops are an essential tool for any Python programmer.