A loop is a programming concept common to many programming languages. Loops are used to repeat a block of code. To a programmer, loops are a very valuable tool because they reduce the amount of code a programmer has to write and, by doing so, end up saving time.
In Python, there are two types of loops: while loops and for loops. When writing a while or a for loop, we must indent the body of code that we want to be executed while the loop is being executed.
While loops
A while loop is used to repeat a block of code as long as the given condition is true, or we can say a while loop is used to iterate through some code until the given condition is false.
While loops are similar to if statements, The major difference between them is that an if statement performs the task once when the condition is true, whereas a while loop keeps running over and over until the condition is false.
Flowchart describing a while loop
The syntax for a while loop is:
while condition:
# body of while loop
An example illustrating a while loop:
x = 15
sum = 0
i = 1
while i <= x:
sum = sum + i
i = i + 1
print("The sum will be", sum)
The above code is for calculating the sum of numbers less than or equal to 15.
Before the while loop was initiated, we were given three variables: x, sum, and i. What Python does here is that it looks through these variables and gets their values; it then looks at the condition of the loop and executes the body of the loop until the condition is false, which happens when i is greater than x, meaning i is equal to sixteen.
When the loop ends, the output will be:
The sum will be 120
Infinite loops: An infinite loop occurs when the condition of a while loop is always true. The loop will keep running forever until the memory of the system runs out. An example illustrating an infinite loop is:
x = 4
while x > 0:
print("Run on!")
print ("Done!")
In this example, the condition for the loop to run is that x must be greater than 0, meaning that for the loop to stop executing, x must be less than 0. But the initial value of x is 4, and since there is no other line of code to reduce the value of x, the value of x remains 4, and since 4 is greater than 0, the loop never stops running. To solve this problem, we can add a line of code like x-1 after the line of code that prints "Run on!". This would reduce the value of x by 1 and will print "Run on!" four times before "Done!" is printed to signify that the loop has ended.
Correct code:
x = 4
while x > 0:
print("Run on!")
x = x - 1
print ("Done!")
Output:
Run On!
Run On!
Run On!
Run On!
Done!
For loops
Another type of loop in Python is the for loop. Before we talk about what a for loop is, we need to understand what a sequence is. A sequence in Python is a collection of ordered sets, for example, lists, which are the most versatile sequence types.
A for loop is used to iterate over a sequence, which could be a list, string, dictionary, etc. For loops are mostly used when we know the number of times the loop needs to be repeated. The difference between a while loop and a for loop is that a while loop is used when the number of iterations is unknown, whereas a for loop is used when the number of iterations is known.
Flowchart illustrating a for loop:
The syntax for a for loop is:
for variable in items:
#loop body to execute
In the syntax above, Python looks through the sequence items, and for every variable or value in those items, it executes the body of the loop.
An example illustrating a for loop:
numbers = [3, 6, 9, 5, 4, 1, 2, 4, 11, 15]
sum = 0
for val in numbers:
sum = sum+val
print("The sum of the number will be", sum)
What this example does is print out the sum of numbers in a list. In this example, a list is stored in the variable “numbers”, and we are given the initial value of the sum to be 0. What the for loop does is that it looks through the list of numbers, and for every number or value in that list, it adds the number to the previous value of the sum and saves the answer in the variable "sum".
The output of this code would be:
The sum of the number will be 60
To check if that is right, we can add all the numbers in the list and notice that it gives us 60.
Range function: When iterating through a for loop, we normally make use of the range function. The range function (range()) is a function that creates a series of numbers within a certain range. When dealing with longer lists of numbers, range() is much more appropriate to use than typing everything out.
The syntax of the range function is:
range (start, stop, step)
Start represents the first number in the list of numbers that we want to loop over.
Stop represents the stopping point of the loop. The stop value is not included in the interaction. For example, if we were to loop over the range (1, 101, 1), the last number that would be iterated over is 100.
The step represents the number of increments. The default value for this is 1, although we can set our values. For example, let's say we have range(2, 100, 2). The numbers would be printed out in increments of two, meaning that only even numbers would be printed.
An example of range() being used in a for loop would be:
for n in range(1,11):
print(n)
In this example, the output would be numbers from one to ten. Eleven would not be added because it is the stop value, and here step is set to the default value of 1.
The output:
1
2
3
4
5
6
7
8
9
10
Break and Continue statements
The break and continue statements are used to either skip a part of a loop's execution or end the execution of a loop. These two statements can be used with both the while and for loops.
The break statement terminates a loop when it is encountered in a block of code. It is used when we want a code to run if a certain condition is met, and it is also used to end the execution of a while loop. An example showing a break statement being used is:
for val in "HKR Trainings":
if val == "i":
break
print(val)
print("END")
In the example above, the break statement only executes when the value of val is equal to i, which means the code runs until the first "i" is encountered, after which the loop breaks and prints "END."
The output:
H
K
R
T
r
a
END
As expected, the values are printed up until the first "i", which is found in the word “Training”.
The continue statement is used to skip a part of a loop. Unlike the break statement, the loop does not stop executing after encountering the continue statement; it just skips the code that comes before the statement during that iteration of the loop. An example of this would be:
for val in "HKR Trainings":
if val == "i":
continue
print(val)
print("END")
In this example, the condition set is that if val == "i", the continue statement should be executed. In this case, all the individual characters except the "i’s" of "HKR Trainings" would be printed out.
The output:
H
K
R
T
R
a
n
n
g
END
As expected, the “i’s” of the word “HKR Trainings” were skipped while the remaining characters were printed out.
To conclude, I would like to summarize what we learned today about loops. Loops are used for repetition in code, loops can help save a programmer’s time, and there are two types of loops in Python, which are the while loop and the for loop. The while loop is used when the number of iterations is unknown, whereas the for loop is used when the number of iterations is known.
Thank you for reading, and I hope you learned something valuable today.
References: hkrtrainings.com, programiz.com, Kibo programming 1-course material.