Python For Loop Syntax And Examples

The for loop in Python is a versatile and powerful construct that allows you to iterate over a sequence of elements.

It is a fundamental tool for repetitive tasks and makes it easy to process each item in a collection, such as a list or a string.

In this guide, we'll delve into the syntax of the for loop and provide examples to illustrate its usage.

Syntax of the for Loop:

The basic syntax of a for loop in Python is as follows:

for variable in iterable:
    # Code to execute in each iteration

The code block inside the for loop is indented and executed in each iteration, with the variable taking on the value of each element in the iterable sequentially.

Example 1: Iterating over a List

Let's start with a simple example of iterating over a list of numbers and printing each element:

numbers = [1, 2, 3, 4, 5]

for num in numbers:
    print(num)

In this example, the for loop iterates over the list numbers, and in each iteration, the variable num takes on the value of the current element. The print(num) statement then outputs each number in the list.

Example 2: Iterating over a String

The for loop is not limited to lists; it can iterate over other iterable objects, such as strings. In this example, we iterate over a string and print each character:

message = "Hello, Python!"

for char in message:
    print(char)

Here, the for loop iterates over the string message, and the variable char takes on the value of each character in the string.

Example 3: Iterating over a Range

The range() function is often used with for loops to generate a sequence of numbers. Here's an example of using range() to print numbers from 1 to 5:

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

The range(1, 6) generates numbers from 1 to 5 (inclusive), and the for loop iterates over this sequence.

Example 4: Iterating over a Dictionary

When iterating over a dictionary, the for loop can iterate over keys, values, or key-value pairs. Here's an example of iterating over keys and values:

person = {"name": "John", "age": 30, "city": "New York"}

for key in person:
    print(f"{key}: {person[key]}")

In this example, the for loop iterates over the keys of the person dictionary, and the print() statement outputs each key-value pair.

Conclusion:

The for loop is a fundamental building block in Python programming, providing a convenient way to iterate over collections of data.

Whether you're working with lists, strings, ranges, or dictionaries, mastering the for loop opens the door to efficient and expressive code.

Experiment with these examples and incorporate for loops into your programs to leverage the power of iteration in Python.