Search⌘ K
AI Features

`for` Loop

Explore how to use for loops in both Python and PowerShell to execute code repeatedly. Understand Python's range function, list iteration, and PowerShell's ForEach and ForEach-Object cmdlets. This lesson helps you grasp loop syntax and practical uses to automate repetitive tasks effectively.

What are loops?

Loops are sets of instructions used to execute a code block repeatedly. Let’s start by discussing the for loop.

for loop

We will often come across scenarios where we will need to repeat or iterate a piece of code over and over without writing the code block multiple times. The for loop is the simplest and most popular type of loop, but there are various ways in which it can be used.

Using the range() method

In Python, for loops can iterate over a number sequence using the range() function. The range function returns a list of numbers within a range that is specified as the function parameter(s).

Python Syntax for for loop:

for i in range(n):
    statement to iterate

Let’s take a simple example where we want to print a series of numbers (1,2,3,4,5) using the for loop in Python.

Python 3.5
for n in range(1,6):
print(n)

What is happening here? Let’s try to understand by reading the above example from left to right. For each number in the range 1 to 5, iterate the statements in the body of the loop. This is print(n) in our example.

Python 3.8
for n in range(6):
print(n)

Note that the range() function is zero-based, which means the count starts from 0 and not from 1 if the starting number is not defined.

Using the list

Just like the range of numbers, you can also use elements of a Python list to iterate statements using a for loop. Let’s see the same example of printing numbers but with a list instead.

for n in [1,2,3,4,5,6]:
    print(n)

The good thing about lists is that you can use characters, strings, and floating-point numbers to iterate, unlike the range() function which can only have numbers.

Python 3.5
## using list of characters
for n in ['a','b','c']:
print('char:',n)
for n in list('abc'):
print('char:',n)
## using list of strings
for n in ['abc','def']:
print('String:',n)
## using list of floating point numbers
for n in [1.4, 2.3, 4.5]:
print('float:',n)

ForEach and ForEach-Object

The PowerShell alternative to a for loop is a ForEach statement. Just like Python, we can define a range of items to iterate over and access within the loop body. In PowerShell, however, the double-dot operator (..) is used to define a range, which means 1..5 will return integers from 1 to 5 and -3…3 will return all the integers from negative 3 to positive 3, including zero.

PowerShell syntax for ForEach loop:

Foreach($i in start..end){
    statement to iterate
}

In the above syntax, we have to provide the start of the range, the end of the range, and the body of the loop with the statements to be iterated enclosed inside braces { }. Let’s take the simple example of printing a series of numbers from 1 to 5 to demonstrate this.

Python 3.5
Foreach($i in 1..5){
$i
}

PowerShell has an optional method for iterating items in a loop by using the ForEach-Object cmdlet. This cmdlet can only receive items from a PowerShell pipeline, however, as in the following example.

1..5 | Foreach-Object { $_ }

## alternatively '%' is an alias of ForEach-Object
1..5 | % { $_ }

Type these commands in the terminal below to see its output.

Terminal 1
Terminal
Loading...

Pipelines are the most powerful feature of PowerShell and are used to connect a series of commands together. This is also known as command chaining. To find out more about how pipelines run, use Get-Help about_Pipelines in the above terminal to read the detailed help description. A pipeline acts as an interface between the output of the command on the left-hand side and feeds it as input to the command on the right-hand side. In the above example, $_ represents the current object that was passed from left to right for processing. The beauty of pipelines is that objects can be passed from left to right one at a time as and when they are processed. Thus, the command on the right doesn’t have to wait for the complete command to be executed on the left.