Python

In Python, a for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).

Unlike the for keyword in other programming languages, Python's for loop works more like an iterator method found in object-oriented programming languages. It executes a block of code for each item in the sequence.

1. Theoretical Overview

How it Works

  1. Initialization: The loop takes a sequence (like a list or a range).

  2. Assignment: In each iteration, the next value in the sequence is assigned to a "loop variable."

  3. Execution: The indented code block is executed with that variable.

  4. Termination: The loop continues until it reaches the end of the sequence.

The range() Function

To loop through a set of code a specified number of times, we use the range() function.

  • range(5): Generates numbers from 0 to 4 (5 is not included).

  • range(2, 6): Generates numbers from 2 to 5.

  • range(2, 30, 3): Generates numbers from 2 to 29, incrementing by 3.

2. Code Implementation

A. Iterating Over a String

A string is an iterable object; it contains a sequence of characters.

Python
word = "PYTHON"
for letter in word:
    print(f"Current Character: {letter}")

B. Using the range() Function

This is the most common way to run a loop a specific number of times.

Python
# Print numbers 1 to 5
for i in range(1, 6):
    print(f"Iteration Number: {i}")

C. Iterating Over a List

Python
fruits = ["Apple", "Banana", "Cherry"]
for fruit in fruits:
    print(f"I like eating {fruit}")

3. Advanced For Loop Features

The else Keyword in For Loops

The else keyword in a for loop specifies a block of code to be executed when the loop is finished. Note: The else block will NOT be executed if the loop is stopped by a break statement.

Python
for x in range(3):
    print(x)
else:
    print("Loop finished successfully!")

Nested For Loops

A nested loop is a loop inside a loop. The "inner loop" will be executed one time for each iteration of the "outer loop".

Python
colors = ["red", "big", "tasty"]
fruits = ["apple", "banana"]

for x in colors:
    for y in fruits:
        print(x, y)

4. Why use a For Loop?

BenefitDescription
AutomationPerforms repetitive tasks without manual coding for each step.
Data ProcessingEasily traverses through data structures like Lists and Dictionaries.
EfficiencyReduces the number of lines in your code, making it cleaner and easier to debug.
Upcoming Course
Upcoming Course
Learn More
Instructor Tips
Instructor Tips
View Tips
Join Community
Join Community
Join Now