Program Design
Program Design
Mark demarcation
There are two parts to writing a program – designing the code and writing the
code. Once the logic of the design has been checked and corrected, the
design is ready to be translated into code. Much time can be wasted in trying
to find logical errors in a program that has been coded without a properly
checked design. Just as a builder should never build a house without a
properly drawn-up plan, one should never code a program without a proper
design.
In the Processing and Logic Concepts module, you learnt about program
flowcharts as a means of describing the flow of logic in a program.
3. Programming Languages
There are many programming languages worldwide. Some of them, like C or
C++, are used for engineering applications or are used in game development,
while programs such as C#, Java and VB.NET are used in commercial
development and web development. Most of them use commands based on
the English language.
Programming languages are described as either low level or high level. The
closer the language is to machine code, the lower the level. Low-level
languages use ones and zeroes, and communicate directly with the
computer’s processor, whereas the high-level languages are more
English-based and need to be converted to zeroes and ones that can be
interpreted by the processor. The languages mentioned in the preceding
paragraph are all examples of high-level languages.
Given the simplicity of Python’s syntax, you won’t need to memorise lots of
sections of code that are included in many different places.
6. CodeRunner
Programming examples provided in this module will be implemented in
CodeRunner. CodeRunner provides you with a platform to run a program; in
this case it will be a Python program. You will encounter CodeRunner when
you start the exercises in this module
To test your code, click the Check button to see if the code passes the tests
defined in the exercise/illustration.
1. Introduction
The concepts discussed in this section are essential to anyone who wants to
become a programmer. These concepts are present in the majority of
computer programming languages and/or are a fundamental part of the
programming process. We will explore some of these concepts practically in
this module.
2. Algorithm
An algorithm is set of steps for carrying out a specific task. Algorithms are
used extensively in computer programming to arrive at a solution for a
problem. The process of creating an algorithm involves documenting all the
necessary steps needed to arrive at the solution and how to perform each
step. A real world example of an algorithm would be a recipe. The instructions
of a typical recipe (add ingredients, mix, stir etc.) are an algorithm
3. Variable
4. Data Type
A datatype is the classification of pieces of information in a program. The
amount of different data types varies between languages. Typically, there are
data types for integers (whole numbers), floating-point numbers (numbers with
a decimal part) and single characters. To distinguish between different data
types, a computer uses special internal codes.
5. Constant
A constant is the same as a variable with one major difference – the value of a
constant does not change, while the value of a variable can change
throughout a program.
6. Conditional
A conditional is set of code that will execute only if a certain condition is true.
Conditionals are used to test expressions and perform certain operations
accordingly. For example, you could test a number input by a user and if it is
too high, it prints the message, "The number entered is too high" and the
program exits. Thanks to conditionals, a program can work differently every
time it runs
7. Array
An array is a special type of variable used in many programming languages
that contains a list of related values. For example, a colour array would
contain a list of colours.
8. Loop
A loop is a segment of code that executes repeatedly based on a certain
condition. Loops are used to perform tasks a number of times. For example, if
you needed to print the numbers 1 to 10, you can use a loop for this task
instead of manually printing all the numbers.
9. Function
A function is a set of code used to carry out specific tasks. A function can take
parameters which will affect its output as well as return values. Functions
prevent unnecessary code because you can use them as much as needed
instead of retyping certain code over and over. For example, if you need to
multiply two numbers, instead of doing the calculation manually every time,
you can supply the data to a function through some parameters that will do it
for you.
Text str
Sequence list
str – Strings – These are a sequence of Unicode characters, e.g. a word or a sentence that can be
manipulated. Strings are represented by the immutable (unchangeable) str data type.
int – Integers – These represent numbers in an unlimited range. This is only limited by a machine’s
memory. Integers are always whole numbers. Integers include negative and positive numbers, e.g.
8, 40, −3 etc.
float – Floating point numbers – Floating point numbers represent double precision numbers, e.g.
78.93.
list – List – A list is a collection that can hold data of any type, with a dynamic number of objects.
Lists use [] (square brackets) to define their elements.
In Python, the data type is set when you assign a value to a variable:
x = 20 int
x = 20.5 float
x = range(6) range
Casting Python Data Types
There may be times when you want to specify what data type a variable should be or change the
type of a specific variable.
This is known as casting. Casting in Python is done using predefined casting functions:
x = int(20) int
x = float(20.5) float
Input
Input is data provided to the program by a user. In this module, all input is provided by myLMS and
will be illustrated in the block below. The result in the block below is the output of the program and
will be explained more in the output section of this quiz.
Note:
Program languages allow developers to add human-readable text to explain the code in a program.
These are known as comments. In Python, a single-line comment starts with a hash (#). All 'code'
after the # is seen as a comment and will not be executed as part of the program. Multi-line
comments in Python are surrounded by ''', for example:
'''
multi
line
comment
'''
For example:
Input Result
input input
input Provide input data: input
data data
Processing
Processing refers to the alteration or manipulation of the data and/or input data. Let's look at a
simple example of how we can manipulate variables with arithmetic logic operators, arrays and
functions. Arithmetic logic, as well as other operations, are explored further in Unit 2 – Logic
Operations and Control Statements. Arrays and functions are explored further in Unit 3 and Unit 4
respectively.
Output
Output refers to user feedback. It is usually the result of the input data after it has been processed.
Let's look at how to provide output in Python using the print() function
+ Add x+y
- Subtract x-y
* Multiply x*y
/ Divide x/y
% Modulus x%y
(Get the remainder of a division)
** Exponential x ** y
// Floor Division x // y
(Result of division in which the digits after the decimal point are removed)
Example: For arithmetic operators, we will take the simple example of addition where we will add two
digits: 4+5=9
x= 4
y= 5
print(x + y)
Similarly, you can use other arithmetic operators for multiplication(*), division (/), subtraction (-), etc.
not Reverses the result; returns False if the result is true not(x < 5 and x < 10)
Example: Here is an example where we get true or false based on the value of a and b.
a = True
b = False
print(('a and b is',a and b))
print(('a or b is',a or b))
print(('not a is',not a))
== Equal x == y
!= Not equal x != y
Example: For comparison operators, we will compare the value of x to the value of y and print the
result as either true or false. Here in the example, the value of x = 4, which is smaller than y = 5, so
when we print the value as x>y, it actually compares the value of x to y and since it is not correct, it
returns false.
x = 4
y = 5
print(('x > y
is',x>y))
not in Returns True if a sequence with the specified value is not present in the x not in y
object
Example: For example, here we check whether the value of x = 4 and the value of y = 8 are
available in the list or not by using in and not in operators.
x = 4
y = 8
list = [1, 2, 3, 4, 5 ];
if ( x in list ):
print("Line 1 - x is available in the given
list")
else:
print("Line 1 - x is not available in the
given list")
if ( y not in list ):
print("Line 2 - y is not available in the
given list")
else:
print("Line 2 - y is available in the given
list")
2.2 Batch Processing vs Online Processing
Batch processing occurs when the program receives its input from a file and there is no interaction
with the user of the program. When dealing with file input, the read statement must be used when
entering data into the program.
Online processing occurs when the program is interactive and the user is prompted by the program
to enter input using the keyboard. When dealing with file input, the input statement must be used
when entering data into the program.
2.2.3 Repetition
Repetition statements are used to execute a set of statements continuously if a specified condition
remains true. As soon as the condition changes to false, the set of statements is skipped and
execution continues from the line following the repetition statement.
● for
Executes a series of statements a fixed number of times.
● while
The while repetition statement (or while loop) repeatedly executes the statements in a loop
for as long as the loop continuation condition remains true. The loop continuation condition
follows the while keyword.
As soon as the condition becomes false, the loop exits. The while loop is used when a
programmer wants to execute a specific statement or set of statements repeatedly, but does
not know exactly how many times the statements will be executed.
For example, a sales manager may want to calculate the total sales achieved by all
salespersons during a month. For this, the manager may enter the sales amount of each
salesperson into a program and accumulate the sales amounts. Although the manager may
know the total number of salespersons to enter, what would happen if another manager
wanted to use the same program but had a different number of salespersons? The while
loop would allow both managers to use the same program, regardless of the number of
salespersons each needed to enter.
2.3 Control Structures
Program control structures are used to transfer control from one part of a program to another.
Sequence – Program performs tasks in sequence (in the order in which they were written).
Selection – Program performs a task depending on the validity of a given condition.
Repetition – Program performs a task repeatedly until a condition is satisfied.
Input Result
8 Input number:
20 8
20
33
The beginning of the if statement is denoted by the keyword "if", followed by the condition to be
tested (in this case amount > 1000). The condition is followed by the mandatory keyword "then".
The statements following the "then" keyword must appear on separate lines (one line per statement).
In the above example, only one statement, rate = 0.2, is needed. The "endIf" keyword denotes the
end of the if statement. Also note that statements within the if…endIf block must be indented. This is
to improve the readability of the program.
The following shows the equivalent if statement as it would be shown in Python using CodeRunner.
The if statement is similar to the one shown in Section 2.3.2.1. It checks the value of the amount
variable, and if this exceeds 1000, the rate is set to 0.2. If the amount is less than or equal to 1000,
the rate is set to 0.1. This is indicated by the "else" keyword. Any statements that occur between the
"else" and "endIf" keywords are executed when the condition in the if statement is false.
The "endIf" keyword denotes the end of the if statement. Once again, the interest is calculated after
the execution of the rate variable has been set by the if statement.
The following shows the equivalent if statement as it would be shown in Python using CodeRunner.
Depending on the value of the mark, the else if block for which the condition is true will be executed.
For example, if the value of the mark is 77, the program first tests the condition mark >= 80.
Because the mark is less than 80, the program skips the condition and moves on to the next
condition (mark >= 70). Because the condition is now satisfied, the program executes the statement
inside this else if block and prints "Well done".
It is important to realise that the program will now exit the if statement completely and execute the
first line following the "endIf" keyword, if any. An if statement always executes the code after the first
condition in the set of else if statements is true and then exits the statement.
In the above example, although the next else if statement (else if mark >=60) also satisfies the
condition, it is not executed because the previous statement (else if mark >= 70) has already
satisfied the condition.
Also note that the final else in the if construct could have been replaced by else if mark >= 0 then. It
is not necessary for the final statement in a series of else if statements to be an else. The "else"
keyword is optional. The following shows the equivalent if statement as it would be shown in Python
using CodeRunner.
2.3.3 Repetition Structure
Repetition statements are used to execute a set of statements continuously if a specified condition
remains true. As soon as the condition changes to false, the set of statements is skipped, and
execution continues from the line following the repetition statement.
In Python, the iterative statements are also known as looping statements or repetitive statements.
The iterative statements are used to execute a part of the program repeatedly as long as a given
condition is true. Python provides the following iterative statements:
● while statement
● for statement
for
while
The while repetition statement (or while loop) repeatedly executes the statements in a loop for as
long as the loop continuation condition remains true. The loop continuation condition follows the
"while" keyword.
As soon as the condition becomes false, the loop exits. The while loop is used when a programmer
wants to execute a specific statement or set of statements repeatedly, but does not know exactly
how many times the statements will be executed.
For example, suppose that a program requires that only numbers from one to ten may be entered by
a user. The following while statement can be used to check a value entered, print a message if the
value is invalid, and allow the user to re-enter the value:
input number
print "You must enter a number from 1 to 10" #prompt user for correct
number
endWhile
●
Note that a number is first entered by the user. The number is then checked using the while
condition. Note that the while loop checks for an incorrect value, outside of the range of
numbers from one to ten. The purpose of this is to prompt the user to re-enter the value of
the number, and allow him or her another opportunity to do so.
The while loop ensures that the user enters a number in the range from one to ten, and will
not continue past the endWhile statement until a valid number is input.
Let us look at the implementation of the pseudocode example in Python.
Just like any other programming language, Python contains its own syntax rules.
Indentation Rule
Indentation refers to the spaces at the beginning of a code line. Where in other programming
languages the indentation in code is for readability only, the indentation in Python is very
important. Python uses indentation to indicate a block of code. Python will give you an error if
you skip indentation.
The number of spaces is up to you as a programmer, but it has to be at least one. You have to
use the same number of spaces in the same block of code, otherwise Python will give you an
error.
1. Python Syntax
Just like any other programming language, Python contains its own syntax
rules.
Indentation Rule
Example 1
A university wants a print-out of how many students failed the first year mathematics final
examination. Each record contains the student’s number, name, mathematics score and maximum
score possible. Each student must have a report printed with his or her number, name, percentage
and a remark stating whether a pass or fail is achieved (50% and above is a pass). Processing
continues until a student number of 0 is entered. Count how many students failed, as well as the
total number of students, and print these totals.
Pseudocode:
begin
totFail = 0
totStud = 0
input num
while num ≠ 0
input name, studScore, maxScore
perc = studScore / maxScore * 100
if perc >= 50 then
msg = “pass”
else
msg = “fail”
totFail = totFail + 1
endIf
totStud = totStud + 1
print num, name, perc, msg
input num
endWhile
print totFail, totStud
end
● The total number of students processed and the total number of failures are initialised to
zero.
● The first student’s number is input and the condition is tested before entering the loop. If this
number is 0, the loop will not execute. If the student number is not equal to 0, the rest of the
student’s data is input and processing begins.
● Remember that the student number is used as an exit condition for the program. Entering the
number separately from the rest of the student data is necessary to prevent the program
prompting the user to enter student data when the user wants to exit.
● For each record the percentage is calculated. If the percentage is greater than or equal to
50, “pass” is assigned to the message variable, otherwise “fail” is assigned, and the total
number of failures is incremented.
● The number of students in total is incremented.
● The record is printed and the next record is input, tested and processed.
● Processing stops when a student number of 0 is entered, at which point the total number of
failures and the total number of students processed are printed.
For example:
Input Result
32 32
David David
30 30
100 100
0 32 David 30.0
fail
0
1 1
Arrays
An array usually has a fixed number of items or elements. Each element has a value. A program can
locate any element within the array. It takes no more time to locate element number 8 than it does to
locate element number 0. For this reason, an array is known as a random access data structure. The
figure below visually depicts an array with ten positions and its features.
There are four collection data types in the Python programming language:
1. A list/array is a collection that is ordered and changeable. It allows duplicate members.
2. A tuple is a collection that is ordered and unchangeable. It allows duplicate members.
3. A set is a collection that is unordered and not indexed. It does not allow duplicate members.
4. A dictionary is a collection that is unordered, changeable and indexed. It does not
allowduplicate members.
Lists and arrays are used in Python to store dataBoth can be indexed and iterated. Arrays need to
be declared whereas lists do not need declaration because they are a part of Python's syntax. Only
lists and arrays will be covered in this module.
Example
# Initializing an array
# The following line sets the variable name cars, to an array with 3 string elements:
# You can use the for loop to iterate through all the elements of an array.
for x in cars:
print(x)
y = cars[0]
print(y)
cars[0] = "Toyota"
print(cars[0])
# The following code snippet shows how the marks are loaded into the array
array = []
for m in range(5):
mark = input() # takes a string input
mark = int(mark) # converts the mark variable to an int
array.append(mark) # insert the mark variable into the array at the next available index
# append() method described in next section
print(array)
Array Methods
Python has a set of built-in methods that you can use on lists/arrays.
Method Description
extend() Adds the elements of a list (or any iterable) to the end of the current list
index() Returns the index of the first element with the specified value
Example
# Refer to the method descriptions above for the following examples
# Example 1:
cars.append("Honda")
print(cars)
# Example 2:
cars.pop(1)
print(cars)
# Example 3:
cars.remove("Ford")
print(cars)
An array index tells us the position or address of a particular element in the array. The array index is
enclosed in square brackets. In this example, the indices are the numbers zero to three.
One of the most important things concerning arrays is to understand what exactly is being stored in
the array. This will help greatly when dealing with array questions in assessments. For example, the
array below holds the English marks obtained by a student in each term during the year.
The following snippet shows how the marks are loaded into the array using pseudocode. Note the
use of the for loop once again when dealing with arrays and that the index (t) of the for loop is the
same variable as the index of the array.
for t from 1 to 4
input mark
marks[t] = mark
endFor
To calculate the average for the student, a for loop is used to accumulate the marks for the four
terms. This total is then divided by four.
begin
totTerm = 0
for t from 1 to 4 #Load the array
input mark
marks[t] = mark
totTerm = totTerm + marks[t] #Accumulate the marks
endFor
ave = totTerm / 4 #Calculate the average mark
print “Pupil average”, ave
end
Python example
Example 2
In the following example, the same array is used as in the previous example to calculate the term
with the highest mark and the term with the lowest mark. The following variable names have been
used:
● Highest mark in a term: hiMark
● Lowest mark in a term: loMark
● Term with the highest mark: hiTerm
● Term with the lowest mark: loTerm
begin
hiMark = 0
loMark = 999
totTerm = 0
for t from 1 to 4
input mark
marks[t] = mark
if marks[t] > hiMark then
hiMark = marks[t]
hiTerm = t
endIf
if marks[t] < loMark then
loMark = marks[t]
loTerm = t
endIf
totTerm = totTerm + marks[t]
endFor
ave = totTerm / 4
print “Pupil average ”, ave
print “Best term”, hiT, “Marks =”, hiMark
print “Worst term”, loT, “Marks =”, loMark
end
● The highest mark for a term is initialised to zero. This is because all elements in the array will
most likely be greater than zero.
● The lowest mark for a term is initialised to 999. This is because all elements in the array will
most likely be less than 999.
● The total mark variable (for all four terms – i.e. totTerm) is initialised to zero before entering
the for loop.
● The processing for loop will execute four times (once for each term and equivalent to the
number of elements in marks[4]).
● Each time the loop executes, the contents of the array is compared with the highest mark
(hiMark) and the lowest mark (loMark) found so far. The first time the loop executes, the
array element marks[1] contains the value of 60 (the value of marks[1]). As 60 is greater than
0, the value of hiMark is changed to 60. Because 60 is also less than 999, the value of
loMark is changed to 60. The term number, which is equal to the current index value of the
for loop, is stored in the variables hiTerm and loTerm.
● The second time the loop executes, the array element marks[2] equals 85. As 85 is greater
than 60, hiMark is assigned the value 85. Because 85 is greater than 60, loMark remains 60.
This process of comparing and replacing values where necessary continues until the loop
has executed four times.
● After the last repetition of the for loop, hiMark will contain the highest mark in the array and
loMark, the lowest mark.
● The average is calculated.
● The average is printed as well as the highest and lowest marks obtained for any term and
the term in which these marks were obtained.
Python Example
Two-Dimensional Arrays
A two-dimensional array is an array within an array. It is an array of arrays. In this type of array, the
position of a data element is referred by two indices instead of one.
Two-dimensional arrays are often used to represent tables of values in a row and column structure.
The first dimension of the array represents the row of the table and the second dimension represents
the table column, as depicted below.
Such data for four days, as shown above, can be presented as a two-dimensional array:
myArray =[[23,27,11,12],[6,10,14,5],[25,10,17,18],[8,9,15,12]]
To print out the entire two-dimensional array we can use a Python for loop, as shown below. We use
end of line keyword to print out the values in different rows.
0 1 2
0 1 2 3
1 4 5 6
2 7 8 9
Output
Example 1
A car rental company keeps track of the kilometres driven by each of its cars in a week. The
following array stores the number of kilometres driven by each car in a day.
The kilometres are stored for each of the five cars, for each day of the week. For example, Car 2
drove 43 kilometres on Friday (day five of the week). The number of kilometres driven for each car is
entered at the end of each week.
We want to find the combined average of all the cars’ kilometres driven in a week. The following
variable names are used:
● Total kilometres driven by all five cars for a whole week (seven days): totCarsKilos
● Total kilometres driven by each car for a whole week: totCar
● Average kilometres driven by a car in a day: average
begin
totCarsKilos = 0 # Total of all 35 input kilometre readings
for c from 1 to 5 # Load the array – first dimension, start with the
first car.
totCar = 0 # Total for kilometres driven by each car; reset to 0
for each car
for w from 1 to 7 # This is the second dimension, start with day
1
input kilos
kilometres[c, w] = kilos
totCars = totCar + kilometres[w, c]# Accumulating kilometres
for current car
endFor
totCarsKilos = totCarsKilos + totCar # Accumulate overall total
for all cars
endFor
average = totCarsKilos / (7 * 5) # or average = totCarsKilos / 35
print “Average kilometres driven by a car in a day: ”, average
end
Note the following points about the example:
The total amount of kilometres driven by all five cars in a week (totCarsKilos) is initialised before the
first for loop is entered. When both the for loops have finished executing, totCarsKilos will contain all
35 records of the kilometre readings in a week. We can then calculate the overall average distance
that the five cars drive in a day simply by dividing this total by 35. This is done on the first line of
code after the outer for loop.
A variable to store the total kilometres driven for a specific car (totCar) is initialised to 0 immediately
after the first for loop header (for c from 1 to 5). This is an important point to remember about arrays.
Any total that is initialised within a for loop applies to whatever item that for loop describes. In this
case, the for loop describes the car’s kilometres driven. Therefore, a total initialised program will
accumulate to the total for each car’s kilometres driven in a week, when the inner for loop has
finished executing.
The variable totCarsKilos is accumulated after the user has input the number of kilometres. Once all
seven kilometre readings have been input for the first car, the inner for loop ends, and the line
between the two endFor statements is executed. At this stage, totCar holds the total kilometres
driven in a week by the first car (c = 1). This total is added to the totCarsKilos variable to accumulate
the total kilometres of all the cars, one car at a time.
The outer for loop now executes for a second time and c = 2. The variable totCar accumulates the
kilometres driven in a week for the second car, and this total is added to the totCarsKilos once more.
This is repeated for all five cars before the overall average is calculated and printed.
Python example
Example 2
Using the same specifications as in the two-dimensional array (Example 1), determine the car(s)
with the highest average of kilometres driven in a day, as well as the average kilometres driven in a
day by all cars. Assume there may be more than one car with the highest average of kilometres
driven.
begin
totCarsKilos = 0
hiAve = 0
for c from 1 to 5
totCar = 0
for w from 1 to 7
input kilos
kilometers[c, w] = kilos # Load kilometers input into array
totCar = totCar + kilometers[c, w]
endFor
ave[c] = totCar / 5 # Stores cars averages in a one-dimensional
array
if ave[c] > hiAve then # Checks for a higher average
hiAve = ave[c] # Stores the highest average so far
endIf
totCarsKilos = totCarsKilos + totCar
endFor
average = totCarsKilos / (7 * 5)
print “Average Kilometers driven by a car in a day”, average
for c from 1 to 5
if ave[c] = hiAve then
● The question calculates and prints the overall average of all 35 cars, exactly as in Example
1.
● The average for each car must be calculated before the highest average can be determined.
This is calculated by accumulating the kilometre readings for each car in the inner for loop
over a week and dividing by 7. These averages are stored in a one-dimensional array,
ave[c]. The index of the array is equal to the number of cars (c).
● The average for each car is then compared with the highest average, which is initialised to
zero at the start of the program. If the average is greater than the highest average, it
becomes the new highest average. For example, suppose that the average for the first car,
Car 1, is 93.3km. Since 93.3 is greater than zero the highest average becomes 93.3. The
next time the loop executes, the average is compared to 93.3, and hiAve is replaced if the
next average is greater than 93.3.
The final for loop at the end of the program runs through all five cars again and compares the
averages of each of these cars with the highest average, which was determined earlier in the
program. When a car’s average equals the highest average, this average is printed together with the
car’s number. Any subsequent cars also equal to the highest average are also printed, together with
their car numbers.
Functions
Functions (also called methods) are self-contained sections of code written by programmers in order
to perform a specific task. These functions are also known as user-defined functions. Although
functions are self-contained, they can interact with other functions in order to carry out their tasks.
In Python, functions are used to utilise the code in more than one place in a program; they are
sometimes also called methods or procedures. Python provides you with many inbuilt functions like
print(), but it also gives you the freedom to create your own functions.
A function in Python is defined by the "def " statement followed by the function name and
parentheses ( () ).
The terms "parameter" and "argument" can be used for the same thing; the argument is a value that
is passed to the function when it iscalled. In other words, on the calling side it is an argument and on
the function side it is a parameter. In Python, arguments are declared in the function definition. While
calling the function, you can pass the values for that args. The return command in Python specifies
what value to give back to the caller of the function.
Keyword arguments
Keyword arguments in Python are used to pass additional information to a function. They are named
arguments, and they are passed after the positional arguments. For example,
my_function(arg1, arg2, keyword_arg=value).
Default arguments
Default arguments are arguments that are assigned a value by the function definition, and that
value is used if the argument is not passed in when the function is called. For example, the
following function has a default argument for the num_items argument:
The return statement in Python is used to send a value back to the caller of the function. The
value can be any type of object, including numbers, strings, lists, and dictionaries.
The return statement is typically used at the end of a function, but it can be used anywhere
within the function. If the return statement is used without a value, the function will return None.
print(add_numbers(1, 2))
This code will print 3 because the add_numbers function returns the sum of its two arguments.
Example 1:
Write the code for a program that requests the user to input three numbers. A function then
calculates and prints the product of the numbers. A second function is then called from the main
program and calculates the average of the numbers. The average is returned to the main program
and printed.
program Numbers # Main program
begin
print "Enter 3 numbers"
input num1, num2, num3
determineProduct(num1,num2,num3) #Call to determineProduct function
result = determineAve(num1, num2, num3) #Call to determineAve
function
print "The average of the numbers is: ", result
end
function determineAge(name)
begin
print "Hello", name
print "Please enter your age"
input age
msg = checkAge(age) # calls checkAge before returning to program.
return msg # returns to program Qualify
end
File Handling
What is a file?
A file is a collection of data that is stored on a storage device such as a hard disk, CD-ROM, DVD or
other storage medium. Files can be used for input, output or both. When a program reads from a file,
the relevant data from the file is input into the program and manipulated by the program. Data from
the program can also be written to a file for storage.
What is a record?
Records are stored in files, which can be input into a program. A record can contain more than one
piece of data; for example, an employee record can consist of the employee number, name and
salary. The employee number, name and salary are known as data fields, or simply, fields. Each
employee record will consist of these three fields.
If information was entered for ten different employees and stored in a file, the file would then contain
ten records, each record consisting of three fields.
Opening a file
Text and binary can only be used in conjunction with another mode.
The key function for working with files in Python is the open() function.
The open() function takes two parameters: filename and mode.
In addition, you can specify if the file should be handled in binary or text mode:
● "t" – Text – Default value. Text mode
● "b" – Binary – Binary mode (e.g. images)
Reading a file
Writing to a file
To write to an existing file, you must add a parameter to the open() function:
● "a" – Append – will append to the end of the file; it will create the file if it does not exist
(working in an online environment, we will not be using this parameter due to file
permissions)
● "w" – Write – will overwrite any existing content; it will create the file if it does not exist
● "x" – Create – will create a file; it will return an error if the file exists
Example 1
Records are read from a file called "salary.txt". Each record contains the
following fields:
● number
● name
● gender
● gross pay
If a male employee earns over R5 000 a month, the record must be written to
the highTax.txt file, and the number of records written to this file must be
counted.
After processing and printing the records contained in salary.txt, all records in
the highTax.txt file must be printed.
Pseudocode Solution
#record
rec = enum, ename, gender, gpay
#endRecord
begin
totRecords = 0
print rec
read rec from salary.fle
endWhile
print totRecords
close employee.fle
close highTax.fle
open highTax.fle for input
close highTax.fle
end
Calculate the gross pay for each employee and write gross pay and the
associated employee number to a new file called "grossPay.txt". Accumulate
the gross pay in the grossPay.txt file and print this total.
● Within the firstloop, the gross pay for each employee is calculated. The
hours and rate fields are stored in a variable. In the next line, the value
of grossPay is calculated and assigned to the gPay variable. The record
is then written to the file grossPay.txt.
● The finalloop accumulates the gross pay for all employees from the
pay.txt file, and prints this total at the end of processing. The grossPay
file is then closed.
Example 3
Records containing employee details are read from the file employee.txt. Each
record in this file contains the following fields: employee number, employee
name, hourly rate of pay and the number of hours worked.
Calculate the gross pay for each employee and write this and the employee’s
number and name to a new file called "gross.txt".
When all the records in the employee.txt file have been processed, print all
the records in the gross.txt file.
● This example is similar to the previous one, but the gross.txt file now
includes extra fields.
● In the firstloop, the employee records are read into the program. The
gross pay for each employee is then calculated, as before, and together
with the employee number and name, is stored in each field of the
gpRec record.
● Print all records in the gross.txt file.
Example 4
Read in records from a file called "student.txt". Each record contains the
following fields:
● student number
● student name
● fees paid (y/n)
If the student’s fees have been paid, the record must be written to a file called
"paid.txt" and the total number of records written to this file must be counted
and printed. If the fees have not been paid, the record must be written to a file
called "arrears.txt". The principal wants a printout of all the students whose
accounts are in arrears.
● In the loop, if the student has paid his or her fees, the record is written
to the paid.txt file and the number of records written to this file is
incremented. If the student has not paid, the record is written to the
arrears.txt file.
Merge Sort
Merge sort is a divide-and-conquer algorithm based on the idea of breaking down a list into several
sublists until each sublist consists of a single element, and merging those sublists in a manner that
results in a sorted list.
Merge sort is implemented with the following steps.
1. If there is only one element in the list, it is already sorted, return.
2. Divide the list recursively into two halves until it can no longer be divided.
3. Merge the smaller lists into a new list in the sorted order.
Search Algorithms
Linear Search
1. Start from the leftmost element of arr[] and one by one compare x with each element of arr[].
2. If x matches with an element, return the index.
3. If x doesn’t match with any of the elements, return −1.
Binary Search
Search a sorted array by repeatedly dividing the search interval in half. Begin with an interval
covering the whole array. If the value of the search key is less than the item in the middle of the
interval, narrow the interval to the lower half. Otherwise narrow it to the upper half. Repeatedly check
until the value is found or the interval is empty.
1. Compare x with the middle element.
2. If x matches with the middle element, we return the middle index.
3. If x is greater than the middle element, then x can only lie in the right half of the subarray,
after the middle element. So we recur for the right half.
4. Otherwise if x is smaller, recur for the left half.
The major difference between linear search and binary search is that binary search takes less time
to search for an element from the sorted list of elements. So it is inferred that the efficiency of the
binary search method is greater than the linear search.
Bubble sort example
This code works by repeatedly comparing adjacent elements in the array and swapping
them if they are in the wrong order. The outer loop iterates through the array from the
beginning to the end, and the inner loop compares each pair of adjacent elements. If the
current element is greater than the next element, they are swapped. This process
continues until the end of the array is reached, and the array is sorted.
[1, 2, 3, 5, 6, 7, 8, 9, 10]
● The bubble_sort() function takes an array as input and returns the sorted
array.
● The for loop in the bubble_sort() function iterates through the array from the
beginning to the end.
● The inner loop in the bubble_sort() function compares each pair of adjacent
elements in the array.
● If the current element is greater than the next element, they are swapped.
● The return statement in the bubble_sort() function returns the sorted array.
This code works by starting at the beginning of the array and comparing each element
to the target value. If the element is equal to the target value, the index of the element is
returned. If the element is not equal to the target value, the next element is compared.
This process continues until the end of the array is reached. If the target value is not
found in the array, -1 is returned.
As you can see, the index of the element 5 in the array is returned.
● The linear_search() function takes an array and a target value as input and
returns the index of the target value in the array if it is found. If the target value is
not found, -1 is returned.
● The for loop in the linear_search() function iterates through the array from
the beginning to the end.
● The if statement in the linear_search() function compares the current
element in the array to the target value. If the elements are equal, the index of
the element is returned.
● The return statement in the linear_search() function returns -1 if the target
value is not found in the array.
I hope this helps! Let me know if you have any other questions.
As you can see, the index of the element 5 in the array is returned.
● The binary_search() function takes an array and a target value as input and
returns the index of the target value in the array if it is found. If the target value is
not found, -1 is returned.
● The while loop in the binary_search() function iterates until the target value
is found or the search space is empty.
● The mid variable stores the index of the middle element of the search space.
● The if statement in the binary_search() function compares the target value
to the middle element of the search space. If the elements are equal, the index of
the middle element is returned.
● The elif and else statements in the binary_search() function update the
search space based on whether the target value is less than or greater than the
middle element.
● The return statement in the binary_search() function returns -1 if the target
value is not found in the array.