Loops

For Loop

The for loop is used to iterate over a sequence (such as a list, tuple, string, or range). It runs the block of code for each item in the sequence.

Syntax:

for variable in sequence:
    # code block

Example:

numbers = [1, 2, 3, 4]
for number in numbers:
    print(number)

Output:

1
2
3
4

Real-world Example:

Dodagatta Nihar lists the tasks he needs to complete today:

tasks = ["Check emails", "Attend meeting", "Write report"]
for task in tasks:
    print(f"Dodagatta Nihar needs to: {task}")

Output:

Dodagatta Nihar needs to: Check emails
Dodagatta Nihar needs to: Attend meeting
Dodagatta Nihar needs to: Write report