Iteration means repetition of a process, in programming it means executing a block of statements until a given condition evaluates to false i.e the condition fails. Iteration in programming is achieved through loops, Python offers two essential loops, the while
and the for
loop, there is also another mode of iteration known as list comprehension .We will explore these looping constructs one by one.
The while loop
The while loop is the most basic iteration tool in Python. It is used to perform an action as long as a given condition remains True. This loop has 4 essential elements:
- Initialization - In this part, we give an initial value to the loop variable. A loop variable is one whose value is meant to change in order to take the loop closer to its termination.
- Test condition - In this part the condition is tested , if met , the loop continues, otherwise, it terminates.
- loop body- This is where the statements to be executed if the condition passes are located. These statements are executed until the condition fails.
- Update Statement - In order for the loop to terminate, the condition given must fail and for this to happen, the loop variable must be altered. The update statement is responsible for updating the loop variable.
A typical while
loop looks like:
<initialize counter>
while <condition> :
...
statement
statement
...
<update counter>
i = 0
while i < 10:
print(i)
i += 1
The loop elements as we discussed above are clearly illustrated in our example:
We have discussed the structure of a while loop. Let us now discuss how it functions
How it works
As we said, whenever a while loop is encountered, the statements within it's block are executed until the condition evaluates to False
. Our example above is simple enough in that the body of the loop only prints the current value stored in the loop variable until the loop terminates.
The simple logic behind our example is that the counter's value starts as 0:
i = 0
We test to check that the value held by i
is less than or equal to ten,
while i < 10:
If the above condition is met, we print the value currently stored in i
print(i)
And before we leave the loop body we increase the value of i
by 1
i = i + 1
This step is very essential because it is responsible for the loop's termination. Consider that after each iteration, the value of i
is increased by 1 , this means that eventually this value will be equal to 10 meaning that the loop's condition will fail consequently making the loop to terminate.
Then we repeat until the time when the condition fails.
i = 1
while i <= 10:
print(i)
i += 2
i = 10
while i >= 1:
print(i)
i -= 1
i = 10
while i >= 1:
print(i)
i -= 2
Infinite while Loops
Consider what would happen if the loop variable is not decreased or increased during each iteration, the condition will never fail and hence the loop will run forever! .These type of loops are called infinity loops , because if the computer had unlimited resources, the program could possibly run forever. In reality, however, the program will exhaust the resources allocated to it by the operating system , and therefore the OS will stop it.
Example of an infinity loop:
while True:
print(1)
The above program will print 1's until you stop it, or until it is stopped by the OS.
While there are some useful applications of infinity loops , you should be careful not to create one unintentionally. Let us check at two examples which effectively demonstrates this:
Our first example can as well be written as:
i = 0
while i != 10:
print(i)
i += 1
We might try to follow the same logic, when writing one of our other example,
i = 1
while i != 10:
print(i)
i+=2
This second example is an infinity loop because when you start with i
as 1 then add 2 at each iteration, there is no point when i
will be equal to 10, therefore the condition will always be satisfied.
The break
Statement
Sometimes we want the loop to terminate without the condition necessarily being False
, the break
statement is used for this purpose. The moment it is encountered in the loop's body, the loop terminates prematurely moving to the next statement. The statement is mostly used together with the if
block .
consider if we are looking for the index of the first occurrence of a value in a Python list, the moment we find the index, there is no need of letting the loop keep on iterating until the time the condition will become False
, in this case we can use the break
statement to terminate the loop.
L = [7, 3, 5, 9, 0, 1, 2, 8, 9, 4]
i = 0
while i < len(L):
if L[i] == 9:
print(i)
break
i+=1
The continue
Statement
While the break statement, is used to terminate the loop, the continue
statement simply tells the loop to 'continue' to the next iteration. When this statement is encountered, the loop simply moves to the start of the next iteration without executing the statement below the continue statement.
Consider if we want to use a while loop to print all the digits from 0 to 9 except 5:
i = 0
while i < 10:
if i == 5:
i+=1
continue
print(i)
i+=1
If we forgot to increment i
before using the continue statement , the value of i
would stuck at 5 creating an infinity loop.
The for loop
The for loop is the most used loop in Python.
In python, this loop's syntax is quite different from for loops in other programming languages. In languages such as c++ and Java, the syntax of for
loop is quite similar to that of while
loop but in Python the two loops have a solid difference.
Iterables in Python, are objects which can be iterated upon such as lists, sets, dictionaries e.t.c. A for loop can only be used with this type of objects. it's syntax looks like:
for i in <iterable> :
...
statement
statement
...
The question now is, how can we use the for loop normally i.e like how we used the while loops above?. You have to create an iterable if you want to use a for loop!. Python provides an easy way to do this through the builtin range()
function, you will use this function a lot so let us start by exploring it.
The range() function
The range function is used to create an iterable from values in a given range. It takes three argument:
- start - This is the point where the range begins for example if we want to create a range of values from 0 to 9 , the start will be 0. This argument is optional, if left, 0 will be used as the default value.
- stop - This is the value where the range ends, if we want the range of integer values from 0 to 9 , the stop will be 10. Yes, it is not 9, as you might have assumed, the stop is not included in the range. This argument is required.
- step - This is how many steps that the range function will jump. This argument is optional, 1 will be used as the default value.
The syntax is as follows:
range(start, stop, step)
All these three arguments should be integers, and the range values returned will be integers as well.
Example:
range(0, 10, 1)
The above range will hold the integer values from 0 to 9
We can write the above range simply as:
range(10)
The above case will work because 0 and 1 are already specified as the default values for "start" and "step" respectively.
We can now use the for loop to print the values inside this range as follows:
for i in range(10):
print(i)
Whenever we need to use another value as the "step" other than the one specified as the default i.e 1 , We will be required to explicitly provide values for all the three arguments, even if we want the "start" to be 0.
for i in range(0,10, 2):
print(i)
To create a reverse range, we pass a negative value as the range's step as follows:
for i in range(10, 0, -1):
print(i)
Notice how the range starts at 10 and ends at 1, this is because the start value is 10 and the stop value is 0, 0 will therefore not get included in the range.
for i in range(10, 0, -2):
print(i)
The for loop can be used with any iterable in Python for example we can use it with a Python list as follows
L = [3, 4, 8, 9, 2, 7]
for i in L:
print(i)
The
else
Statement.
It is possible to use the else
statement with loops, the statements under it's block will be executed only if the loop terminates successfully i.e the condition loop fails without encountering continue or break statements . It can be used with both for
and while
loops.
the following shows how we can use the else block with the while
loop:
i = 1
while i <= 5:
print(i)
i += 1
else:
print("done")
with for
loop:
for i in range(1, 6):
print(i)
else:
print("done")
An example of using the else statement in a useful way is when we want to find an element in a sequence , we can use the else
statement to return a default if the search fails:
def find(v, seq):
i = 0
while i < len(seq):
if seq[i] == v:
return i
i += 1
else:
return -1
print(find(7, [6, 1, 8, 0, 9, 2, 5] ))
In the above case, if the value is not located in the sequence, the function will return -1