For Loop In Python: What You Need To Know, With Examples

Loops are fundamental constructs seen in a variety of programming languages. Loops make it easier for us to repeat a set of instructions over a number of different elements. Task automation and effective workflow are made possible by the ability to carry out activities for a particular set of components or up until a particular result is attained. An overview of Python’s for loops, their functionality, and applications will be provided in this article.

What Are For Loops in Python?

While loops, for loops, and nested loops are the three primary forms of loops in Python. When a condition is true, an action is repeated in a while loop, which ends when the condition is false. Nested loops are loops that are contained within other loops. However, for loops repeatedly run code over a certain element sequence.

How Are For Loops in Python Used?

For loops are used to run code repeatedly for a list of elements, as was already mentioned. Iteration is the term for this repetition. A for loop’s fundamental syntax is as follows:

for [element] in [sequence]:
      [code to be executed]
     [function to be executed]

For instance, a for loop that outputs each item in a list of veggies is an example. This would be noted as follows:

vegetables = ["cucumber", "tomato", "potato"]

for vegetable in vegetables:
    print(vegetable)

The variable veggie will hold the value of each element as the for loop iterates over each one. As seen in the picture, each component is printed to the console.

Illustration of the basic syntax of a for loop.

History-Computer.com

Using For Loops With an Else Statement

Within a for loop, an else statement is an optional clause that is carried out after the for loop has finished. Let’s examine this code as an example:

vegetables = ["cucumber", "tomato", "potato"]

for vegetable in vegetables:
    print(vegetable)
else:
    print("All vegetables have been printed.")

This improved version has a straightforward else statement that publishes a message after printing all of the vegetables. The picture below shows how this works.

A for loop with an else statement, with its output.

History-Computer.com

Using For Loops With an if Statement

In Python, the if statement is another typical statement to use with for loops. This is used to determine whether a specific condition is true before changing the outcome. This is evident in this code block:

vegetables = ["cucumber", "tomato", "potato"]

for vegetable in vegetables:
    print(vegetable)
    if vegetable == "tomato":
        print("Encountered a tomato!")
else:
    print("All vegetables have been printed.")
)

If the tomato element is found, a second message will be printed using an if statement. The output is altered as a result, as shown below.

Illustration of a for loop with an if statement.

History-Computer.com

Using For Loops With the Range() Function

Therange() method is another way to use for loops. When we don’t want to traverse every element, this can be used to iterate over a subset of elements. The altered code that illustrates this is as follows:

vegetables = ["cucumber", "tomato", "potato", "carrot", "spinach"]

for i in range(1, len(vegetables), 2):
    print(vegetables[i])
else:
    print("Printing every other vegetable is complete.")

Here, the list length is determined by the len() function, and all additional elements are handled by the range() function. As can be seen in the photograph, only tomato and carrot are printed.

A for loop with the range() function implemented.

History-Computer.com

What Control Statements Are Used With For Loops in Python?

In Python, for loops can be combined with 3 different types of control statements. These influence how the loop is executed. These clauses may contain continue, break, or pass clauses. Here is a quick look at these.

Continue statements

These are employed to stop a loop from running and go on to the subsequent operation. We can demonstrate this using similar code:

vegetables = ["cucumber", "tomato", "potato"]

for vegetable in vegetables:
    if vegetable == "tomato":
        continue
    print(vegetable)
else:
    print("All vegetables have been printed.")

We changed the result, as shown in the image, by adding a continue statement. The continue statement implies that the tomato part is skipped once we get there, so it hasn’t been printed. The remaining components are subsequently added to the for loop. The else clause repeats the previous printing of the other parts.

A continue statement illustrated.

History-Computer.com

Break statements

Even if a for loop is still running, this kind of statement can be used to stop it from continuing. The software then picks up the subsequent statement after the loop. The same vegetable example can be used to demonstrate this. Look at the following code:

vegetables = ["cucumber", "tomato", "potato"]

for vegetable in vegetables:
    if vegetable == "tomato":
        break
    print(vegetable)
else:
    print("All vegetables have been printed.")

In addition to using an if statement, we also utilize a break statement. When the tomato element is located, the for loop is terminated, printing only the first element. This is evident in the results.

A for loop with a break statement.

History-Computer.com

Pass statements

A pass statement is the third classification of control statement. Since a pass statement does nothing, it is primarily used as a stand-in to preserve the intended organization of the code. It is frequently replaced with a function or other executable code afterwards. Take this code, for instance:

vegetables = ["cucumber", "tomato", "potato"]

for vegetable in vegetables:
    print(vegetable)
    if vegetable == "tomato":
        pass
else:
    print("All vegetables have been printed.")

Although it is present, the pass statement has no impact on the code’s output.

A pass statement included in a for loop.

History-Computer.com

A note on nested loops

For loops are not a requirement for nested loops, but they frequently are. Any type of loop can be inserted inside another loop when many levels of operation are needed. The nested loop will repeat each iteration of the outer loop it is contained within. Let’s use the following illustration to demonstrate:

vegetables = ["cucumber", "tomato", "potato"]

for vegetable in vegetables:
    for letter in vegetable:
        print(letter)
    print("End of", vegetable)
else:
    print("All vegetables have been printed.")

This has been changed to incorporate a second for loop inside the first. We print the first letter of the name after each vegetable ingredient is encountered, then End of [vegetable]. The image shows the modified output.

A second loop can be nested within the first loop.

History-Computer.com

For Loop in Python: Wrapping Up

In conclusion, for loops are a relatively straightforward but crucial Python feature that let you carry out intricate and repetitive processes quickly. Whether the elements are character strings or numbers, they can be used to iterate over lists of elements. For loops can be nested inside of one another to execute more actions as needed. Each element can be worked on separately. Control statements are frequently used to govern operations according to particular circumstances.

Leave a Comment