Class 11 Control statement For loop notes

The for loop is a control structure used in programming to repeat a block of code for each item in a sequence, such as a list, tuple, dictionary, set, or string. It’s commonly used when you know beforehand how many times you want to execute a statement or a block of statements.


Syntax

for variable in sequence:
# Code to execute for each item in the sequence
  • variable: This is a temporary variable that takes the value of each item in the sequence one by one.
  • sequence: This can be any iterable object, such as a list, string, or range.

Example 1: Iterating Over a List

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)

Output:

apple

banana

cherry

In this example, the for loop iterates over each item in the fruits list, and fruit takes the value of each item in each iteration.

Example 2: Using range() with a for Loop

The range() function generates a sequence of numbers, which is useful for looping a specific number of times.


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

Output:

0
1
2
3
4

Here, range(5) generates numbers from 0 to 4, and the loop runs five times, printing each number.

Example 3: Iterating Over a String

You can also use a for loop to iterate over characters in a string.

for letter in "Hello":
print(letter)

Output:

H
e
l
l
o

In this case, the loop iterates over each character in the string "Hello" and prints it.

Example 4: Nested for Loop

You can use a for loop inside another for loop. This is useful for working with multi-dimensional data structures, such as lists of lists.

for i in range(3):
for j in range(2):
print(f"i = {i}, j = {j}")

Output:

i = 0, j = 0
i = 0, j = 1
i = 1, j = 0
i = 1, j = 1
i = 2, j = 0
i = 2, j = 1

In this example, the outer loop runs three times, and for each iteration of the outer loop, the inner loop runs twice.

Key Points

  • A for loop is used when you need to execute a block of code multiple times, typically over a sequence of items.
  • It’s especially useful when you know in advance how many times the loop should run.
  • range() is commonly used in for loops to generate sequences of numbers.


Post a Comment

0 Comments