Last updated on 2/18/22

## Use the right loop

Imagine you have a block of code you need to repeat multiple times. You can wrap it in a function and call that function as many times as you need. That could do the trick, however, most of the time you don't even know in advance how many times you need to call it.

Loops solve this issue!

A loop, in programming, is a technique that allows you to repeat one or more instructions without having to retype them multiple times.

Enumerated loops are used when you know in advance how many times you want to loop. In Python, these are called for loops.

#### `For`  loops with collections

The classic use for enumerated loops in Python is when you need to iterate over a collection. Here is an example with a list:

The result is the elements of the list one by one.

Let's review what happened in the code below:

1. We set a list (`myList`) with four elements: 7, 2, 4 and 10.

2. We took the first element of the list (7) and stored it into the `elt` variable.

3. Then we executed the block of code included in the for loop, with the `elt` variable containing our first value (print it).

4. Then we started the process with `elt` taking the second value (2).

5. We continued this process until all our list's elements had been stored in the `elt` variable, and the block of code executed for each one of them (print all of our list's values).

Here is a flowchart, to understand the Python logic behind the for loop:

You can also iterate over a string:

``````myString = "Elements"

for elt in myString:
print(elt)
``````

In this case, `elt` takes every character of your string.

#### For loops with an integer value

To loop with an integer value in Python, first create a sequence starting from 0 to your integer using the `range` function. `range` generates a list of numbers according to three potential parameters `range(start, stop, step)` with:

• `start`: starting number of the sequence

• `stop`: generate numbers up to, but not including this number

• `step`: the difference between each number in the sequence

For instance:

``````for i in range(0, 5, 1):
print(i) # -> print 0 to 4 (stop-1)

for i in range(0, 5):
print(i) # -> print 0 to 4 too

for i in range(5):
print(i) # -> print 0 to 4 too

for i in range(0, 5, 2):
print(i) # -> print 0, 2, 4
``````

The for loop is great when you want to loop a predefined number of times or over all the elements of an array. When it is not the case, Python provides a more general way of looping with conditional loops.

Conditional loops are also called while loops.

As you can guess by the name, the loop needs to keep going while … something… or"as long as." It is a little like a combination of a for loop and an if statement. The number of repetitions is not defined by the lower and upper limits of an enumerator, but by a condition like that of an if statement.

Here's what the syntax looks like:

``````while logicalExpression:
# list of statements
``````

It can be interpreted as "as long as the logical expression is true, repeat the instructions."

This is how it works:

1. The program verifies that `logicalExpression` is `True`

2. If it is `False`, the instructions are ignored. You do not even enter the body of the loop located below `:`.

3. If it is `True` , the list of statements below `:` are executed.

Try the example below:

``````numberOfTrees = 0

while numberOfTrees < 10:
numberOfTrees += 1
print("I planted", numberOfTrees, "trees")

print("I have a forest!")
``````

This will produce the following result:

At each loop turn, `numberOfTrees` is incremented by one. When the variable reaches the value `10,` the numberOfTrees <`10` is no longer true. So, we terminate the loop and move on with the rest of the code in the program. In this case, it prints `"I have a forest!"`.

``````theSunIsUp = True

while theSunIsUp:
print ("Stay awake...forever!")# theSunIsUp never changes

# we never reach this
print ("Go to sleep!")
``````

It's a common and easy mistake to make. So, pay attention!

As you can see, the while condition is checked before the corresponding block of code can be executed even one time!

#### Try it yourself !

Coding application
##### Houston... ?
It seems you're not connected to the internet.
##### You are not signed in

Make sure to practice in this chapter before moving on.

#### Skipping some instructions inside a loop

Within each type of loop, there might be situations when you want to skip some iterations or interrupt the whole loop prematurely upon a certain condition.

For example, you may want to repeat something 10 times, but skip (or partially skip) when the value  equals `2` or `5`. In Python, to skip an iteration in the loop, use `continue` statement:

``````for i in range(10):
# statements executed for each iteration
if i == 2 or i == 5:
continue
# statements not executed when i == 2 or 5}
``````

You can also interrupt the sequence if you are looking for, and then find, an element in an array:

In Python, to interrupt an execution sequence, use a `break` statement:

``````basket = ["apple", "orange", "banana"]

if fruit == "orange":
print("I have an", fruit, "!")
break
``````

Once you have found an item you were looking for, you can stop browsing the rest of an array.

In this chapter, you learned about two types of loops:

• Enumerated loops that execute a set of instructions a fixed number of times over a sequence.

• Conditional loops that execute a set of instructions until a defined condition is satisfied.

• A common mistake to watch out for with conditional loops: infinite loops!

• Iterations in a loop can skip some instructions within the loop using command `continue`.

• The loop cycle can be interrupted and exited using the command `break`.