Python For Loop

What is a For Loop?

The for loop in Python is used to iterate over a sequence (such as a list, tuple, dictionary, string, or range).

Basic Syntax

for item in sequence:
    # Code block to execute

Try It Now

Example: Looping Through a List

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

Try It Now

Using the Range Function

The range() function generates a sequence of numbers.

for num in range(5):
    print(num)  # Prints 0 to 4

Try It Now

Looping Through a String

for char in "Python":
    print(char)

Try It Now

Iterating Over a Dictionary

student = {"name": "Alice", "age": 25, "grade": "A"}
for key, value in student.items():
    print(key, ":", value)

Try It Now

Using Else with For Loop

An optional else block runs when the loop completes normally.

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

Try It Now

Nested For Loops

A loop inside another loop.

for i in range(3):
    for j in range(2):
        print(f"i: {i}, j: {j}")

Try It Now

Break Statement

The break statement exits the loop when a condition is met.

for num in range(10):
    if num == 5:
        break
    print(num)

Try It Now

Continue Statement

The continue statement skips the current iteration and moves to the next.

for num in range(5):
    if num == 2:
        continue
    print(num)

Try It Now