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.
Use enumerated loops for known number of iterations
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:
We set a list (
myList) with four elements: 7, 2, 4 and 10.
We took the first element of the list (7) and stored it into the
Then we executed the block of code included in the for loop, with the
eltvariable containing our first value (print it).
Then we started the process with
elttaking the second value (2).
We continued this process until all our list's elements had been stored in the
eltvariable, 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 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 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 toofor i in range(5):print(i) # -> print 0 to 4 toofor 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.
Loop until you reach a condition with while 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:
The program verifies that
If it is
False, the instructions are ignored. You do not even enter the body of the loop located below
If it is
True, the list of statements below
Once the instructions are executed, return to step one.
Try the example below:
numberOfTrees = 0while numberOfTrees < 10:numberOfTrees += 1print("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 = Truewhile theSunIsUp:print ("Stay awake...forever!")# theSunIsUp never changes# we never reach thisprint ("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 !
You are not signed in
Sign in to access coding exercises and test your new skills.
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
5. In Python, to skip an iteration in the loop, use
for i in range(10):# statements executed for each iterationif 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
basket = ["apple", "orange", "banana"]for fruit in basket: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
The loop cycle can be interrupted and exited using the command