Python for Loop

The for loop in Python is used to iterate over a sequence (like a list, tuple, string, dictionary, or range). It allows you to execute a block of code once for each item in a sequence.

Syntax

for variable in sequence:
   # code block to execute
  • variable: A temporary name that takes the value of each item in the sequence.
  • sequence: A collection of items (like a list or string).

Example 1: Loop Through a List

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

Output:

apple
banana
cherry

Example 2: Loop Through a String

for char in "Python":
   print(char)

Output:

P
y
t
h
o
n

Example 3: Using range()

The range() function generates a sequence of numbers.

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

Output:

0
1
2
3
4

You can customize range(start, stop, step):

for i in range(2, 10, 2):
   print(i)

Output:

2
4
6
8

Example 4: Loop Through a Tuple

colors = ("red", "green", "blue")
for color in colors:
   print(color)

Output:

red
green
blue

Example 5: Loop Through a Dictionary

You can loop through keys or key-value pairs:

person = {"name": "Alice", "age": 25}
for key in person:
   print(key, ":", person[key])

Output:

name : Alice
age : 25

Example 6: for Loop with else

The else block executes after the loop finishes normally (no break).

for i in range(3):
   print(i)
else:
   print("Loop completed!")

Output:

0
1
2
Loop completed!

Nested for Loop

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

Output:

i=1, j=1
i=1, j=2
i=2, j=1
i=2, j=2
i=3, j=1
i=3, j=2

Loop Control Statements

You can use these with for loops:

  • break: Exit the loop early.
  • continue: Skip current iteration.
  • pass: Do nothing (used as a placeholder).

Example:

for i in range(5):
   if i == 3:
       break
   print(i)

Output:

0
1
2

Summary Table

StatementDescription
forRepeats a block of code for each item
range()Creates a sequence of numbers
breakExits the loop early
continueSkips the current loop iteration
elseRuns when loop completes normally

Practice Task

Print the square of numbers from 1 to 5 using a for loop.

for i in range(1, 6):
   print(i * i)

Output:

1
4
9
16
25