0% found this document useful (0 votes)
52 views127 pages

Program Design and Python Basics

The document provides study notes for a Program Design course, focusing on the importance of program design, the use of Python as a programming language, and fundamental programming concepts such as algorithms, variables, data types, and functions. It emphasizes the advantages of Python's readability and simplicity, making it suitable for both beginners and advanced programmers. Additionally, it covers the installation of Python, the use of CodeRunner for testing code, and the significance of properly defining variable names and data types in programming.

Uploaded by

domicblair
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
52 views127 pages

Program Design and Python Basics

The document provides study notes for a Program Design course, focusing on the importance of program design, the use of Python as a programming language, and fundamental programming concepts such as algorithms, variables, data types, and functions. It emphasizes the advantages of Python's readability and simplicity, making it suitable for both beginners and advanced programmers. Additionally, it covers the installation of Python, the use of CodeRunner for testing code, and the significance of properly defining variable names and data types in programming.

Uploaded by

domicblair
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Program Design Study Notes

Skip to main content

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

Video 1- Computer Programs

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.

Although a program flowchart is a useful tool for describing what a


program must do, it has definite shortcomings:

 Program flowcharts are time-consuming to construct.


 Flowcharts can become clumsy and unmanageable when describing
larger or more complicated programs.
 Flowcharts are often difficult to modify because they are drawings.
 Flowcharts are more difficult to read and follow, especially for larger
programs.

We learnt that pseudocode offers a program design alternative to


flowcharts. It is not code-specific, easily readable and can be translated
into any high-level computer programming language, but it cannot be
tested programmatically. We will use the Python programming language
to test program logic in this module.
2. Why use Python?
Pseudocode is ideal for designing a program plan because it shows the
step-by-step logic in a form that is easy to read and translate into a
specific computer language. However, pseudocode cannot be tested
programmatically. With Python, we can test the program to ensure that
the program output meets the requirements.

You would use Python instead of pseudocode because it:

 Is a dynamic programming language that focuses on code


readability.
 Has simple syntax that is easy to learn, so both new and
experienced programmers can start programming quickly.
 Has syntax that is very clear, so it is easy to
understand the program's code. Python is often referred to as
"executable pseudo-code" due to its syntax (Hilley, D. 2014). Python
syntax mostly follows the conventions used by programmers to
outline their ideas without the formal verbosity of code in most
programming languages. In other words, the syntax of Python is
almost identical to the simplified "pseudo-code" used by many
programmers to prototype and describe their solution to other
programmers (Hilley, D. 2014). Thus, Python can be used to
prototype and test code which is to be implemented later in other
programming languages. Since you will study other programming
languages (e.g. Java/C#) later during your studies, Python will
provide the necessary foundation required when you start on the
other programming languages.

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.

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.

4. History of Python and Comparison to


Other Languages
Python is a popular programming language. It was created by Guido van
Rossum and released in 1991. Python works on different platforms
(Windows, Mac, Linux, Raspberry Pi, etc.) and uses simple syntax like the
English language (pseudocode). The most recent major version of Python
is Python 3. Python version 3.8.2 will be used in this module to test your
understanding of program design concepts ([Link], 2020).

Unlike C# and other languages, Python’s syntax is human-readable


and concise. As a beginner, this will allow you to pick up the basics
quickly, with less mental strain, and you can level up to advanced topics
quicker pace. With one glance at Python code, you can identify what the
code is doing. In contrast, most programming languages require more
syntax (written code) to accomplish similar tasks, and the syntax doesn’t
mirror the human 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.

5. Installing Python on Windows 10


Use the following tutorial to install Python on your Windows machine:
Play Video

Source: ProgrammingKnowlege2, 2020 [Online] Available at:


Play Video

[Accessed on 25 September 2020]

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.

Figure 1 – CodeRunner interface as seen on myLMS

To test your code, click the Check button to see if the code passes the
tests defined in the exercise/illustration.

Skip to main content

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

Video 2 - Python Variables

A variable is a container (placeholder), which represents a value in a


program. Variables can store different data types including numeric
values, single characters and text strings. The value of a variable can
change all throughout a program.

 A variable name should be short, simple, descriptive and meaningful


and the same name should be used throughout the program. The
variable names num, number, nums will all represent a different
variable name to the program.
 Some computer languages are case-sensitive and so the variable
name should be in the same case throughout the program. The
variable Num and num will therefore be treated as two different
variables.
 Do not use an underscore to join two words. In fact, do not use any
symbols in variable names, for example num<five,
greaterThan50%, etc. will all be incorrect as the program will
attempt to perform a calculation when it finds a symbol.
 Variable names should begin with a small letter. When joining two
words, the first letter of the second word should be capitalised. For
example, totStud could be used to represent the total number of
students.

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

1.3 Data Types


Python Data Types

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

Numeric int, float

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

Assigning Variable Data Types

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.

Here are a few examples of valid variable names:

 c
 ref_number
 admin
 aVeryLongName

Here are a few examples of invalid variable names:

 True
 $name
 12Graph

In Python, the data type is set when you assign a value to a variable:

Example Data Type


x = "Hello World" str
x = 20 int
x = 20.5 float
x = ["apple", "banana", "cherry"] list
x = range(6) range

 Query successful

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:

Example Data Type


x = str("Hello World") str
x = int(20) int
x = float(20.5) float
1.4 Designing a Program
 Query successful

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
“"“

Comments will be used to explain code in the code block.

Let's explore how we can get user input in Python.

The following code illustrates the syntax for obtaining input in Python using the predefined
function.
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.
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:

 Value of the motor car


 Monthly installment amount
 Annual fuel cost

The output is the annual cost of running the car.


Answer – Pseudocode:
begin
input carValue, monthlyInstallment, annualFuelCost
annCost = monthlyInstallment * 12
insurance = carValue * 0.03
totalCost = annCost + insurance + annualFuelCost
print "Total annual cost of running the car", totalCost
end
Answer – Python:

2.1 Operators in Python


 Query successful

2.1 Operators in Python

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

2.1.1 Arithmetic Operators

Arithmetic operators perform various arithmetic calculations like addition, subtraction,


multiplication, division, % modulus, exponent, etc.

Operato Exampl
Name
r e

+ Add x+y

- Subtract x-y

* Multiply x*y

/ Divide x/y

% Modulus<br>(Get the remainder of a division) x%y

** Exponential x ** y

Floor Division<br>(Result of division in which the digits after


// x // y
the decimal point are removed)

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

2.1.2 Logic Operators

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.

For logical operators, the following conditions are applied:


Operato
Description Example
r

and Returns True if both statements are true x < 5 and x < 10

or Returns True if one of the statements is true x < 5 or x < 4

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.

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)

 Query successful

2.1.3 Comparison Operators

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 x > y

< Less than x < y

Greater than or
>= x >= y
equal to

<= Less than or equal to x <= y

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.

x = 4 y = 5 print('x > y is', x > y)

 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

Returns True if a sequence with the specified value is present


in x in y
in the object

Returns True if a sequence with the specified value is not


not in x not in y
present in the object

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.

2.2.1 Sequential Programs

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

totMoney = tot10 + tot20 +tot50 +tot100 + tot200 + coins

print "Total cash in the register:", totMoney


end

Note:

 Use input() to retrieve values from user.


 Use int() to convert the string input to an integer so we can perform calculations.
 Determine the logical steps needed to solve the problem, by means of program
flowcharts and/or pseudocode before attempting to code the solution.
 The input is provided by the system (one input line at a time), as illustrated in the
table below and the previous example.
 The expected output is also illustrated in the table below and will be provided in the
same format in this module.
 Query successful

2.2.2 Selection Structure

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

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.
 Query successful

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.

 Query successful

2.3.1 Sequential Programs

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

Selection statements are also known as “decision making statements” or “branching


statements”. The selection statements are used to select a part of the program to be executed
based on a condition.

Python provides the following selection statements:

 if statement
 if-else statement
 if-elif statement

The next section will explain more on the selection structures.

 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.

if amount > 1000 then


rate = 0.2
endif
interest = amount * 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.

if amount > 1000 then


rate = 0.2
else
rate = 0.1
endIf
interest = amount * rate

The if statement is similar to the one shown in Section [Link]. 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.

[Link] if-elif Statement


The if…elif statement can be expanded to include many different values
or cases to test for the condition, by nesting one or more else
if statements after the initial if statement.

In Python, when we want to test multiple conditions, we


use the elif statement.
The following code snippet makes use of nested else if statements to
check the mark of a student and print a message depending on the value
of the mark:
if mark >= 80 then
print "Distinction"
else if mark >= 70 then
print "Well done"
else if mark >= 60 then
print "Passed"
else
print "Failed"
endIf

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

Play Video
Video 3 - The For Loop

 for
Executes a series of statements a fixed number of times.

Play Video

Video 4- The While Loop

 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
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.

Here is the implementation of the above in CodeRunner

Skip to main content

Print book

3.1 Program Design Problem-


Solving Guide
Site: Eduvos LMS
Course: Program Design

3.1 Program Design Problem-Solving


Book:
Guide

Printed
Kriveshan Naidoo
by:

Date: Wednesday, 27 August 2025, 4:08 PM

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

By the end of this lesson, you should be able to:

 Write program control statements.

Prescribed
Reading

2. Python Syntax
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 don't
indent your code.

White Spaces Rule

The number of spaces is up to you as a programmer, but there 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.

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.

Make use of the following input values:

 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.

Program Design is therefore the process of breaking down a presented


problem, finding a solution and designing an algorithm (using Python) that
solves that problem.
5. Problem-Solving
The Approach
Program design is the process of developing structured, programmable
solutions to real-world problems. But how does one approach this task
effectively?

While there are multiple possible approaches, this guide distils the
process into two fundamental questions:

1. What are the primary and secondary objectives of the program?


2. What data is available for analysis?

By structuring our approach around these questions, we can enhance our


understanding of the problem and improve the efficiency of our solutions.

These questions form the foundation of the Programme Design


Framework, which can be divided into three key stages:

 Stage 1: Identifying Objectives and Available Data


 Stage 2: Applying the IPO (Input-Process-Output) Model
 Stage 3: Algorithm Development

This structured methodology ensures a logical and systematic approach to


program design, fostering both clarity and efficiency in problem-solving.

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.

Question 1: What are the primary and secondary objectives of the


program?

 Primary Objective: Count the number of male employees earning above


R25,000 and the number of female employees earning below R20,000.
 Secondary Objective: None.

Having established the primary objective, we now turn to the second


question.

Question 2: What data is available for analysis?


Data refers to the relevant information that can be used to solve the
problem. In this case, the problem statement explicitly provides the
following variables:

 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.

Good programmers thoroughly analyse every aspect of a problem. Writing


the details down in a structured manner improves comprehension and
highlights what is available versus what is required.

To effectively answer Question 2, it is essential to identify all available


data from the problem statement—no matter how minor or seemingly
insignificant. Extraneous details can always be filtered out later if they
prove unnecessary.

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.

For our problem our output values will be:

 empNum = print for testing


 genders = print for testing
 sal = print for testing
 threshold = print for testing
 maleEmp = print for user
 FemaleEmp = print for user

In our output we distinguish the visualized data for development and


testing and the requested user data. The output information has two new
variables that were not included in in our input. This represents the
information we need to know and can now help us formulate the
processes that we can use to solve the problem. Hence IOP.

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:

 Figure out each employees gender


 Figure out each employees salaries
 Count how many male employees meet the threshold
 Count how many female employees meet the threshold
 Repeat until 0 is added as an employee number

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.

Figure out each employees gender and Figure out each


employees salaries

If gender == “male” then threshold else threshold

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.

Because we are comparing in this process we use the if else statementas


we are told in the problem that we are comparing either male or female.

Count how many male employees meet the threshold and Count
how many female employees meet the threshold

If sal > < threshold then gender = gender + 1

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.

This however highlights a Logical Error in our Design.

Up until this point our breakdown has made sense, the processes
identified match the input and that combination will lead to the requested
result.

But let us examine the above line of code again

The result of the comparison statement is gender + 1, but gender as a


variable already has a value assigned to it (“male” or “ female”) which is a
string.

Since we know that adding a string and an integer wont give us the
expected result we can revise our inputs.

 Employee number = int


 Salary = int/float
 Gender = str
 Processing ends when 0 is entered
 threshold: greater than 25k
 threshold: less than 20K
 maleEmp = int (0)
 femaleEmp = int (0)

We don’t need to make changes (for this problem) to the process and the
output as those were already identified.

Now we can rewrite the above code as

If sal > < threshold then female/maleEmp = female/maleEmp + 1

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.

Repeat until 0 is added as an employee number

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:

i.e repeat until employee number 0 is added.

Finally print your results.

NB structure the above as Pseudocode

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.

Step 2: Display Initialization Results

 Print the initialized variables to verify that they have been set correctly
before processing input data.

Step 3: Define Input Variables

 Capture initial user input, such as employee number, gender, and salary.

Step 4: Start the Loop

 Implement a loop to process employee data until the termination condition


(e.g., entering 0 for the employee number) is met.

Step 5: Re-Evaluate the Condition at the End of the Loop

 Prompt for input again at the end of each iteration to ensure continuous
processing until termination.

Step 6: Capture Remaining Input Variables

 Ensure all necessary input data (e.g., salary and gender) are correctly
captured within the loop.

Step 7: Process and Identify Missing Variables

 Analyze whether any expected data points are missing and apply
appropriate handling mechanisms to ensure data completeness.
Step 8: Compute Counts

 Apply logical conditions to determine if an employee meets the salary


threshold based on gender and update the corresponding counters.

Step 9: Display Output for Verification

 Print the results to confirm that all computations are working as expected.

3.2 Program Examples


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

Note the following points from Example 1:

 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.
Example 2
Write a program that will calculate the net pay for each employee in a
company. The following data is input: num, name, gross pay and
deductions. A pay slip must be printed for each employee. The program
prompts the user to enter another record.

Pseudocode:

begin
answer = "yes"

while answer = “yes”


input name, num, gPay, deductions
nPay = gPay – deductions
print name, num, gPay, deductions, nPay
print “Enter another (yes/no) ?”
input answer
endWhile
end

Note the following points from Example 2:

 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 must read variable amounts for the:

 Monthly deposit amount


 Annual interest rate
 Target balance

It should then display the following information each month:

 Number of deposits made


 The total amount deposited by the investor
 The interest earned for the month
 The total amount of interest earned since the beginning of the
investment
 The balance of his account at the end of the month, with interest
added
 The amount outstanding before the target balance is reached

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

print “END OF MONTH ACCOUNT SUMMARY”


print “Month: “, month
print “Total amount deposited: R”, totDeposited
print “Total number of deposits: “, numDeposits
print “Interest earned for this month: R”, monthIntEarned
print “Total amount of interest earned: R”, totInt
print “Balance of account: R”, balance
print “Total amount short of target: R”, diff
if balance < targetBal then
balance = balance + monthDepAmt
endIf
endWhile
end

Note the following points from Example 3:

 Counters for the month and number of deposits are initialised to


zero at the beginning of the program.
 Totals for the difference, deposit, total interest earned and monthly
interest earned are initialised to 0 at the beginning of the program.
 The account balance is assigned a value equal to the deposit at the
start of the process, as this is the total money initially available in
the account.
 The while loop compares the account balance to the desired target
balance. Keep in mind that each repetition of the while loop
represents one month of processing. The number of deposits made
varies monthly, so the month and numDeposits variables are
incremented for every repetition of the loop.
 The amount of interest earned is calculated with the formula:
monthIntEarned = balance * annIntRate / 100 / 12. annIntRate is a
number representing the annual interest rate percentage. To
convert this to a monthly interest rate it must be divided by 12. To
convert it to a fraction it must be divided by 100. This is a useful
formula to remember when calculating monthly interest.
 Totals for the interest, deposit and account balance are
accumulated.
 The variable diff stores the difference between the current balance
and the target balance.
 The details of the investor are printed each month.
 The final if statement checks if the balance is still short of the target
value. If it is, the deposit for the next month is input, the balance
updated and the process repeated.
Example 4
A small publishing company would like to do a monthly analysis of the tax
paid by its employees. Employees who earn below R5 000 a month pay
20% tax on their gross pay. Employees who earn R5 000 or more pay 30%
tax. For each employee, the employee number, name and gross pay must
be input. The total number of employees must also be input. For each
employee, the number, name, gross pay, tax and net pay is printed. At
the end of processing, the total tax paid by all employees is printed.

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

Note the following points from Example 4:

 The number of employees is input as a variable into the program.


This allows us to use a for loop to process the employee records,
instead of a while loop, by using the number of employees variable
(numEmp) as the end condition of the for loop.
 The if statement is used to assign the correct tax amount to the
employee, depending on his or her gross pay.
 The details of each employee are printed within the for loop.
 The total combined tax amount is accumulated for all employees
and printed after the for loop.
Example 5
A commercial company would like to do a monthly analysis of the petrol
consumption of the fleet of two vehicles used by their sales department.
The following information must be input:

 The registration number of each vehicle


 The number of times the vehicle was filled up with petrol during the
month
 For each fill-up, the distance driven since the last fill-up and the
amount of petrol required

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

for y from 1 to numfills


input distance #for current fill-up
input fuel #for current fill-up
print y, distance, fuel
totDistance = totDistance + distance
totFuel = totFuel + fuel
endFor

consumption = (totFuel / totDistance) * 100 #calculate monthly fuel consu


print consumption, totDistance, totFuel
endFor
end

Note the following points from Example 5:


 There are two vehicles in the fleet so the for loop runs from 1 to 2.
The outer for loop represents the processing of two vehicles for the
month.
 Each time the for loop repeats, it represents the next vehicle for the
month. This is why the total distance and total fuel consumed is
reset to 0 at the start of the for loop, and why the registration
number and number of fillings for the month are input here.
 The nested, inner for loop accumulates the total distance travelled
and the total fuel used by the vehicle in the month, from the
distance covered and fuel used between fuel stops during the
month. The number of fill-ups is input and used as the end condition
of the for loop.
 For each vehicle, the fuel consumption is calculated and printed,
and processing continues with the next vehicle.
3.3 Simple Program Exercises
A user enters ten numbers. Write a program that will print the largest of these
numbers once all of the numbers have been entered.
The cost prices and the selling prices of items are input into a program until a
cost price of 0 for an item is input. The profit made on each item is
calculated. Write a program that will calculate the total profit made on all the
items and print it at the end.

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.

Input an amount in rands and cents (e.g. R12.30 would be 12.3).


Determine and print out the maximum number of R10 notes, R1 coins, 50
cent coins and 1 cent coins of which the amount input could consist.

Processing continues until a value of 0 is entered.


Input a student’s name, number, test score and maximum test score until
a student number of 0 is entered. Each student must have a report
printed with his or her name, number, percent and a remark. The remark
is based on the following scores:
0 – 44 Fail
45 – 49 Supplementary
50 – 59 Third class
60 – 69 Second class
70 – 74 Upper second
75 – 100 First
Count how many students are processed and print this total at the end.
Use the round(percentage,2) function to round the percentage to two
decimal places
Write a program for the following:

 Input: time in seconds.


 Convert this time to hours, minutes and seconds and print the
result.

A secretary working in the subscription department for a magazine inputs


data using the keyboard. For each subscriber, a Code field is input. The
subscriber types are as follows:

 Code 1 = Individual subscriber


 Code 2 = Associate subscriber
 Code 3 = Corporate subscriber

Count the number of subscribers in each category. Processing stops when


a code of 0 is entered. The individual totals, as well as the total number of
subscribers, must be printed.
The voting for a company chairman is recorded by entering the numbers 1 to 5
at the keyboard, depending on which of the five candidates secured a vote. Enter
0 to indicate that all votes have been input. Write a program that will count the
number of votes for each of the five candidates. Once all the votes have been
entered, print the total for each candidate and the total of all the invalid votes.
Write a program that is required to convert the US customary units (feet
and inches) into metric units (centimetres). The required input values are
feet and inches; the output value should be in centimetres.
(1 foot = 30.48 centimetres; 1 inch = 2.54 centimetres)
3.4 Standard Program Exercises
An investor deposits a fixed amount of money into a savings account
every month.
To open the account, a sum of money has to be deposited as a starting
balance.
The bank compounds interest monthly.
Write a program that calculates the total balance and interest earned.
The input details are the name, account number, gender, age, initial
deposit and monthly deposit amount.
The interest earned must be accumulated and the program should stop
listing information about the account status when the total interest earned
is greater than the original deposit amount.

 If an investor is a man or under 30, the interest rate is 5% per year.


 If the investor is a woman and over 60, the interest rate is 10% per
year.
 For anyone else, the interest rate is 7% per year.

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:

 The first input must be the salesperson number. If a number of 0 is


entered, a summary report is printed.

 If a salesperson number of 0 is entered, the user must not be


prompted for other information.
 The gender of the salesperson can be either M or F.

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.

The salary of each salesperson is strictly commission-based. Each


salesperson earns a basic commission calculated as 12.5% of his/her total
sales.

 If a salesperson sells more than R1 000 of product two, he or she


receives an additional 10% commission on product two.
 If not, commission for sales of product two is reduced to 5% (instead
of receiving the basic 12.5% commission for sales of product two, a
penalty is paid).
 If a saleswoman sells more than R500 of product one, she receives a
bonus of R100.

 An added bonus of R750 is given to each salesperson whose total


commission is more than R6 000.
 Each employee receives a printout showing all the employee details,
net pay and any additions.

The unit prices for the two products are as follows:

 Product one: R250


 Product two: R175

At the end of processing, the manager wants to know:


 The total number of items sold.
 The total number of women and the total number of men that
received a bonus.
 The number of women employed by the company.
 The total salary paid out (i.e. total net pay).

Write a program that does all the above processes.

Processing continues until the name "ZZZ" is entered.


Round off your calculations to two decimal places when printing.

An investor deposits a fixed amount of money into a savings account


every month.
To open the account, a sum of money has to be deposited as a starting
balance.
The bank compounds interest monthly.
Write a program that calculates the total balance and interest earned.
The input details are the name, account number, gender, age, initial
deposit and monthly deposit amount.
The interest earned must be accumulated and the program should stop
listing information about the account status when the total interest earned
is greater than the original deposit amount.

 If an investor is a man or under 30, the interest rate is 5% per year.


 If the investor is a woman and over 60, the interest rate is 10% per
year.
 For anyone else, the interest rate is 7% per year.

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.

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.

Figure 2: One-Dimensional Array


Arrays can be used to ascertain the following types of values when
dealing with numbers:

 The highest value in a group


 The lowest value in a group
 The total of all values
 The average value
 The highest average value
 The lowest average value

Python Collections

Play Video

Video 5: Collection Data Types: Tuple


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.
Answer:(penalty regime: 10, 20, ... %)

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

4.2 One-Dimensional Arrays


Examples
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 following points are noted from the answer above:

 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

4.3 Two-Dimensional Arrays


Two-Dimensional Arrays
Play Video
Video 6 - 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.

Figure 3: Two-dimensional Array


Consider the example of recording temperatures four times a day, every
day. Sometimes the recording instrument may be faulty and we fail to
record data.

 Day 1 – 23, 27, 11, 12


 Day 2 6, 10, 14, 5
 Day 3 25, 10, 17, 18
 Day 4 8, 9, 15, 12

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.

Updating Values in Two-Dimensional Arrays


We can update the entire inner array or some specific data elements of
the inner array by reassigning the values using the array index.
Deleting the Values in a Two-Dimensional Array
We can delete the entire inner array or some specific data elements of the
inner array by reassigning the values using the del() method with the
array index. In case you need to remove specific data elements in one of
the inner arrays, use the update process described in Question 3.

Another Two-Dimensional Array Example


The following initialisation of an array has nine elements.
It has three rows and three columns that can be visualised as a table.
0 1 2
0 1 2 3
1 4 5 6
2 7 8 9
4.4 Two-Dimensional Arrays
Examples
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.

The array can be defined as follows: kilometres[c, w] = carKilos

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 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

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.
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.

The following additional variable names have been used:


 Highest average kilometres driven by a car: hiAve
 One-dimensional array containing the average week’s kilometeres
per car: ave[c]

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

Note the following points about Example 2:

 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

51 Average Kilometers driven by a car in a day


51 102.8
32 Highest average 173.6
256 Car no: 4
35
83
56
200
352
98
23
39
54
23
150
243
75
27
43
75
123
25
265
14
62
123
Input Result

78
74
27
21
211
92
54
369
94

4.5 Arrays Program Exercises


The final exam marks for ten students must be stored in an array. Find:

 The student with the highest mark.


 The student with the lowest mark.
 The total marks for all the students.
 The overall average.
The melting points of 20 metals must be loaded into an array.
Assume that no two melting points are the same.
Find:

 The metal with the highest melting point.


 The metal with the lowest melting point.
 The average melting point of the metals.
Every element in an array of eight numbers must be changed as follows:

 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

Video 7 - Python 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.

The following are some of the characteristics of functions:

 They perform a specific task using self-contained units of code.


 They promote code maintainability. Changes made to a function should
not affect the rest of the program.
 Their code is hidden from other parts of the program
 They control which code other parts of the program may access, and to
what extent they may access it.
 They interact with the program or other functions through function calls.
 They are reusable. A function can be used (called) many times in the same
program.

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 ( () ).

4.2 Parameter and Argument


Play Video

Video 8 - In depth look at Functions


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.

4.3 Recursive Functions


A function can call other functions. It is also possible for the function to
call itself. These are known as recursive functions.
An example of a recursive function is to find the factorial of an integer.
A factorial of a number is the product of all the integers from 1 to that
number.
For example, the factorial of 6 is 1*2*3*4*5*6 = 720.
5.2 Functions Examples
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 determineProduct(value1, value2, value3) #Code for determineProd


begin
product = value1 * value2 * value3
print "The product of the numbers is: ", product
end
function determineAve(value1, value2, value3) # Code for determineAve fun
begin
average = (value1 + value2 + value3) / 3
return average
end

The following points can be noted regarding Example 1:

 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).

 After the function determineProduct() determines and prints the product of


the numbers, program control is automatically returned to Numbers, and
continues to the next line, where the determineAverage function is called.
 This function receives the three numbers as input parameters, calculates
the average of the numbers and returns the average to the variable result
in the Numbers program without printing it.
 The Numbers program receives the average in the result variable and
prints it.

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

function checkAge (value)


begin
if value > 25 then # if statement ensures only one message will
return "You are too old" # be returned
else if value > 16 then
return "You qualify"
else
return "You are too young"
endIf
end

The following points can be noted regarding Example 2:

 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

Jare Please enter your name:


d Jared
27 Hello Jared
Please enter your age: 27
Jared You are too old
Write a program that prompts the user to input the maximum
temperatures recorded for a city, over the last two days, in degrees
Fahrenheit (°F). A function converts the temperatures to degrees Celsius
(°C) and returns these values to the main program, which prints the
temperatures in °C. Another function is then called, which determines and
prints a message stating which of the two days was the coldest, or if the
temperature was the same.
The formula to convert °F to °C is:
C = 5/9 * (F-32)

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

Jare Name: Jared


d Good day Jared
19 Age in years: 19
y Do you have a driver’s
license? y
Drive with care
Write a program into which the user enters two numbers, both of which
must be greater than nine. A check function checks each number as it is
entered. If the number is not valid, the function prints a message
saying "Invalid. Enter num:" and prompts the user to re-enter a number.
The valid number is returned to the main function. Before the second
number can be entered and checked, the first number must be valid.
The two valid numbers are passed to a second function, which adds the
numbers together and prints the result. The program then ends.
For example:

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.

What is file handling?

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.

5.1 Opening a file


Play Video

Video 9 - File Handling in Python


The key function for working with files in Python is the open() function.
The open() function takes two parameters: filename and mode.

There are four different modes for opening a file:

 "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:

 "t" – Text – Default value. Text mode


 "b" – Binary – Binary mode (e.g. images)
5.2 Reading
a file
Play Video

Video 10 - Reading a Text File in Python


The open() function returns a file object, which has a read() method for
reading the content of the file.
Answer:(penalty regime: 10, 20, ... %)
5.3 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

Answer:(penalty regime: 10, 20, ... %)

Skip to main content

Print book

reading from a record with


multiple fields
Site: Eduvos LMS

Course: Program Design

reading from a record with multiple


Book:
fields
Printed
Kriveshan Naidoo
by:

Wednesday, 27 August 2025, 8:20


Date:
PM

Table of contents
 1. Reading from file

1. Reading from file


Reading Multiple Fields from a Text File in Python

Suppose you have a file named [Link] like this:

101 John 25 Engineer

102 Alice 30 Designer

103 Bob 28 Developer

Each line has 4 fields : ID, Name, Age, Job.

Basic Read and Split (Space-separated)

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.

Reading and Splitting Each Line (Space-separated)

Use this when fields are separated by spaces or tabs (whitespace).

with open('[Link]', 'r') as file:

for line in file:

fields = [Link]().split() # splits by whitespace

id = fields[0]

name = fields[1]
age = fields[2]

job = fields[3]

print(f"{name} is a {job} aged {age}.")

Reading with a Custom Delimiter (e.g., Comma or Tab)

with open('[Link]', 'r') as file:

for line in file:

fields = [Link]().split(',') # split by comma

id, name, age, job = fields

print(f"{name} - {job}")

To split by a tab replace the comma with a \t. for example : fields =
[Link]('\t')

Converting Fields to Specific Data Types

When reading from a file , the fields are read as Strings by default.
Convert fields as needed (e.g., to int, float).

with open('[Link]') as file:

for line in file:

fields = [Link]().split()

id = int(fields[0]) # convert to int

name = fields[1]

age = int(fields[2]) # convert to int

job = fields[3]

print(f"{id}: {name} ({age}) - {job}")

From the example id and age fields were converted to int data type.
Reading Fixed-Width Fields

Use slicing if each field has a fixed character width.

Example of text file:

Here is an example of code to read from the file using slicing:

with open('[Link]') as file:

for line in file:

id = line[0:3].strip()

name = line[4:14].strip()

age = line[14:16].strip()

job = line[16:].strip()

print(id, name, age, job)

Summary

File Format Method Used Example


Space-separated split() [Link]()
Comma- split(',') [Link](',')
separated
Tab-separated split('\t') [Link]('\t')
Fixed-width Slicing line[0:5].strip(
(line[x:y]) )

6.2 File Handling Examples


Example 1

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

open [Link] for input # this file is used to read data


into the program
open [Link] for output # this file is going to be written
to
read rec from [Link] # reads the whole record
while not EOF [Link] # the input file
if [Link] =”m” and [Link] > 5000 then
write rec to [Link]
totRecords = totRecords + 1
endIf

print rec
read rec from [Link]
endWhile

print totRecords
close [Link]
close [Link]

open [Link] for input

read rec from [Link]


while not EOF [Link]
print rec
read rec from [Link]
endWhile

close [Link]
end

Note the following points from the example:

 "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.

Here is the example implemented in Python using CodeRunner


Example 2
Records containing employee details are read from the file [Link].
Each record 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 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

7.1 Sorting Algorithms


Bubble Sort
Play Video
Video 11 - Bubble Sort Algorithm
Bubble sort is a sorting algorithm that works by repeatedly stepping
through lists that need to be sorted, comparing each pair of adjacent
items and swapping them if they are in the wrong order. This procedure is
repeated until no swaps are required, indicating that the list is sorted. The
steps for implementing bubble sort are as follows:

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.

Write a Python function to perform bubble sort.


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.

Write the Python function that implements merge sort.

 Query successful

So why choose one over the other?

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.

7.2 Search Algorithms


Linear Search
Play Video

Video 12 - Search Algorithms

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.
Write the Python function to implement a binary search.

You might also like