Python for loop


A for loop in Python is a control flow statement that allows you to iterate over a sequence (such as a list, tuple, dictionary, set, or string) or other iterable objects.

Iteration means going through each item in the sequence one by one.

Properties of for loop

  1. Iterable: A for loop in Python requires an iterable object, which is an object capable of returning its members one at a time. like lists, tuples, dictionaries, sets, and strings.
  2. Loop Variable: The loop variable takes the value of the next element of the iterable object in each iteration of the loop.
  3. Indention: The block of code inside the for loop must be indented.
  4. Range Function: The range() function is often used with a for loop to generate a sequence of numbers.
  5. Nested Loops: You can use one for loop inside another for loop, which is called nesting.
  6. Else Clause: A for loop can have an optional else block, which is executed after the loop completes normally. However, if the loop is terminated by a break statement, the else block is skipped.

Examples:

Iterating over a list

numbers= [1,2,3,4,5,6,7]
for num in numbers:
    print(num)

Output:

1
2
3
4
5
6
7

Using range() function

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

Output:

0
1
2
3
4

Iterating over a dictionary

ages = {"Alice": 25, "Bob": 30, "Charlie": 35}
for name, age in ages.items():
    print(f"{name} is {age} years old.")

Output

Alice is 25 years old.
Bob is 30 years old.
Charlie is 35 years old.

Nested for loop

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

for loop with else clause

numbers = [1, 2, 3, 4, 5]
for num in numbers:
    if num == 3:
        break
    print(num)
else:
    print("Completed without break")

Output:

1
2

In this example, the else clause is not executed because the loop is terminated by a break statement.

These examples demonstrate the basic properties and usage of the for loop in Python.