For Loop

A for loop is used to repeat a block of code multiple times.
It is commonly used to iterate over sequences like lists, tuples, strings, dictionaries, and ranges.

For loops make programs shorter, cleaner, and more efficient.

SYNTAX OF FOR LOOP

for variable in sequence:
# code block

The loop runs once for each item in the sequence.

EXAMPLE 1: LOOP WITH A LIST

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

The loop prints each number from the list one by one.

EXAMPLE 2: LOOP WITH A STRING

text = "Python"for letter in text:
print(letter)

The loop prints each character separately.

USING range() FUNCTION

The range() function generates a sequence of numbers.

Example 1: Basic range

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

Output:
0
1
2
3
4

Example 2: Start and Stop

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

Output:
1 to 5

Example 3: Step Value

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

This prints numbers with a step of 2.

FOR LOOP WITH IF CONDITION

for num in range(1, 11):
if num % 2 == 0:
print(num)

This prints only even numbers between 1 and 10.

NESTED FOR LOOP

You can use a loop inside another loop.

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

Nested loops are useful for patterns, tables, and matrix operations.

BREAK AND CONTINUE

Break Statement

Stops the loop completely.

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

Continue Statement

Skips the current iteration.

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

WHY FOR LOOPS ARE IMPORTANT

• Automate repetitive tasks
• Work with collections of data
• Build logical programs efficiently
• Create patterns and tables

Understanding the for loop is essential for writing powerful and dynamic Python programs.

Home » PYTHON FUNDAMENTALS (PYF) > Control Flow > For Loop