Skip to content

Python for Loop

Python3 Loop Statements Python3 Loop Statements


for is the most commonly used loop statement in Python, used to iterate over iterable objects (sequences, dictionaries, sets, etc.).

Python’s for loop is simpler and more powerful than languages like C/C++, requiring no manual management of loop variables and directly iterating over elements.

Word Meaning: for means “for each” or “for every”, used for iterative traversal.


for variable in iterable:
    code block
  • variable: The element taken from the iterable object in each iteration.
  • iterable: Lists, tuples, strings, dictionaries, sets, range, etc.
  • Indentation: The loop body must be indented.
  • Optional: The for loop can have an else clause.
  • Execution Timing: Executed when the loop ends normally (without exiting via break).

# Iterate over a list
fruits = ["Apple", "Banana", "Orange"]

for fruit in fruits:
    print(fruit)

# Iteration with index
for i, fruit in enumerate(fruits):
    print(f"{i}: {fruit}")

Expected Output:

Apple
Banana
Orange
0: Apple
1: Banana
2: Orange

Code Explanation:

  1. The for loop directly iterates over each element in the list.
  2. enumerate() provides both index and value simultaneously.

Example 2: Iterating Over Strings and Tuples

Section titled “Example 2: Iterating Over Strings and Tuples”
# Iterate over a string
for char in "Python":
    print(char, end=" ")
print()  # Newline

# Iterate over a tuple
point = (10, 20)
for value in point:
    print(value, end=" ")
print()

Expected Output:

P y t h o n
10 20

Strings and tuples are also iterable.

# Iterate over a dictionary (default iterates over keys)
person = {"name": "Tom", "age": 20, "city": "Beijing"}

for key in person:
    print(key)

print("---")

# Iterate over key-value pairs
for key, value in person.items():
    print(f"{key}: {value}")

print("---")

# Iterate over values only
for value in person.values():
    print(value)

Expected Output:

name
age
city
---
name: Tom
age: 20
city: Beijing
---
Tom
20
Beijing

The items(), keys(), and values() methods of a dictionary can iterate over different parts.

# for-else structure
for i in range(3):
    print(i)
else:
    print("Loop ended normally")

print("---")

# else does not execute when break is used
for i in range(5):
    if i == 3:
        break
    print(i)
else:
    print("This line will not print")

Expected Output:

0
1
2
Loop ended normally
---
0
1
2

The else clause of the for-else structure does not execute when the loop is terminated by break.

# Nested loops - print the multiplication table
for i in range(1, 10):
    for j in range(1, i + 1):
        print(f"{j}*{i}={i*j}", end="\t")
    print()

Expected Output:

1*1=1
1*2=2    2*2=4
1*3=3    2*3=6    3*3=9
...

Nested loops can be used to process multi-dimensional data structures or generate tables.


Python3 Loop Statements Python3 Loop Statements