In programming, loops are used to execute a block of code repeatedly. A lot of times, you will come face to face with situations where a piece of code will be used over and over without writing the same line of code multiple times. In this article, I will be explaining understanding the purpose of having loops in your code using python programming language.
Outline
Loop: what does it mean?
Types of loop
Loop control statement
The purpose of having a loop in your code
How to use Loop
Conclusion
So sit back and enjoy the read.
Loop: what does it mean?
Whenever we have any task that has to be done repeatedly, or there is any condition that needs to be checked after a certain block of code then a loop is introduced.
Basically, loop executes statements in sequential order. This means that the first statement in a function is executed first, followed by the second and it continues that way till the stated condition is finally met. There may be a situation when you need to execute a block of code several times.
Types of loop
Having understood what loop really means the next in line is the types of the loop we have in python.
There are different types of loop in python which are listed below:
- While loop
- For Loop
- Nested Loop
While loop
While loop repeats a statement or group of statements while a given condition is True. While loop tests the condition of the statement before executing the loop body. For example
'''this code performs a while loop function
it takes in x check the value of x while x is 0, it will also
check the next value still the x < 10 condition is met. '''
x = 0
while x < 10:
print("current value of x", x)
x = x + 1
Output:
0
1
2
3
4
5
6
7
8
9
For Loop
For Loop executes a sequence of statements several times and shortens the code that manages the loop variable. Example For loop
'''this code is checking for the for loop that is for i in A print A
the interperter will check for all the values in A and print them'''
A = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # list
B = (0,1, 2, 3, 4, 5, 6, 7, 8, 9) # tuple
C = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9} # set
D = "Oluwabamikemi" # string
E = {"name": "Atinuke", "age": 12} # dictionary
for i in D: # iterating all the element in list A
print (i)
Output:
O
l
u
w
a
b
a
m
i
k
e
m
i
Note: The whole character in D was printed because the condition was checked by the interpreter and if the condition is true it will print D as seen in the result above.
Nested Loop
A nested loop is a loop inside a loop. In a nested loop the "inner loop" will be executed one time for each iteration of the "outer loop" i.e The program first encounters the outer loop, executing its first iteration. This first iteration triggers the inner, nested loop, which then runs to completion. Then the program returns back to the top of the outer loop, completing the second iteration and again triggering the nested loop. Again, the nested loop runs to completion, and the program returns back to the top of the outer loop until the sequence is complete or a break or other statement disrupts the process.
num_list = [1, 2, 3]
alpha_list = ['a', 'b', 'c']
for number in num_list:
print(number)
for letter in alpha_list:
print(letter)
Output:
1
a
b
c
2
a
b
c
3
a
b
c
Loop control statements
Loop control statements change execution from its original sequence. While executing code and the execution leave that particular scope, all the objects that were created in that scope are eliminated. Loop control statements in python are:
break statement
Continue statement
Pass statement
break statement terminates the loop statement and transfer execution to the next statement that follows the loop.
a = [0, 1, 2, 3, 4, 5]
for x in a:
if x == 2:
break
print(x)
Output:
0
1
in the above code snippet what the interpreter will do is that it will interpret code line by line process the condition and break when it gets 2.
Continue statement causes the loop to skip the remainder of its body and immediately retest its previous condition before iterating. i.e it will skip one iteration from the loop. As shown in the example below
x = 0
while x < 8:
x += 1
if x == 4:
continue
print(x
Output:
1
2
3
5
6
7
8
As you can see in the above code snippet the python interpreter checked the condition and when it got to 4 the interpreter skipped it and continue from the next iteration.
Pass statement is like the saying 'I will pass' Pass statement is used when a statement is required syntactically but do not want any code to execute. Python interpreter does not ignore a pass statement. However, nothing happens and the statement results in no operation. You can learn more about Pass statement here
Below is an example of pass statement
'''pass is just a placeholder for
functionality to be added later.'''
n = {'T', 'i', 'n', 'u'}
for val in n:
pass
In the code snippet above we can see that the result came out to be empty you might be wondering what is going on, like writing some block of codes and running it, then boom! Nothing happened but that is exactly what pass statement does. It is useful when you do not write the execution of a function but you want to execute it later.
Purpose of having a loop in your python code
You might want to ask why is loop important in code or what is the main purpose of loop in python. The answer is not far fetched.
The main purpose of having a loop in your code is to iterate a sequence. This can either be a list, a tuple, a dictionary, a set, or a string. A loop helps to repeat or reiterate a particular statement until the condition is met. Loop is a vital part of programming language because it is applicable in all areas of interest, be it web design, mobile app, or data science.
How to use it
As a code newbie loop can be a bit confusing, yeah. Like the whole while true, else , print indentation can be really confusing for a code newbie. No sweat, take a chill pill that's why I'm here.
This is how it works:
Make sure you are using the right function
Make sure your indentation is correct, I mean it should be on the right track
Make sure your function is well defined
Yippe! We made it through. It was a long ride but I want to believe you now understand the whole concept of having a loop in your python code.
Feel free to drop your comments. It was a great ride yeah?