Program Design and Python Basics
Program Design and Python Basics
Print book
1.1. Notes
Site: Eduvos LMS
Course: Program Design
Book: 1.1. Notes
Printed by: Kriveshan Naidoo
Date: Wednesday, 27 August 2025, 3:18 PM
Table of contents
1. Introduction
2. Why use Python?
3. Programming Languages
4. History of Python and Comparison to Other Languages
5. Installing Python on Windows 10
6. CodeRunner
1. Introduction
Play Video
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 [Link] are
used in commercial development and web development. Most of them use
commands based on the English language.
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. Figure 1 below shows a
program as displayed in CodeRunner.
To test your code, click the Check button to see if the code passes the
tests defined in the exercise/illustration.
Print book
1.2. Notes
Site: Eduvos LMS
Course: Program Design
Book: 1.2. Notes
Printed by: Kriveshan Naidoo
Date: Wednesday, 27 August 2025, 3:19 PM
Table of contents
1. Introduction
2. Algorithm
3. Variable
4. Data Type
5. Constant
6. Conditional
7. Array
8. Loop
9. Function
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
Play Video
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.
Query successful
Programming languages can process different types of data. Data types have different
functions in a program. One of the most important factors to take into consideration is that
the performance of a computer can be severely affected by choosing the wrong data type.
For example, a program might only need to use numbers between one and 20; it would
therefore not make sense to use string variables to store these numbers in, as one will need to
convert these strings back to numbers in order to perform calculations on them. This would
create extra work for the computer, which means that the performance could degrade in
larger programs. Therefore, one should rather define the variables as integers.
We will be working with the following built-in Python data types in this module:
Descriptio Data
Type
n Types
Text str
Sequenc
list
e
Export to Sheets
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.
Query successful
In Python, variables are defined in a standard way by using the assignment character (=).
This changes the value of the variable. Naming conventions specify the way in which
variables should be named. This standard is used to make code more readable and thus easier
to understand.
The rules include the start and continuation characters. Variable names may contain any
upper or lower case letters (a–Z, A–Z), a number or the underscore character. They may not
begin with a number or contain spaces. Continuation characters are any characters except
whitespace characters, like tab and space.
c
ref_number
admin
aVeryLongName
True
$name
12Graph
In Python, the data type is set when you assign a value to a variable:
Query successful
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:
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
“"“
The following code illustrates the syntax for obtaining input in Python using the predefined
function.
Processing
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.
1.5 Example
Example:
A program is required to calculate the annual cost of running a motor car.
Costs include monthly installments, the annual fuel cost and insurance.
The annual insurance rate is 3% of the car's value.
Required input values are:
Programs must often perform tasks that include calculations or making decisions based on the
value of one or more variables. A program could also be used to compare values and perform
a certain action based on the outcome. For these actions, operators are used. Operators are
used to perform operations on variables and values. Operators can manipulate individual
items and return a result. The data items are referred to as operands or arguments.
We will be working with the following Python operators in this module:
Arithmetic operators
Logic operators
Comparison operators
Membership operators
Identity operators
Query successful
Operato Exampl
Name
r e
+ Add x+y
- Subtract x-y
* Multiply x*y
/ Divide x/y
** Exponential x ** y
Export to Sheets
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.
Query successful
Logical operators were introduced in the Logic section of the Processing and Logic Concepts
course. For the purposes of this course, we will be using the three most common logical
operators: AND, OR, and NOT. The use of logical operators results in only one of two
values: TRUE or FALSE.
and Returns True if both statements are true x < 5 and x < 10
Reverses the result; returns False if the result not(x < 5 and x <
not
is true 10)
Export to Sheets
Example: Here is an example where we get true or false based on the value of a and b.
Query successful
These operators compare the values on either side of the operand and determine the
relationship between them. They are also referred to as relational operators. Various
comparison operators are ==, !=, >, <. >=, and <=.
Operato Exampl
Description
r e
== Equal x == y
!= Not equal x != y
Greater than or
>= x >= y
equal to
Export to Sheets
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.
Query successful
2.1.4 Membership Operators
Membership operators are used to test if a sequence is present in an object variable or list.
There are two membership operators that are used in Python (in, not in). It gives the result
based on the variable present in a specified sequence or string.
Operato
Description Example
r
Export to Sheets
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.
Python
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.
In sequential programs, program statements are executed in the order in which they occur,
line after line, from top to bottom. Most programming languages use this method of
programming and the sequence control structure is built into the program.
Query successful
Example
The following example is a sequential program that is required to calculate a shop's total
amount of money in a specific register. All the different notes that are entered should be
added to calculate how much money is in the register. The coins are added together manually
and then added to the total.
Pseudocode:
begin
input note10, note20, note50, note100, note200, coins
tot10 = note10*10
tot20 = note20*20
tot50 = note50*50
tot100 = note100*100
tot200 = note200*200
Note:
Indentation refers to the spaces at the beginning of a code line. 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. If the indentation is not done
correctly, you will get a syntax error in your code.
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
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.
Query successful
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.
Query successful
In sequential programs, program statements are executed in the order in which they occur,
line after line, from top to bottom. Most programming languages use this method of
programming and the sequence control structure is built into the program.
For example:
Inpu
Result
t
Input: number:
8
8<br>20<br>33
20
33
Export to Sheets
2.3.2 Selection Structure
if statement
if-else statement
if-elif statement
Query successful
[Link] If Statement
An if statement is used for decision making in Python. It will run the body of code only
when an if statement is true. When you want to justify one condition while the other
condition is not true, then you use the if statement.
Let us look at the pseudocode design example. The following if statement checks whether a
variable called “amount” is greater than 1000. If it is, a variable called “rate” is adjusted to
the value of 0.2. The program then calculates the interest with the statement: interest =
amount * rate. If the amount is less than or equal to 1000, the rate variable remains
unchanged, and the interest is calculated with the original value for rate.
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.
[Link] If....else Statement
An if…else statement allows you to specify action(s) to perform when a
condition is true, and different action(s) to perform when a condition is
false. The following example expands on the example above and
illustrates a different action to be performed 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.
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.
while statement
for statement
Play Video
Video 3 - The For Loop
for
Executes a series of statements a fixed number of times.
Play Video
while
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.
input number
while number < 1 or number > 10 #check for an incorrect range
print "You must enter a number from 1 to 10" #prompt user for correc
input number # re-enter the 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.
Print book
Printed
Kriveshan Naidoo
by:
Table of contents
1. Learning outcome
2. Python Syntax
3. Problem Statement
4. Program Design
5. Problem-Solving
6. Stage 1
7. Stage 2
o 7.1. Stage 2.5
8. Stage 3
o 8.1. Let's Code
o 8.2. Code Break down
1. Learning outcome
Prescribed
Reading
2. Python Syntax
Just like any other programming language, Python contains its own syntax
rules.
Indentation Rule
3. Problem Statement
Consider the problem statement below:
Develop a program to assess salary disparities by calculating the number
of men earning above R25,000 and women earning below R20,000. The
program should process employee data until an employee number of 0 is
entered.
Employee number
Gender
Salary
For the purposes of this guide, the above problem statement will work as
an example of how students can make use of program design within the
development life cycle.
4. Program Design
What is Program Design?
Program design is not Python programming. The Python language works
as a vehicle to teach Program Design. Because Python is easy to read it
provides students an opportunity to think about coding in terms of written
language.
While there are multiple possible approaches, this guide distils the
process into two fundamental questions:
6. Stage 1
Identifying Objectives and Available Data
The primary goal of this step is to systematically address the problem-
solving questions. Regardless of the complexity or scale of the problem, it
can be broken down into manageable components.
Employee Number
Salary
Gender
Processing Condition: Ends when '0' is entered.
Threshold 1: Salary greater than R25,000.
Threshold 2: Salary less than R20,000.
7. Stage 2
Applying the IPO Model
Input: This refers to the data that the program receives from the user or
another source. Inputs can be numbers, text, files, or sensor readings,
depending on the program's purpose.
Process: This is the computational logic that transforms the input data
into meaningful results. It involves applying algorithms, calculations,
conditions, loops, and other logical structures.
Output: This is the result of the program after processing the input data.
The output should be clear, concise, and aligned with the program’s
objectives.
Put simply the IPO model is the Life cycle of any program. Understanding
how each of these stages works will help you add structure to the actions
you performed in Step 1.
NB! For the sake of understanding and teaching we will rearrange the
model to IOP.
Input
Because we have already answered Question 2 in step 1 our input
variables are already clear. However during this stage we also want to
assign variables to our input data.
Employee number: empNum
Employee genders: genders
Salaries: sal
Earnings threshold: 20K or 25K (NB) because we are given the amount for
the earning threshold we do not need to create two variables to store
these values.
Once our input variables are stated clearly we can now focus on the
output.
Output
Considering that output is the information displayed we can make use of
printing to display our input data as we code and see results as we go
along. This will minimize errors within our code. It is important to note
that once your program is complete and you have tested that it runs,
DISPLAY ONLY THE DATA REQUESTED BY THE USER.
Process
At this stage it is important to remind yourself of the problem and the
information you gained from the previous actions. To identify the different
processes we can consider our each process as tasks that need to be
completed:
At this stage we have out Inputs, our Processes and our Outputs. From
here we can jump to step 3 and develop our alogorithm. However, we will
add an additional step. Call it step 2.5.
7.1. Stage 2.5
Pseudocode
Step 2.5 serves as an intermediary step that involves the use of pseudocode to
outline the logical flow of the program. While this guide does not cover
pseudocode in detail, the following section illustrates its importance by
converting the previous steps into structured pseudocode.
In the first two processes we want to find out which employees are male
and which are female. Once we know that we can the assign the threshold
amount (25K or 20K) to that gender as it changes based off of that.
Count how many male employees meet the threshold and Count
how many female employees meet the threshold
The above line of code will tell the computer to check if the employees
salary is greater than or less than the threshold, depending on that result
add 1 to the gender.
Up until this point our breakdown has made sense, the processes
identified match the input and that combination will lead to the requested
result.
Since we know that adding a string and an integer wont give us the
expected result we can revise our inputs.
We don’t need to make changes (for this problem) to the process and the
output as those were already identified.
We can now interpret our code as: if salary is greater than the threshold
then add 1 to maleEmp or else add 1 to femaleEmp. In order to achieve
this count we need to initialize our target values.
This process addresses how the system should use the data provided.
Because we are told that all the above processes need to happen for all
employees until an employee number of zero is added. We can summarise
it as
While emp != 0:
8. Stage 3
Algorithm Development
Now the fun part. Open up your Python compiler.
8.1. Let's Code
8.2. Code Break down
Step 1: Initialize Variables
Define and initialize necessary variables, including counters for male and
female employees meeting the threshold conditions.
Print the initialized variables to verify that they have been set correctly
before processing input data.
Capture initial user input, such as employee number, gender, and salary.
Prompt for input again at the end of each iteration to ensure continuous
processing until termination.
Ensure all necessary input data (e.g., salary and gender) are correctly
captured within the loop.
Analyze whether any expected data points are missing and apply
appropriate handling mechanisms to ensure data completeness.
Step 8: Compute Counts
Print the results to confirm that all computations are working as expected.
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
Pseudocode:
begin
answer = "yes"
A while loop is used to allow the user to enter more than just one
employee record.
The while condition allows the user to enter many employee
records for processing, and the number of records does not need to
be known beforehand.
Example 3
An investor deposits money into a savings account that compounds
interest monthly and needs a program that will determine the status of
the account at the end of each month for any given interest rate.
The program should stop listing information about the account status
when the account balance is greater than the initial target balance.
Pseudocode:
begin
month = 0
diff = 0
numDeposits = 0
totDeposited = 0
monthIntEarned = 0
totInt = 0
input monthDepAmt, annIntRate, targetBal
balance = monthDepAmt
while balance < targetBal
month = month + 1
totDeposited = totDeposited + monthDepAmt
numDeposits = numDeposits + 1
monthIntEarned = balance * (annIntRate / 100 / 12)
totInt = totInt + monthIntEarned
balance = balance + monthIntEarned
diff = targetBal - balance
Pseudocode:
begin
totalTax = 0
taxAmt = 0
input numEmp #Enter the number of employees
for x from 1 to numEmp
input empNum, empName, grossPay
if grossPay < 5000 then
tax = 0.20
else
tax = 0.30
endIf
taxAmt = grossPay * tax
nettPay = grossPay – taxAmt #Calculate each employee’s nett pay
totalTax = totalTax + taxAmt #Accumulate the total tax for all employees
print empNum, empName, grossPay, taxAmt, nettPay
endFor
print totalTax
end
The output will be the consumption (litres per 100 kilometres) of each
vehicle.
Pseudocode:
begin
for x from 1 to 10
totDistance = 0 #each vehicle starts new month
totFuel = 0 #with 0 km and 0 litres of petrol
input reg
input numfills
The organisers of a marathon have a list of entrants with their name, age
and sex. They want to know how many entrants are males and how many
are females. Each entrant’s details must be printed.
Processing continues until an entrant name of “ZZZ” is input.
Input the name, address and exam percentage of students.
Calculate the total percentage of marks of all the students and the class
average.
For each student, print the name, address and percentage.
When a student name of “ZZZ” is input, print the total percentage of
marks and the class average.
Each month, the investor receives a printout reflecting the account status
i.e. total balance and interest for that month earned on the total balance.
At the end of each year, the investor receives a printout of
the accumulated totals.
A final summary of the account balance, as well as the total interest
earned over the period, must be shown when the program stops.
Write a program to calculate how much a salesperson earns when his/her
commission and basic salary are combined. If a salesperson sells above
R3 000 he/she earns 10% commission, otherwise, he/she earns no
commission. The report prints each salesperson's number, gender,
department number (1 or 2), sales amount, basic salary and total salary.
The program must adhere to the following specifications:
At the end of the report, print how many women work in each department.
Processing continues until a salesperson number of 0 is entered.
A company sales manager requires a sales analysis of the two products on
offer at the end of the month.
The company employs five salespersons. The program takes input values
of each salesperson (name, number, gender and total units sold for the
month for each of the products.
Each month, the investor receives a printout reflecting the account status
i.e. total balance and interest for that month earned on the total balance.
At the end of each year, the investor receives a printout of
the accumulated totals.
A final summary of the account balance, as well as the total interest
earned over the period, must be shown when the program stops.
Topic 2
4.1 One-Dimensional Arrays Practice
1D Arrays
An array is a data structure that consists of related data items
(called elements) of the same data type (any data type – strings, integers,
etc.). An array may contain all character values or all number values, but
not a mixture of both.
Python Collections
Play Video
Array Methods
Python has a set of built-in methods that you can use on lists/arrays.
Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified value
Adds the elements of a list (or any iterable) to the end of the current
extend()
list
index() Returns the index of the first element with the specified value
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the first item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list
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.
For example:
Inp
Result
ut
60 60
85 85
70 70
93 93
Pupil average 77.0
Best term 4 Marks =
93
Worst term 1 Marks =
60
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.
Inserting Values in Two-Dimensional Arrays
We can insert new data elements in a specific position by using the
insert() method and specifying the index.
In the example below, a new data element is inserted at index position
three.
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:
begin
totCarsKilos = 0 # Total of all 35 input kilometre readings
for c from 1 to 5 # Load the array – first dimension, start with the firs
totCar = 0 # Total for kilometres driven by each car; reset to 0 for each
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
endFor
totCarsKilos = totCarsKilos + totCar # Accumulate overall total for all c
endFor
average = totCarsKilos / (7 * 5) # or average = totCarsKilos / 35
print “Average kilometres driven by a car in a day: ”, average
end
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.
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
print “Highest average”, hiAve # Prints all cars averages that equal hiAv
print “Car no:”, c
endIf
endFor
end
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.
For example:
Input Result
78
74
27
21
211
92
54
369
94
If the value of the element is less than the array index, the element
must be replaced with the index plus ten.
If the value of the element is equal to the index, the element must
be doubled.
If the value of the element is greater than the index, the element
must be replaced by the index squared.
Print the original number and the changed number.
The numbers must first be loaded into the array.
For example:
Input Result
0 0
3 3
4 4
6 6
5 5
4 4
2 2
3 3
[0, 3, 4, 6, 5, 4, 2, 3]
[0, 1, 4, 9, 16, 15, 16,
17]
5.1 Functions
4.1 User-Defined Functions
Play Video
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 main program, Numbers, calls both functions one after the other. The
first function receives copies of all three numbers input by the user into
the parameter variables (value1, value2 and value3).
For example:
Inp
Result
ut
5 Enter 3 numbers
8 5
9 8
9
The product of the numbers is: 360
The average of the numbers is:
7.333333333333333
Example 2:
A program prompts for the user’s name and calls a function, which prints
"Hello" followed by the name. The function then prompts for the user’s
age. The age is sent as an argument to a second function, which returns a
message to the first function depending on the age of the user. If the user
is older than 25, "You are too old" is returned to the calling function. If the
user is between 17 and 25, "You qualify" is returned. If the user is younger
than 17, "You are too young" is returned. The main program prints the
user’s name followed by the return value. For example, if the user's name
is Joe and he is 18, the following message will be printed: “Hello Joe, you
qualify”. The program then ends.
program Qualify
begin
print "Please enter your name"
input name
message = determineAge(name)
print name, message
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
The main program calls the determineAge function with the user’s name
as an argument.
The determineAge function calls the checkAge function with the user’s age
included as an argument.
Depending on the user’s age, an appropriate message is returned to the
calling function of checkAge, which is determineAge.
Although there is more than one return statement in this function,
the if…else statement ensures that only one return will execute,
depending on the age of the user.
The message is stored in the msg variable. This value is then returned to
the main program (Qualify) and stored in the message variable.
Finally, the name and message is printed by Qualify.
For example:
Inpu
Result
t
For example:
Inpu
Result
t
58 Day 1: 58
62 Day 2: 62
Day 1 in celcius: 14.4
Day 2 in celcius: 16.7
Day 1 is colder than
day 2
Write a program into which a number between 0 and 10 is entered by the
user. The user is prompted to re-enter a number if the number falls
outside of the required range. After a valid number has been entered, the
number is passed to a function; the number and a relevant message
about the number are printed by the function. If the number is less than 5,
this number is returned to the program which adds 10 to the number and
prints the result. If the number is greater than or equal to 5, 0 is returned
to the program, which prints this value.
For example:
Input Result
12 12
20 20
90 90
4 4
4 is less than
5
14
Write a program that asks the user to input his or her name and passes
this name to a function. The function prints a message saying “Good day”
and their name, and then asks the user to input his or her age in years. If
the user is 18 years of age or older, the function requests whether or not
the user has a driver’s licence. If the user answers “yes”, the message
“Drive with care” is printed by the function.
The user’s age is returned to the main program and if the user is younger
than 18, the program calculates and prints how many years until the user
can apply for his or her driving licence. (A person has to be 18 years of
age or older before being allowed to apply for a driver’s licence.) The
program then ends.
For example:
Input Result
Inpu
Result
t
10 Enter num:
15 10
12 Enter num:
2 15
90 25
1
6.1 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.
File handling is an umbrella term for creating a file, opening a file, saving a data file,
updating or modifying data files, deleting a file, copying a file and closing a file.
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.
"r" – Read – Default value. Opens a file for reading; returns an error if the
file does not exist
"a" – Append – Opens a file for appending; creates the file if it does not
exist
"w" – Write – Opens a file for writing; creates the file if it does not exist
"x" – Create – Creates the specified file; returns an error if the file exists
In addition, you can specify if the file should be handled in binary or text
mode:
"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
Print book
Table of contents
1. Reading from file
To read the fields into different variables the split() method is used. The
split() method in Python is used to divide a string into a list of substrings
based on a delimiter (separator). The separator is the character where the
string is split. If omitted, it defaults to any whitespace (space, tab,
newline). The split() method is commonly used when reading lines from a
file where multiple fields are separated by a known character like spaces,
commas, or tabs i.e. delimiters.
id = fields[0]
name = fields[1]
age = fields[2]
job = fields[3]
print(f"{name} - {job}")
To split by a tab replace the comma with a \t. for example : fields =
[Link]('\t')
When reading from a file , the fields are read as Strings by default.
Convert fields as needed (e.g., to int, float).
fields = [Link]().split()
name = fields[1]
job = fields[3]
From the example id and age fields were converted to int data type.
Reading Fixed-Width Fields
id = line[0:3].strip()
name = line[4:14].strip()
age = line[14:16].strip()
job = line[16:].strip()
Summary
Records are read from a file called "[Link]". 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 [Link] file, and the number of records written to this
file must be counted.
After processing and printing the records contained in [Link], all
records in the [Link] file must be printed.
Pseudocode Solution
#record
rec = enum, ename, gender, gpay
#endRecord
begin
totRecords = 0
print rec
read rec from [Link]
endWhile
print totRecords
close [Link]
close [Link]
close [Link]
end
"rec" is the name given to a record in the file and contains the fields
enum, ename, gender and gpay.
The total number of records written to the [Link] file is
initialised to zero.
The program reads records from [Link] and writes some of those
records to [Link].
An if statement is used to check for records where the gender is
male and the gross pay is over 5 000. These are written to the
[Link] file. The total number of records written to the
[Link] file is incremented.
Each employee record is printed by the program. The next record is
then read from the file.
After all the records from the employee file have been processed
and printed, the total number of records in the [Link] file is
printed. Both files are then closed.
The [Link] file is reopened and all records printed. Finally, the
[Link] file is closed.
Calculate the gross pay for each employee and write gross pay and
the associated employee number to a new file called "[Link]".
Accumulate the gross pay in the [Link] 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 [Link].
The finalloop accumulates the gross pay for all employees from the [Link]
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 [Link]. 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 "[Link]".
When all the records in the [Link] file have been processed, print all the
records in the [Link] file.
This example is similar to the previous one, but the [Link] 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 [Link] file.
Example 4
Read in records from a file called "[Link]". 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
"[Link]" 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 "[Link]". 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 [Link] file and the number of records written to this file is
incremented. If the student has not paid, the record is written to the
[Link] file.
6.3 File Handling Exercises
1. In an unsorted array of five elements, start with the first two elements and
sort them in ascending order. (Compare the element to check which one is
greater.)
2. Compare the second and third element to check which one is greater, and
sort them in ascending order.
3. Compare the third and fourth element to check which one is greater, and
sort them in ascending order.
4. Compare the fourth and fifth element to check which one is greater, and
sort them in ascending order.
5. Repeat steps 1 – 4 until no more swaps are required.
Query successful
Both have their pros and cons, but ultimately bubble sort quickly becomes less efficient when
it comes to sorting larger datasets (or "big data"), whereas merge sort becomes more efficient
as datasets grow.
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