I know for the first time to under how loops work is a bit difficult. I felt the same way when I was first introduced to loops. In this chapter, I will compare the analogy between "pseudocode", "flow chart", and "python code" for "For
" & "While
" loop.
For Loop
A "For" loop or any other loop allows us to repeat a set code over and again for a specified number of times. Most commonly it is used to count and run a piece of code or a set of instructions.
For example, let's say, I have 5 students in a class and want to find the total marks obtained by the class and also to find the average mark of all the students.
Student Dataset
Pseudocode - For Loop
Now, we have our dataset ready, let's look at a typical pseudocode to calculate the total and average of the above dataset.
Flow Chart - For Loop
Here is the same logic is given as a flow chart.
Let's understand the flow chart,
- The program starts with the
"Start"
operation. - Then, we use the process operation to initialize 3 variables,
- Total to 0
- Average to 0
- i to 0 ( Here i is our counter )
- Next comes the decision block, to check have we executed the code 5 times or not. Here, we execute the logic 5 times because our
"ClassA"
has 5 students. - If we had already executed our calculation 5 times, then we follow the
"Yes"
path or we will follow the"No"
- The
"No"
path repeats the calculation and the "Yes" path completes the iteration. - In the
"No"
path, we accumulate the sum of marks in the "Total" variable. After that, we increment the counter " i " and then return to the decision block. - This repeats until we reach the
"Yes"
path. - Once we finished running the task 5 times, we calculate the average with the use of
"Process"
block. - Then, print the
"output"
and"Stop"
the program.
Python Code - For Loop
Now, we are comfortable with the logic and we know how to use pseudocode and flowchart, let's reproduce the same logic in Python. To count in python, we use we take help of an in-built function called range.
Range returns an object that produces sequences of integers and we will use as a counter.
Enough said, let's directly jump into the code.
#### Let's define our classA
classA = {
'Anitha' : 248,
'Cynthia': 210,
'George' : 240,
'John' : 255,
'Jane' : 280
}
#### Extract the marks
# Don't worry about the code below if you don't understand it quite yet.
# I am just extracting the marks and store them in a list for the ease of handling
marks = [v for k, v in classA.items()]
#### Initialize the variables for the logic
total = 0
average = 0
i = 0
#### Here comes the "For" loop
for i in range(0, 5):
total = total + marks[i]
#### Calculate the Average
# average = total / 5
# or
average = total / len(marks)
#### Output the result
# I am using string interpolation to fill in the curly braces with variables.
print(f"The total mark and average of the class is {total} and {average} respectively.")
While Loop
The "While"
loop in Python is a special kind of loop which allows the user to repeat a piece of code for an unlimited number of times as long as the condition to run the code remains true. The loop can also be terminated by using the "break
" keyword.
Ok, let's take the same students dataset and achieve the same goal that is to calculate the total marks & average mark of the class.
Pseudocode - While Loop
The pseudocode for while
is very similar to For
loop and here it is.
The pseudocode above is very intuitive.
- Declare Average, Total & Counter X and initialize them to 0, 0 & 1 respectively and Initialize the Calculate to True
- We start the loop using the WHILE keyword.
- Run the calculation
- After we accumulated the score for all the 5 students, then we set the Calculate flag to "False".
- End the loop and calculate the average.
Flow Chart - While Loop
Let's look at the flow chart for while loop.
Let's understand the flow chart,
- The program starts with the
"Start"
operation. - Then, we use the process operation to initialize 3 variables,
- Total to 0
- Average to 0
- i to 1 ( Here i is our counter )
- Calculate (
True
orFalse
)
- The only difference between our example "
For
" and "While
" loop is, here instead of checking have we executed the code for 5 times? we evaluate theCalculate
to beTrue
orFalse.
It doesn't matter if we execute the code for 5 or 10 times, all it needs is theCaclucate
flag to beFlase
to terminate the loop. - If the
Calculate
variable evaluates toTrue
, then we follow the"Yes"
path or we will follow the"No"
- The
"No"
path repeats the calculation and the "Yes
" path completes the iteration. - In the
"No"
path, we accumulate the sum of marks in the "Total" variable. After that, we increment the counter " i " and then return to the decision block. - The condition to run the while loop varies based on application. In our case we check have we calculated the total for all 5 students.
- This repeats until we reach the
"Yes"
path. - Then, we calculate the average with the use of
"Process"
block. - Then, print the
"output"
and"Stop"
the program.
Python Code - While Loop
Let's take a look into the code for a while a loop.
#### Let's define our classA
classA = {
'Anitha' : 248,
'Cynthia': 210,
'George' : 240,
'John' : 255,
'Jane' : 280
}
#### Extract the marks
# Don't worry about the code below if you don't understand it quite yet.
# I am just extracting the marks and store them in a list for the ease of handling
marks = [v for k, v in classA.items()]
# Total to accumulate the marks
total = 0
# Average mark of the class
average = 0
# Completed flag
calculate = True
# Counter to store the current student
i = 0
#### Let's calculate the total
while calculate:
total = total + marks[i]
i = i + 1
if i >= 5:
calculate = False
#### Calculate the average
average = total / len(marks)
#### Print the results
print(f"The total mark and average of the class is {total} and {average} respectively.")
Workbook
Click here to download the workbook.