COS 102 Note 1
COS 102 Note 1
COS 102 Note 1
1
TABLE OF CONTENTS
2
Preamble
This is a set of notes for students of IT Applications and Foundations degree in
IT. These notes have been prepared as to cover some aspects of software
development that usually are omitted from the modules due to time pressures.
Rather than looking in the specifics of languages, web technologies and
development tools, we will look at the main skills that programmers must
develop to be able to use their knowledge effectively for tangible results.
Thus, we will look at the mental skills of analysis and organization of work to
turn the knowledge acquired in IT Apps to produce results.
In this example, the algorithm consists of three steps. Also, note that the
description of the algorithm is done using a so-called pseudocode. A pseudocode
is a mixture of English (or any other human language), symbols, and selected
features commonly used in programming languages. Here is the above algorithm
written in pseudocode:
READ degrees_Farenheit
degrees_Celcius =
(5/9)*(degrees_Farenheit-32) DISPLAY
degrees_Celcius
3
Another option for describing an algorithm is to use a graphical representation in
addition to, or in place of pseudocode. The most common graphical
representation of an algorithm is the flowchart.
READ grade
IF (grade >= 95)
THEN student receives a distinction
In this case, there is also a decision to be made but a more complex one. If the
condition is true only the Accept user step is executed and if the condition is
false only the Deny user step is executed. That is, the condition helps us
make a selection which controls which of the two steps will be executed.
Now look more closely to the condition. Does it guarantee that the user is valid?
What if we had this condition instead, which looks pretty similar: IF (username
in database AND password in database)? What would happen is
somebody typed a valid username but the password of a different but also valid
user? Does this second condition satisfy our requirement that to access this
account one should be the right user and know the corresponding password?
4
Example 3. Decide on a student’s grade based on their coursework mark.
READ result
CASE (result >=90)
PRINT ‘A’
CASE (result >=80)
PRINT ‘B’
CASE (result >=70)
PRINT ‘C’
CASE (result >=60)
PRINT ‘D’
CASE (result <60)
PRINT ‘F’
5
In this case, there are five conditions which are checked, one after the other.
1.3 Repetition.
In Repetition one or more steps are performed repeatedly.
total = 0
average = 0
FOR 1 to 10
Read number
total = total + number
END FOR
average = total / 10
Example 2. Read numbers and add them up until their total value reaches (or
exceeds) a set value represented by S.
6
2. SOFTWARE DEVELOPMENT
A program is a sequence of instructions that a computer follows to solve a
problem. A program is written in a computer language. Most of the languages
have been created to fit particular classes of problems. Python is a versatile
programming language that has been designed to support a wide range of
applications, from web and desktop applications to data analysis and machine
learning. Unlike static languages, Python’s dynamic typing and high-level,
readable syntax allow for rapid application development, making it a popular
choice for developers around the world. The process of collecting requirements,
analyzing a problem and designing its solution as well as writing and maintaining
a computer program is called software development. It is important to note that
for most of this course, Python syntax will be used to write codes that are used
for examples and illustrations in the pages that follows.
1. Problem statement. You are the receiving clerk for an electronics parts
7
distributor that imports large quantities of wire and cable produced abroad and
sold in Nigeria. Most of the wire you receive is measured in meters; however,
your customers order wire by foot. Your supervisor wants you to compute the
8
length in feet of each roll of wire or cable that you stock. You have to write a
program to perform this conversion.
Next, you need to know the relationship between meters and feet. If you do not
know this already you open up a book that explains how you can convert length
measurements or you search on the Web. For example, if you look it up in a
table of conversions factors, you will find that one meter equals 39.37 inches. We
also know that there are 12 inches to a foot. These findings are summarized
below:
We then must decide whether any steps of the algorithm need further
refinement. Steps 1, and 3 need no further refinement. The refinement of step 2
shows how to perform the conversion:
9
4. Implementation. The next step is to implement the algorithm
as a python function.
’’’
Converts wire length from meters to feet.
The user enters the wire length in meters.
’’’
def convert_meters_to_feet(length_in_meters):
length_in_feet = length_in_meters * 3.28084
return length_in_feet
wire_length_in_meters = wmeter
wire_length_in_feet = convert_meters_to_feet(wmeter)
print(f"The length of the wire is {wire_length_in_feet} feet.")
For example:
Wire_length_in_meters = 10
Wire_length_in_feet = convert_meters_to_feet(10)
Print(f’The length of the wire is {wire_length_in_feet} feet.’)
10
A sample output of the program is shown below:
Let’s look at the different elements that we used to create this program.
Variables. Variables are quantities that can retain any value each time a
program runs:
var inchmt
Also wfeet, and inchft are variables. It is very important that variables have
meaningful names, because they make program easier to read, and understand.
If, for example, you name your variables m and f, it would not be straightforward
to remember what they represent.
Each language has special rules that restrict your selection of variable names. In
python, a variable name can be made up of small or capital letters, digits, and
underscore characters and the first character must always be a letter or the
underscore. Other characters, such as blanks, must not appear within a name.
Types. Variable inchmt holds a real value, and inchft holds an integer
value. Reals contain a fractional part, whereas integers are whole numbers.
11
Comments. Any line that starts with # is taken as a comment and thus ignored
by the computer. A comment can also be anything contained between ’’’ and
’’’ for example:
’’’
Converts wire length from meters to feet.
The user enters the wire length in meters.
’’’
and
# Helper variables
5. Testing and verification. Compare the program results with those that
you compute manually or by using a calculator. Keep in mind that programs
often have errors. We distinguish between two types of errors: Syntactic
(grammatical), and semantic (logical) errors.
12
Semantic errors indicate that there is an error in the logic of the program. Some
semantic errors might cause a failure (e.g. divide by zero), others might just
provide wrong results. For example, if we had used
winchs = wmeter + inchmt;
in the example above, then everything would seem to work as required but the
calculated result would be incorrect.
13
3. USING FUNCTIONS FOR MODULAR PROGRAMMING
In the previous section we discussed the divide-and-conquer approach to
program design. The main idea was to divide the overall task in smaller chunks
that we can handle more easily. Sometimes there are tasks that are being
repeated in several points in the program – we would want to write code only
once!
For example, if we want to find the smaller of two variables, we can use
math.min function:
Function MIN gets two arguments: num1 and num2 and returns the minimum of
the arguments that is assigned to the variable minimum
def myfunction(argument1,argument2,etc:
some statements
Example: Let’s write a function that calculates the area of a square given the
length of its side.
14
def square_area(side):
return side*side
Functions that will return a result must use the return statement. This
statement specifies the value that will be returned to the point where the
function was called.
15
4. STRUCTURED PROGRAMMING: SEQUENTIAL STRUCTURE
In section one we learnt that any algorithm (and thus any program) can be
structured using the three basic control structures: sequence, selection, and
repetition. In this and the following sections we will look at each of these
structures in turn, starting with the simplest one, the sequential structure.
16
4. STRUCTURED PROGRAMMING: SELECTION STRUCTURE
The selection structure can take different forms: single selection, nested ifs and
multiple selection. We will discuss each case individually.
Single Selection
is:
Example: The following code fragment reads the time from the system clock and
if it is earlier than 10am it displays the message “Good morning!”
Example: The following code fragment reads the time from the system clock and
if it is earlier than 10am it displays the message “Good morning!” and in every
other case it prints “Good day!”.
Nested IF Statement
def display_result(mark):
if mark >= 90:
print("A")
elif mark >= 80:
print("B")
elif mark >= 70:
print("C")
elif mark >= 60:
print("D")
else:
print("F")
Multiple Selection
The selection structure considered thus far, involved selecting one of two
alternatives. It is also possible to use the IF construct to design selection
structures that contain more than two alternatives. The switch construct is
used to select among multiple alternatives on the basis of a single expression
value. The general form of the case structure is
def switch(expression):
if expression == 'label1':
# code to be executed if expression = label1
pass
elif expression == 'label2':
# code to be executed if expression = label2
18
pass
else:
# code to be executed if expression is different from both label1 and label2
Pass
The expression is evaluated and compared to each selector, where each selector
is a list of possible values of the expression. Only one statement is executed. The
DEFAULT statement is optional and it is obeyed if none of the other CASE
statements produces a match.
We can start with an example: Consider the following price structure for concert
tickets:
Using a nested IF statement, one can have the following structure to assign the
desired value to price or displays an error message if the section is not listed in
the table:
if (section == 50):
price = 50.00;
elif ((section>= 100) AND (section <= 199)) OR (section>= 200) AND (section <= 299)):
print(“price = 25.00”)
elif ((section>= 300) AND (section <= 399)):
print(“price = 20.00”)
elif ((section>= 400) AND (section <= 499)):
print(“ price = 15.00”)
else:
print("Invalid section number”)
19
6. STRUCTURED PROGRAMMING: REPETITION STRUCTURE
The repetition of a block of statements a number of times is called a loop, and is
so important that Python support several different constructs to support this
feature.
In this case, the index variable is initialized at initialization and the code
is executed until condition is reached. At the end of each iteration the
variable is increased by increment.
Example 1: The following program segment will display the first 10 positive
integers:
Example 2: In the following example, the initial value for variable i is 1, and it
is incremented by 2, so the next values will be 3, 5, and so on. The following
segment would display the odd positive integers between 1 and 10.
20
In this example, when the i variable exceeds its final value (i.e. 10), there are
no more repetitions.
The following segment will compute the average of the first ten numbers:
# compute average
average = total / limit
The while statement will execute a block of code while a condition is true.
while (condition)
{
code to be executed
}
i=0
while (i <= 5):
print(" ", i)
i +=1
The DO…WHILE construct
The do...while statement will execute a block of code once, and then it will
repeat the loop while a condition is true
do
{
code to be executed
21
}
while (condition)
22
Example 4. Let’s redo Example 1 using the do..while construct
i = 0
do
{
print(" ", i) i++
}
while (i <= 5)
Summary
Very often when you write code, you want the same block of code to run a
number of times. You can use looping statements in your code to do this. In
JavaScript we have the following looping statements:
● while - loops through a block of code while a condition is true
● do...while - loops through a block of code once, and then repeats the
loop while a condition is true
● for - run statements a specified number of times
23