Python For Loop


In this tutorial, we will explore the concept of loops in Python, specifically the ‘for’ loop.

A ‘for’ loop is used to iterate over a sequence (such as a string, list, tuple, or range) or any other iterable object.

We will cover the syntax and usage of the ‘for’ loop in Python.

 

Basic for Loop Syntax


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

for item in iterable:
    # Code to be executed in each iteration


Here's an example that demonstrates the usage of a ‘for’ loop:

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
    print(fruit)


In the above example, the for loop iterates over each element in the fruits list and prints it. The loop variable fruit takes on the value of each element in the list in each iteration.

 

Looping Through a String


You can use a ‘for’ loop to iterate over the characters of a string. Since a string is a sequence of characters, it is iterable. Here's an example:

text = "Hello, World!"

for character in text:
    print(character)


In the above example, the ‘for’ loop iterates over each character in the ‘text’ string and prints it.


Using range() in a for Loop


The ‘range()’ function is often used in conjunction with a ‘for’ loop to generate a sequence of numbers. The’ range()’ function returns a sequence of numbers from a starting value to an ending value (exclusive) with a specified step size.

Here's an example:

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

In the above example, the ‘for’ loop iterates over the numbers 1 to 5 (inclusive) and prints each number.

 

Skipping Iterations with ‘continue’


You can use the ‘continue’ statement within a ‘for’ loop to skip the rest of the code in the current iteration and move on to the next iteration.

Here's an example:

for num in range(1, 6):
    if num == 3:
        continue
    print(num)


In the above example, when ‘num’ is equal to 3, the ‘continue’ statement is encountered, causing the loop to skip printing 3 and move on to the next iteration.

 

Breaking out of a Loop with ‘break’


You can use the ‘break’ statement within a ‘for’ loop to terminate the loop prematurely, even if the loop has not finished iterating through all the items.

Here's an example:

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
    if fruit == "banana":
        break
    print(fruit)


In the above example, when the loop variable ‘fruit’ becomes equal to "banana", the ‘break’ statement is encountered, causing the loop to terminate.


‘else’ Clause in a ‘for’ Loop


A ‘for’ loop can also have an optional ‘else’ clause that is executed after the loop has finished iterating through all the items, except when the loop is terminated by a ‘break’ statement. The code under the ‘else’ clause will execute once at the end of the loop.

Here's an example:

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
    print(fruit)
else:
    print("Finished iterating through all fruits.")


In the above example, the message "Finished iterating through all fruits" will be printed after all the fruits have been iterated through.

 

Nested ‘for’ Loops


You can nest one or more ‘for’ loops within another ‘for’ loop to create nested loops. This allows you to perform more complex iterations.

Here's an example:

fruits = ["apple", "banana", "cherry"]
colors = ["red", "yellow", "black"]

for fruit in fruits:
    for color in colors:
        print(fruit, color)


In the above example, the nested ‘for’ loops iterate through each fruit for each color, resulting in combinations like "apple red," "apple yellow," "apple black," and so on.

 

Summary


In this tutorial, we covered the basics of the ‘for’ loop in Python. We learned how to iterate over sequences using a ‘for’ loop, loop through strings, use the ‘range()’ function, skip iterations with ‘continue’, break out of loops with ‘break’, and use the ‘else’ clause in a ‘for’ loop. Additionally, we explored nested ‘for’ loops for more complex iterations. With the knowledge gained from this tutorial, you should be able to effectively use ‘for’ loops in your Python programs to iterate over sequences and perform various tasks.

© 2022-2023 All rights reserved.