Let’s jump directly into some programming. Using concepts learned so far, let’s create a program to calculate the average height of three students (three_average.py)
three_average.py |
# program to calculate average height of three students # get input of height _a1= float(input(“Enter height of first student (cm): “)) _a2= float(input(“Enter height of second student (cm): “)) _a3= float(input(“Enter height of third student (cm): “)) # use the formula for average = Sum of values/ total number of values _avg=(_a1+_a2+_a3)/(3) # print the output print(“The average height is: “, _avg) |
At the output we get,
Creating a More Versatile Program
While the initial program successfully calculates the average height of three students, it falls short in scenarios involving a larger number of students. Consider a situation with ten students—writing ten input commands for each student’s height isn’t practical. Furthermore, creating a new program for each change in the number of students is inefficient.
To address these issues, we need a single program capable of accommodating various scenarios. The key to achieving this flexibility lies in the concept of loops.
Introducing Loops
Loops are a fundamental programming structure that enables us to repeat a sequence of instructions multiple times. In essence, they help us automate tasks that need to be executed a certain number of times.
One common and powerful type of loop is the ‘for’ loop. Below is a typical syntax for using a ‘for’ loop:
for _num in range(0, 5, 1):
print(“hello”)
If executed, we will get the output below
Let’s delve into the ‘for‘ loop, a fundamental programming construct used for repeating a sequence of instructions. To illustrate this concept, let’s break down the components of a ‘for’ loop used in our example:
for _num in range(0, 5, 1):
# Code inside the loop
- ‘_num’ – The Variable: In Python, you can use any variable as the loop control variable. Here, we’ve used ‘_num’ as an example, but you can choose a variable name that suits your needs.
- The
range()
Function: Therange(0, 5, 1)
defines the behavior of the loop.- ‘0’ is the initial value assigned to ‘_num.’
- ‘5’ is the final or limiting value for the variable. This means the loop will continue as long as ‘_num’ is less than ‘5.’
- ‘1’ is the increment by which ‘_num’ will increase its value. With each iteration of the ‘for’ loop, ‘_num’ will start at 0, increase to 1, then to 2, and so on.
- ‘Upper Bound’ Exclusivity: Python follows the ‘upper bound’ exclusive rule (Remember Strings and Lists!). This means that while ‘5’ is defined as the limiting value, the loop will stop just before ‘_num’ reaches it. So, the maximum value ‘_num’ will reach is ‘4’ (0, 1, 2, 3, 4).
What is part of the loop that will get executed?
For example
for _num in range(0, 5, 1):
print(“hello”)
print(“Namaskar”)
print(“End of program”)
The two commands, print(“hello”) and print(“Namaskar”) are indented below the ‘for’ command, so they are part of the loop and will get repeated ‘5’ times as the value of ‘_num’ increases (0, 1, 2, 3, 4).
Whereas print(“End of program”) is not part of the loop, hence will be executed only once.
Using a ‘for’ Loop to Calculate Average Height
In our program for calculating the average height of students, we can employ a ‘for’ loop to streamline the input process. By specifying the upper bound of the loop with the total number of students, we can control the repetition of the ‘Input’ command:
_total = int(input(“Enter the number of Students:”))
for _num in range(0, _total, 1):
_height = float(input(“Enter height of Student: “))
If, for example, you enter ‘5’ as the number of students, the loop will repeat five times, allowing you to input the heights for each student.
The next step is to calculate the average height. The formula for average height is:
Average height = (Sum of all heights) / (Total number of students)
To calculate the sum of all heights, we can use the ‘_height’ variable, which stores a single height value at any given time. We’ll utilize the technique of manipulating a variable with itself. To do this, we’ll define a new variable, ‘_sum’, and continuously add ‘_height’ to it:
_sum = 0 # Initialize _sum to 0
for _num in range(0, _total, 1):
_height = float(input("Enter the height of Student: "))
_sum = _sum + _height
To avoid confusion, we declared the initial value of ‘_sum’ to be ‘0’.
_total = int(input(“Enter the number of Students:”))
_sum = 0
for _num in range(0, _total, 1):
_height = float(input(“Enter height of Student: “))
_sum = _sum + _height
_avg = _sum/_total
print(“The average height is: “, _avg)
The output run of our program is
Initializing ‘_sum’ to ‘0’ helps avoid confusion and ensures that we start with a clean slate for each calculation. As the loop iterates, ‘_height’ values will be accumulated in ‘_sum’, which can later be used to calculate the average height.
This systematic approach allows us to efficiently determine the average height of any number of students while simplifying the input and calculation process.
Ideally, the program should have prompted ‘Enter height of first student:’ and so on. Aside from this cosmetic inconsistency, the core of our program works fine.
So let’s understand this program in a stepwise algorithm.
Step No | Command | Interpretation | Parameter Values | Comment | |
1 | _total = int(input(“Enter the number of Students:”)) | Ask user to input value for total number of students | _total = 3 | ||
2 | _sum = 0 | Initialize value for ‘_sum’ variable | _total = 3
_sum = 0 | ||
3 | for _num in range(0, _total, 1): | begin ‘for’ loop | _total = 3
_sum = 0 _num = 0 | ||
3.L.1 | _height = float(input(“Enter height of Student: “)) | Ask user input for height of first student | _total = 3
_sum = 0 _num = 0 _height =131 | within loop | |
3.L.2 | _sum = _sum + _height | Modify ‘_sum’ variable | _total = 3
_sum=0 +131 =131 _num = 0 _height =131 | ||
3.L.3 | Loop step executed
check if range end is reached (upper – bound exclusive) | Is _num ≥ (_total-1)
True or False | 0 ≠ 2 (3 – 1)
FALSE | This step is executed internally | |
3.L.4 | If FALSE go back to step 3 (3.L.1)
increase range variable by step size | _num=_num+1 | _total = 3
_sum =131 _num =0+1 =1 _height =131 | This step is executed internally | |
3.L.1 | _height = float(input(“Enter height of Student: “)) | Ask user input for height of second student | _total = 3
_sum = 131 _num = 1 _height =140 | within loop – overwrite _height | |
3.L.2 | _sum = _sum + _height | Modify ‘_sum’ variable | _total = 3
_sum=131+140 =271 _num = 1 _height =140 | ||
3.L.3 | Loop step executed
check if range end is reached (upper – bound exclusive) | Is _num ≥ (_total-1)
True or False | 1 ≠ 2 (3 – 1)
FALSE | This step is executed internally | |
3.L.4 | If FALSE go back to step 3 (3.L.1)
increase range variable by step size | _num=_num+1 | _total = 3
_sum =271 _num = 1+1 =2 _height =140 | This step is executed internally | |
3.L.1 | _height = float(input(“Enter height of Student: “)) | Ask user input for height of Third student | _total = 3
_sum = 271 _num = 2 _height =149 | within loop
overwrite _height | |
3.L.2 | _sum = _sum + _height | Modify ‘_sum’ variable | _total = 3
_sum=271+149 =420 _num = 2 _height =149 | ||
3.L.3 | Loop step executed
check if range end is reached (upper – bound exclusive) | Is _num ≥ (_total-1)
True or False | 2 = 2
TRUE | This step is executed internally | |
3.L.4 | If TRUE, End of Loop | _num=_num+1 | _total = 3
_sum =420 _num = 2 _height =149 | LOOP END | |
4 | _avg = _sum/_total | calculate _avg | _total = 3
_sum =420 _num = 2 _height =149 _avg=420÷3=140 | ||
5 | print(“The average height is: “, _avg) | print output | _avg = 140 | END of PROG |
Check the final value of ‘_num’ it is ‘2’ (Upper bound — 1)
Next, the ‘_height’ is holding the latest value of height. Thus we need a ‘_sum’ variable to capture the values as we repeat the loop, and ‘_height’ gets overwritten.
You can also view the stepwise change in the value of variables easily in ‘Thonny’
Open Thonny, and as shown below, in the top pane, go to ‘Run’ options
under which you will find an option to ‘Debug current script (nicer)’ click on it – enter the debug mode.
Once in debug mode, to move from one line of the program to next, in the same ‘Run’ option, we have the option to ‘Step into.’ It is more convenient to use the ‘F7’ key as we have to keep on clicking it until the program ends.
As you move through the code stepwise, in the variables window, you can see the value of variables change right next to your program window. (In case you are unable to see to Variables window, in the top pane, go to ‘view,’ in which tick on variables window)
A stepwise Algorithm becomes slightly tedious to follow, especially for loops. Hence a graphical flow representation is preferred, defined as ‘Flowchart.’
The average program is not storing individual heights values as the loop overwrites the ‘_height’ variable at every execution. In case we need to recall the height of a particular student, we will need to add a few more lines to our code.
Firstly, we will need to store all heights. A great way of storing all the heights together will be a ‘list.’
Secondly, we can use’ dictionaries’ for associating the name of a student with the corresponding height.
We need to do all this before we overwrite the ‘_height.’ So it should be a part of the loop. Plus, we need the lists to be ‘dynamic.’ We mean by ‘dynamic’ that the number of members in a list needs to be flexible.
Enhancing the Average Height Program with Lists and Dictionaries
The original average height program doesn’t store individual height values as the ‘_height’ variable is overwritten with each iteration of the loop. To recall the height of a specific student, we’ll make a few modifications.
Storing Individual Heights:
- We’ll use a ‘list’ to efficiently store all the heights together.
- Lists offer dynamic sizing, adapting to the number of students. We can use the ‘append()’ function to add new members to a list.
- Example:
_items = [23, 41, 5, 100]
_items.append(77)
will increase the list size dynamically to[23, 41, 5, 100, 77]
.
- Example:
Associating Students with Heights:
- We’ll use ‘dictionaries’ to associate each student’s name with their corresponding height.
- Dictionaries don’t have a specific order; they pair keys with values.
- Example:
_months = {1: "Jan", 2: "Feb"}
_months[3] = "Mar"
will update the dictionary to{1: "Jan", 2: "Feb", 3: "Mar"}
.
- Example:
To implement these enhancements, we’ll integrate lists and dictionaries into our program, creating a new script called ‘avg_with_storage.py.’
The output is as below
Conditionality
Branching |
As seen in the flowchart, the ‘for’ loop’s execution includes a ‘condition’ check. This check can be expressed in detail as follows
for _num in range(0, 5, 1): Is _num ≥ 5 ? NO : Execute statements within ‘for’ loop YES: Exit the ‘for’ loop The same logic can we written in a slightly different format — If _num ≥ 5 then execute the commands else exit The ‘If…..else…..’ statements come under a category called as ‘Conditionality’ statements. Technically they introduce ‘branching’ in the code. |
Comparing Student Heights with the Average
To enhance our average height program, we can introduce branching to provide different output based on certain conditions. For instance, we can prompt the user to enter a student’s name and then determine whether that student has an above-average height, below-average height, or an average height.
To implement this feature, we’ll add ‘if’ and ‘elif’ (else if) statements to our code:
avg_with_storage.py |
# ask for name of student for comparison _compare = input(“Enter name of student for comparison: “) # extract value of height from dictionary _cheight = _students[_compare] # if else branching to compare height with Average if _cheight > _avg: print(_compare,“s height is more than average”) elif _cheight < _avg: print(_cheight,“s height is less than average”) elif _cheight == _avg: print(_compare,“s height is same as the average”) |
The output after adding the code to ‘avg_with_storage.py’ and creating a new file (compare_average.py)
In the ‘elif’ command for checking if _cheight
is equal to _avg
, the symbol used for “equal to” is ‘==’.
elif _cheight == _avg:
For the other comparison operations the symbols are as below —
No | Description | Syntax |
1 | A Greater than B | A > B |
2 | A Less than B | A < B |
3 | A Greater than or equal to B | A >= B |
4 | A Less than or equal to B | A <= B |
5 | A Equal to B | A == B |
6 | A Not equal to B | A ! = B |
Summary
This chapter introduces the concept of loops and conditional statements in programming. It focuses on the creation and enhancement of a program for calculating the average height of students, while also providing explanations of the key programming elements introduced.
- Introduction to Loops and ‘for’ Loop: The chapter begins by introducing the ‘for’ loop, a fundamental programming structure that repeats a sequence of instructions until a specific condition is met. It explains the syntax of the ‘for’ loop and demonstrates how it can be used to repeat a task a certain number of times, making it efficient for scenarios involving multiple data points.
- Stepwise Algorithm Explanation: The chapter provides a stepwise algorithm for the average height program, highlighting the input of student heights and the calculation of the average height within the ‘for’ loop. It also explains the concept of the upper bound exclusive rule in Python.
- Enhancement with Lists and Dictionaries: The text emphasizes the need to store individual height values and introduces ‘lists’ and ‘dictionaries’ as powerful data structures. Lists are employed to dynamically store all heights, while dictionaries are used to associate students’ names with their heights. This ensures data integrity and flexibility as the number of students can change.
- Conditional Statements and Branching: The chapter demonstrates the use of conditional statements (if and elif) to compare individual student heights with the calculated average. It explains the syntax of these statements and provides a reference for comparison operators, showing how to determine whether a student’s height is above, below, or equal to the average.
- Creating a Comprehensive Program: Finally, the chapter combines all the elements to create a comprehensive program for calculating the average height, storing individual heights, and comparing heights. The code is organized into separate scripts, making it modular and easy to manage.
In summary, this chapter provides a foundational understanding of loops, conditional statements, data structures, and how to use them to solve practical problems in programming. It demonstrates a step-by-step approach to creating programs, making them more versatile and informative.
Technical Note: The functions that we used for strings, lists, like capitalize( ), append( ), etc., are technically referred to as ‘methods.’ Because, later on, we will see that python allows us to create some ‘user-defined functions.’ Hence, for clarity, the ‘method’ terminology is used.
Exercise
- Prompt the user to enter the name of a student and his score in English on a scale of 100. Proceed towards calculating the average of the class. The grade is assigned as per below formula.
Score above average = A Grade
Average score = B Grade
Score below average = C Grade
Prompt user for a name of the student, and return the calculated grade for that student.
- Prompt the user to define the distance on a race track. Ask for the number of drivers on the track. Prompt for the name of the driver, and the time in minutes taken to complete the race. Calculate the speed of each driver in m/min, and display each drivers speed.
- Ask the user for input on the account balance of a bank client. also ask for the input on his outstanding loan. Compare the account balance and the outstanding to return whether the client is in default or not.
- In problem no 2, prompt for the names of the two drivers, determine who is the faster one amongst the two, and also display the percentage amount by which one driver is faster than the other.
- Create a program to compare the number of letters in the names of two people and return whose name is longer than the other person.
[…] Prev Chapter Course Homepage Next Chapter […]
simple and effective programming