Have you ever challenged yourself while exercising like “I will run 10 rounds of this park” or “I will run as many rounds as I can”? If yes, basically, you were putting yourself in a loop with a counter or a condition. Programming turned out to have a similar concept. You will encounter situations where you have to repeatedly execute certain logics. This is call programming loops. And programming loops can be either condition-controlled or count-controlled. In this post, I will go through these two types of loops in Python, namely while loop and for loop. The codes in this post are also in this notebook.
While loops in Python
A while loop is called a condition-controlled loop. It allows you to repeatedly execute a code block as long as a condition is True. In terms of syntax, it is very similar to an if statement
while <condition expression>:
block of codes
Like in the if structure, when Python encounters a while loop, it first check the condition expression
. If the expression is True, Python execute the block of codes
. However, after that, the program will check the condition expression again. The checking the condition and executing the codes will be repeated until the condition is False. A small note here, if the condition expression
is False before the first iteration, the block of codes will not be executed at all.
Now let us examine the below example to observe a while loop in Python.
1. Python assigns the value 1
to the variable time
.
2. The program reaches the while loop. It checks the condition expression, which is (time < 6)
here. Since time is currently 1
, the condition checks out
3. The program executes the two statements inside the while loops
3.1. Printing the message using the current value of time which is 1
, so the output is "I have been repeated 5 times(s)"
3.2. Execute time = time + 1
. If you are new to programming, this surely looks odd. However, the statement is perfectly correct. time
is being updated with a new value which equals to its old value incremented by 1
. The new value of time
is now 2
4. The program checks the condition (time < 6)
again with the new value 2
of time
. As the condition still checks out, it executes the codes inside the while loop again. This process repeats until the value of time
is 6 and (time < 6)
is no longer True. That is why the last message we see in the output is "I have been repeated 5 times(s)"
.
5. The program terminates the loop and perform the last print()
statement.
time = 1
while (time < 6):
print('I have been repeated', time, 'time(s)')
time = time + 1
print('the loop has ended')
I have been repeated 1 time(s) I have been repeated 2 time(s) I have been repeated 3 time(s) I have been repeated 4 time(s) I have been repeated 5 time(s) the loop has ended
for loops in Python
Unlike while loop that continues or terminates based on checking a certain condition, a for loop iterates through item of a given sequence of items and is a count-controlled loop. The syntax of a for loop is as follows.
for <variable> in <sequence>:
block of code
At the beginning of each iteration, the program checks if there are item remaining in the sequence
. If there are more items, it assigns the value of the current item to variable
then executing the block of codes. If there are no items left, the loop terminates. There are many things that can be a sequence
in Python. The first type we will discuss is the range()
function.
The range() function
The range()
function generates a sequence of integer numbers. You can choose the start, stop, and step. The most basic use of range()
is range(stop)
. This will produce all integer numbers from 0
to stop-1
as an iterable sequence. For example, the use of range(5)
in the code below generate a sequence of number from 0
to 4
. You can try changing 5
to other values and observe that the sequence always stops at stop-1
.
for num in range(5):
print(num)
0 1 2 3 4
The second use of range()
is range(start,stop)
. This syntax creates a sequence from start
to stop-1
. For example
for num in range(5,10):
print(num)
5 6 7 8 9
Again, try playing with the values of start and stop and see how the results look like. The third use of range()
is range(start,stop,step)
which creates a sequence start
to stop-1
incremented by step
. Take some times to practice with all three versions of range()
and the for loop, you will get familiar with them in no times!
for num in range(0,10,2):
print(num)
0 2 4 6 8
Accumulator
Accumulator is the concept of a variable that accumulates itself with new values throughout a loop. Accumulators have a lot of applications in loops in Python as well as other languages. An example is to calculate the sum of all numbers in a sequence. The code can be as follows
accumulator = 0
for num in range(2,10,2):
accumulator = accumulator + num
print(accumulator)
20
What is happening here? Let us examine the codes step-by-step.
1. The program sets the variable accumulator
with the value 0
2. The program reaches the for loop. First, it generates a sequence [2, 4, 6, 8]
from the range(2,10,2)
function
3. The program enters the for loop. In the first loop, it assigns the first item in the sequence, 2
, to num
. Then, accumulator is updated with its old value (0
) added up with current value of num
(2
). accumulator is 2
at the end of the first iteration.
4. The program checks that there are more items after the first one. It enters the second loop and assigns the second item in the sequence, 4
, to num
. Accumulator is updated with its old value (2
) plus current num
(4
). Accumulator is 6
at the end of the second iteration.
5. The program checks, and there are still items in the sequences. It repeats the process, assigns 6
to num
, add current num
to the old accumulator (6
) to get the new accumulator being 12
6. There is one last items in the sequence, 8
, which is assigned to num
. Accumulator is updated one last time to reach 20
.
7. There are no items left. The for loop terminates. By the end, accumulator has the value of 20
, so the print()
statement displays 20
.
Conclusion
Like the post about if, this is a fairly long one too. However, like any programming languages, loops in Python are very important to master. So, please also take your time to practice with loop. Like always, you can change the values of variables, change names, etc. and see what happens. You can also try to rewrite a for loop using while, write accumulator to get the product of a sequence, or the power of a number, etc. So, happy programming, and see you again in the next post!
Pingback: Collections in Python - Data Science from a Practical Perspective