19
Main Topics
90+
Sub-Topics
70+
Code Examples
2026
Exam Ready
9.1
Uses of the Problem-Solving Process
ගැටලු විසඳීමේ ක්‍රියාවලියේ භාවිතයන්

Before writing a single line of code, a programmer must fully understand the problem and plan a solution. The problem-solving process has four main stages.

කේත පේළියක් ලිවීමට පෙර, ක්‍රමලේඛකයෙකු ගැටලුව සම්පූර්ණයෙන් තේරුම් ගෙන විසඳුමක් සැලසුම් කළ යුතුය. ගැටලු විසඳීමේ ක්‍රියාවලියේ ප්‍රධාන අදියර හතරක් ඇත.

StageWhat Happens
1. Understanding the ProblemRead the problem carefully. Identify what is given (inputs), what is required (outputs), and any conditions.
2. Definition of Problem & BoundariesClearly state the problem in your own words and set its limits — what the solution must and must not do.
3. Planning the SolutionDesign a step-by-step method (algorithm) using flowcharts or pseudocode.
4. Check Solutions & Select the BestCompare possible solutions and choose the most efficient and correct one.
Every problem has three parts: Input → Process → Output (the IPO model). Identifying these three first makes the rest of the solution much easier.

Example — Applying the process

Problem: Find the average of three numbers.

ගැටලුව: සංඛ්‍යා තුනක සාමාන්‍යය සොයන්න.

  • Input: three numbers (num1, num2, num3)
  • Process: add them, then divide the total by 3
  • Output: the average
  • Boundary: only numeric values are accepted
A common exam task is to break a stated problem into Input, Process and Output. Practise this for problems like "convert temperature", "calculate area", "find the largest number".
9.2
Top-Down Design & Stepwise Refinement
Top-Down Design සහ Stepwise Refinement

9.2.1 – Modularization

9.2.1 – Modularization (මොඩියුලකරණය)

Modularization means breaking a large problem into smaller, manageable parts called modules. Each module solves one part of the problem and can be developed and tested separately.

Modularization යනු විශාල ගැටලුවක් modules නම් කුඩා, කළමනාකරණය කළ හැකි කොටස්වලට බෙදීමයි. එක් එක් module එක ගැටලුවේ එක් කොටසක් විසඳන අතර වෙන වෙනම සංවර්ධනය කර පරීක්ෂා කළ හැක.

  • Makes complex programs easier to understand
  • Modules can be reused in other programs
  • Errors are easier to locate and fix
  • Different people can work on different modules

9.2.2 – Top-Down Design & Stepwise Refinement

9.2.2 – Top-Down Design සහ Stepwise Refinement

Top-down design starts with the whole problem at the top, then breaks it into smaller sub-problems, level by level. Stepwise refinement is the technique of refining each step into more detailed steps until it is simple enough to code.

Top-down design මුළු ගැටලුවෙන් ඉහළින් ආරම්භ වී, එය මට්ටමෙන් මට්ටම කුඩා උප ගැටලුවලට බෙදයි. Stepwise refinement යනු එක් එක් පියවර කේත කිරීමට තරම් සරල වන තෙක් වඩාත් සවිස්තර පියවරවලට පිරිපහදු කිරීමේ ක්‍රමයයි.

Top-Down Breakdown
Make a cup of tea                    (main problem)
 ├── Boil water                      (sub-problem)
 │    ├── Fill kettle with water
 │    └── Switch kettle on
 ├── Prepare cup
 │    ├── Add tea bag
 │    └── Add sugar
 └── Pour and serve

9.2.3 – Structure Charts

9.2.3 – Structure Charts (ව්‍යුහ සටහන්)

A structure chart is a diagram that shows how a program is divided into modules and how they relate to each other in a hierarchy (like an organisation chart). The main module is at the top; sub-modules branch downward.

Structure chart එකක් යනු වැඩසටහනක් modules වලට බෙදී ඇති ආකාරය සහ ඒවා ධුරාවලියක (organisation chart එකක් මෙන්) එකිනෙකට සම්බන්ධ වන ආකාරය පෙන්වන සටහනකි. ප්‍රධාන module එක ඉහළින්ම ඇත; උප modules පහළට අතු බෙදේ.

Structure charts show what the modules are and how they connect — they do not show the detailed logic. That detail belongs in a flowchart or pseudocode.
9.3
Algorithmic Approaches to Solve Problems
ගැටලු විසඳීමට ඇල්ගොරිතම ප්‍රවේශ

9.3.1 – Algorithms

9.3.1 – ඇල්ගොරිතම (Algorithms)

An algorithm is a finite, ordered set of clear steps that solves a problem. A good algorithm has these properties:

ඇල්ගොරිතමයක් යනු ගැටලුවක් විසඳන, සීමිත හා පිළිවෙළකට සකසන ලද පැහැදිලි පියවර සමූහයකි. හොඳ ඇල්ගොරිතමයක මෙම ගුණාංග ඇත:

PropertyMeaning
FinitenessMust end after a finite number of steps
DefinitenessEach step is clear and unambiguous
InputZero or more inputs are supplied
OutputProduces at least one result
EffectivenessEach step is basic enough to be carried out

Algorithms are commonly represented in two ways: flowcharts (diagrams) and pseudocode (structured English).

ඇල්ගොරිතම නිරූපණය කරන ප්‍රධාන ක්‍රම දෙකකි: flowcharts (ගැලීම් සටහන්) සහ pseudocode (ව්‍යූහගත ඉංග්‍රීසි).

9.3.1.1 – Flowcharts

9.3.1.1 – Flowcharts (ගැලීම් සටහන්)

A flowchart uses standard symbols connected by arrows to show the flow of steps in an algorithm.

Flowchart එකක් ඇල්ගොරිතමයක පියවර ගලා යන ආකාරය පෙන්වීමට, ඊතලවලින් සම්බන්ධ කළ සම්මත සංකේත භාවිතා කරයි.

SymbolNamePurpose
Oval / Rounded boxTerminatorStart or Stop of the algorithm
ParallelogramInput / OutputRead data or display results
RectangleProcessA calculation or action
DiamondDecisionA Yes/No (True/False) condition
ArrowFlow lineShows direction of flow

Example flowchart — largest of two numbers

Start Read A, B A > B ? Print A Print B Stop Yes No
Terminator — Start / Stop Parallelogram — Input / Output Diamond — Decision

9.3.1.2 – Pseudocode

9.3.1.2 – Pseudocode (ව්‍යාජ කේතය)

Pseudocode describes an algorithm using structured, plain-English keywords. It is not tied to any programming language, so it is easy to translate into Python later.

Pseudocode ව්‍යූහගත, සරල ඉංග්‍රීසි වචන භාවිතයෙන් ඇල්ගොරිතමයක් විස්තර කරයි. එය කිසිදු ක්‍රමලේඛන භාෂාවකට බැඳී නොමැති නිසා පසුව Python වෙත පරිවර්තනය කිරීම පහසුය.

Pseudocode
BEGIN
    READ A, B
    IF A > B THEN
        PRINT A
    ELSE
        PRINT B
    ENDIF
END

Common pseudocode keywords: BEGIN/END, READ/INPUT, PRINT/OUTPUT, IF...THEN...ELSE...ENDIF, WHILE...ENDWHILE, FOR...ENDFOR, REPEAT...UNTIL.

9.3.2 – Hand Traces / Dry Run / Trace Tables

9.3.2 – Hand Traces / Dry Run / Trace Tables (ලුහුබැඳීම් වගු)

A dry run (hand trace) means manually working through an algorithm step by step, recording the value of each variable in a trace table. This checks whether the logic is correct before running it on a computer.

Dry run (hand trace) යනු ඇල්ගොරිතමයක් පියවරෙන් පියවර අතින් ක්‍රියාත්මක කරමින්, එක් එක් විචල්‍යයේ අගය trace table එකක සටහන් කිරීමයි. මෙමඟින් පරිගණකයේ ධාවනයට පෙර තර්කය නිවැරදිදැයි පරීක්ෂා වේ.

Algorithm to trace
total = 0
FOR n = 1 TO 3
    total = total + n
END FOR
PRINT total

Trace table

StepntotalOutput
Start-0
n = 111
n = 223
n = 336
End366
Trace tables appear very frequently. You will be given a short algorithm and asked to complete a trace table showing each variable's value at every step, and the final output.
9.4
Comparison of Programming Paradigms
ක්‍රමලේඛන Paradigms සංසන්දනය

9.4.1 – Evolution of Programming Languages

9.4.1 – ක්‍රමලේඛන භාෂාවල පරිණාමය

Programming languages developed through generations, moving from machine-level to human-friendly:

ක්‍රමලේඛන භාෂා පරම්පරා (generations) ඔස්සේ, යන්ත්‍ර මට්ටමේ සිට මිනිසාට හිතකර මට්ටම දක්වා වර්ධනය විය:

GenerationTypeDescription
1GLMachine languageBinary (0s and 1s) — directly understood by the CPU
2GLAssembly languageUses mnemonics (ADD, MOV); needs an assembler
3GLHigh-level languagesEnglish-like: C, Java, Python; needs a compiler/interpreter
4GLVery high-levelCloser to human language: SQL, report generators
5GLAI / logicProblem-solving languages: Prolog, used in AI

9.4.2 – Programming Paradigms

9.4.2 – ක්‍රමලේඛන Paradigms

A paradigm is a style or approach to writing programs.

Paradigm එකක් යනු වැඩසටහන් ලිවීමේ විලාසයක් හෝ ප්‍රවේශයකි.

ParadigmIdeaExamples
ProceduralProgram is a sequence of procedures/functions that operate on dataC, Pascal, Python
Object-Oriented (OOP)Program is built from objects that combine data and methodsJava, C++, Python
FunctionalComputation as evaluation of mathematical functions; avoids changing stateHaskell, Lisp
LogicProgram is a set of facts and rules; you state what, not howProlog
Python is a multi-paradigm language — it supports procedural, object-oriented and functional styles.

9.4.3 – Characteristics of High-Level Languages

9.4.3 – High-Level භාෂාවල ලක්ෂණ

  • English-like keywords — easy to read and write
  • Machine independent (portable)
  • Must be translated (compiled or interpreted) before running
  • Easier to detect and correct errors
  • Supports structured programming
9.5
Program Translation & Translators
වැඩසටහන් පරිවර්තනය සහ Translators

9.5.1 – Need for Program Translators

9.5.1 – Program Translators අවශ්‍ය වීමට හේතුව

A CPU only understands machine language (binary). Programs written in high-level languages must therefore be translated into machine code before they can run. A translator does this job.

CPU එක තේරුම් ගන්නේ යන්ත්‍ර භාෂාව (binary) පමණි. එබැවින් high-level භාෂාවලින් ලියූ වැඩසටහන් ධාවනයට පෙර යන්ත්‍ර කේතයට පරිවර්තනය කළ යුතුය. එම කාර්යය කරන්නේ translator එකකි.

9.5.2 & 9.5.3 – Source Program vs Object Program

9.5.2 සහ 9.5.3 – Source Program සහ Object Program

TermMeaning
Source ProgramThe code written by the programmer in a high-level (or assembly) language
Object ProgramThe translated machine-code version produced by the translator

9.5.4 – Program Translators

9.5.4 – Program Translators (වැඩසටහන් පරිවර්තක)

InterpreterCompiler
TranslationLine by lineWhole program at once
Output fileNo separate object fileProduces an object/executable file
Speed of executionSlowerFaster (after compiling)
Error reportingStops at the first error foundReports all errors after scanning
ExamplePython, JavaScriptC, C++
9.5.4.3 – Assembler: a special translator that converts assembly language (2GL) into machine code.

9.5.5 – Linkers

9.5.5 – Linkers (සම්බන්ධක)

A linker combines the object program with other required object files and library modules to produce a single executable program.

Linker එකක් object program එක අවශ්‍ය අනෙකුත් object files සහ library modules සමඟ ඒකාබද්ධ කර තනි executable වැඩසටහනක් නිපදවයි.

You must be able to compare interpreter vs compiler and correctly define source program, object program, assembler and linker.
9.6
Integrated Development Environment (IDE)
සමෝධානිත සංවර්ධන පරිසරය (IDE)

An IDE is software that provides all the tools a programmer needs to write, test and debug programs in one place. For Python, common IDEs include IDLE, Thonny, PyCharm and VS Code.

IDE එකක් යනු වැඩසටහන් ලිවීමට, පරීක්ෂා කිරීමට සහ දෝෂ නිරාකරණයට අවශ්‍ය සියලු මෙවලම් එකම තැනකින් සපයන මෘදුකාංගයකි. Python සඳහා ප්‍රචලිත IDE අතර IDLE, Thonny, PyCharm සහ VS Code වේ.

9.6.1 – Basic Features of an IDE

9.6.1 – IDE එකක මූලික පහසුකම්

FeaturePurpose
Code EditorWhere you type your program, with syntax highlighting
Syntax HighlightingColours keywords, strings and comments to improve readability
Auto-completionSuggests code as you type
DebuggerHelps find and fix errors by running code step by step
Compiler / InterpreterRuns the program from inside the IDE
Output / Console windowDisplays program output and error messages
Beginners often start with IDLE (bundled with Python) or Thonny, which are simple and made for learning.
9.7
Using Python to Encode Algorithms
ඇල්ගොරිතම කේතනය සඳහා Python භාවිතය

9.7.1 – Structure of a Program

9.7.1 – වැඩසටහනක ව්‍යුහය

A simple Python program is made of statements executed from top to bottom. Unlike many languages, Python uses indentation (spaces) instead of braces { } to group statements.

සරල Python වැඩසටහනක් ඉහළ සිට පහළට ක්‍රියාත්මක වන ප්‍රකාශවලින් සමන්විතය. බොහෝ භාෂාවලට වෙනස්ව, Python ප්‍රකාශ කාණ්ඩ කිරීමට braces { } වෙනුවට indentation (හිස්තැන්) භාවිතා කරයි.

Python
# A simple Python program
name = input("Enter your name: ")
print("Hello,", name)
print("Welcome to Python")
Enter your name: Kamal Hello, Kamal Welcome to Python

9.7.2 – Comments in Programs

9.7.2 – වැඩසටහන්වල Comments

Comments explain code and are ignored by the interpreter.

Comments කේතය පැහැදිලි කරයි; interpreter ඒවා නොසලකා හරියි.

Python
# This is a single-line comment
print("Hello")   # comment after a statement

"""
This is a
multi-line comment (docstring)
"""

9.7.3 – Constants, Variables & Storing Data

9.7.3 – නියත, විචල්‍ය සහ දත්ත ගබඩා කිරීම

A variable is a named storage location whose value can change. Python creates a variable automatically the moment you assign a value to it (=).

විචල්‍යයක් යනු අගය වෙනස් විය හැකි, නමක් සහිත ගබඩා ස්ථානයකි. අගයක් ආදේශ කළ (=) සැණින් Python විචල්‍යය ස්වයංක්‍රීයව සාදයි.

9.7.3.1 – Declaring variables and storing data

Python
age = 17            # integer
price = 250.75      # float
name = "Nimal"      # string
passed = True       # boolean
print(age, price, name, passed)
17 250.75 Nimal True

9.7.3.2 – Assign the same value to multiple variables

Python
x = y = z = 0
print(x, y, z)
0 0 0

9.7.3.3 – Assign different values to several variables

Python
a, b, c = 10, 20, 30
print(a, b, c)
10 20 30

9.7.3.4 – Rules & good practice for naming variables

RuleValidInvalid
Must start with a letter or underscorename, _total2name
Can contain letters, digits, underscoresmarks1marks-1
No spacesfirst_namefirst name
Cannot be a keywordtotalif, for
Case-sensitiveAge and age are different variables
Use meaningful names (student_marks, not x) and lowercase words joined by underscores — this is the standard Python style.

9.7.4 – Constant Variables

9.7.4 – Constant (නියත) විචල්‍ය

Python has no true constants, but by convention a variable written in UPPERCASE is treated as a constant that should not be changed.

Python හි සැබෑ නියත නොමැත; නමුත් සම්මුතියක් ලෙස UPPERCASE අකුරින් ලියූ විචල්‍යයක් වෙනස් නොකළ යුතු නියතයක් ලෙස සලකයි.

Python
PI = 3.14159
MAX_MARKS = 100
print(PI, MAX_MARKS)

9.7.5 – Local & Global Variables

9.7.5 – Local සහ Global විචල්‍ය

TypeWhere it is definedWhere it can be used
GlobalOutside all functionsAnywhere in the program
LocalInside a functionOnly inside that function
Python
total = 100          # global variable

def show():
    msg = "Hello"    # local variable
    print(msg, total)

show()
print(total)         # works
# print(msg)         # ERROR: msg is local
Hello 100 100

9.7.6 – Primitive Data Types

9.7.6 – ප්‍රාථමික දත්ත වර්ග

TypeKeywordExampleMeaning
Integerint25, -7Whole numbers
Floatfloat3.14, -0.5Numbers with a decimal point
Stringstr"Hello"Text (in quotes)
BooleanboolTrue, FalseLogical values
Python
print(type(25))         # <class 'int'>
print(type(3.14))       # <class 'float'>
print(type("Hi"))       # <class 'str'>
print(type(True))       # <class 'bool'>
Type casting converts between types: int("5") → 5, float(3) → 3.0, str(10) → "10". This is needed because input() always returns a string.

9.7.7 – Categories of Operators

9.7.7 – කාරක (Operators) වර්ග

Arithmetic operators

OpMeaningExample (a=7, b=2)Result
+Additiona + b9
-Subtractiona - b5
*Multiplicationa * b14
/Division (float)a / b3.5
//Floor divisiona // b3
%Modulus (remainder)a % b1
**Exponent (power)a ** b49

Relational (comparison) operators

== equal, != not equal, > greater, < less, >= greater-or-equal, <= less-or-equal. All return True or False.

Logical operators

OpTrue when…Example
andBoth conditions are True(a>0) and (b>0)
orAt least one is True(a>0) or (b>0)
notReverses the resultnot(a>0)

Assignment operators

=, +=, -=, *=, /=, %=. Example: x += 5 is short for x = x + 5.

9.7.8 – Operator Precedence

9.7.8 – කාරක ප්‍රමුඛතාව (Operator Precedence)

Precedence decides the order operators are evaluated. Higher precedence runs first. Use brackets to control the order.

Precedence මඟින් කාරක ඇගයෙන පිළිවෙළ තීරණය වේ. ඉහළ precedence සහිත කාරක පළමුව ක්‍රියාත්මක වේ. පිළිවෙළ පාලනයට වරහන් භාවිතා කරන්න.

PriorityOperators
1 (highest)( ) parentheses
2** exponent
3* / // %
4+ -
5relational < > == !=
6 (lowest)not → and → or
Python
print(2 + 3 * 4)        # 14 (× before +)
print((2 + 3) * 4)      # 20 (brackets first)
print(2 ** 3 + 1)       # 9  (power first)
14 20 9
Remember BODMAS: Brackets, Order (powers), Division/Multiplication, Addition/Subtraction.

9.7.9 – Input & Output in Python

9.7.9 – Python හි ආදාන සහ ප්‍රතිදාන

print() displays output; input() reads a value from the keyboard as a string.

print() ප්‍රතිදානය පෙන්වයි; input() යතුරුපුවරුවෙන් අගයක් string එකක් ලෙස කියවයි.

Python
name = input("Name: ")            # string
age = int(input("Age: "))         # convert to int
marks = float(input("Marks: "))   # convert to float
print("Hi", name, "- next year you will be", age + 1)
Name: Sitha Age: 16 Marks: 78.5 Hi Sitha - next year you will be 17
Because input() always returns a string, you must use int() or float() before doing arithmetic. Forgetting this is a very common error.
9.8
Control Structures in Software Development
මෘදුකාංග සංවර්ධනයේ පාලන ව්‍යුහ

Control structures decide the order in which statements run. There are three basic types:

පාලන ව්‍යුහ මඟින් ප්‍රකාශ ක්‍රියාත්මක වන පිළිවෙළ තීරණය වේ. මූලික වර්ග තුනකි:

TypeMeaning
SequenceStatements run one after another, top to bottom
SelectionA choice is made using if conditions
Iteration (Loop)Statements repeat using while or for

9.8.1 – Selection: if statements

9.8.1 – වරණය: if ප්‍රකාශ

9.8.1.1 – Simple if

Python
marks = int(input("Marks: "))
if marks >= 50:
    print("Pass")
Marks: 65 Pass

9.8.1.2 – if...else

Python
marks = int(input("Marks: "))
if marks >= 50:
    print("Pass")
else:
    print("Fail")
Marks: 40 Fail

9.8.1.3 – if...elif...else (nested selection)

Python
marks = int(input("Marks: "))
if marks >= 75:
    print("Distinction")
elif marks >= 65:
    print("Credit")
elif marks >= 50:
    print("Pass")
else:
    print("Fail")
Marks: 68 Credit
Indentation matters! Every statement inside an if block must be indented (usually 4 spaces). Wrong indentation causes an IndentationError.

9.8.2 – Iteration (Looping)

9.8.2 – පුනර්කරණය (Looping)

9.8.2.1 – while loop

Repeats while a condition is True. Use it when you don't know in advance how many times to loop.

කොන්දේසිය True වන තාක් පුනරාවර්තනය වේ. loop වාර ගණන කලින් නොදන්නා විට භාවිතා කරන්න.

Python
count = 1
while count <= 5:
    print(count)
    count = count + 1     # update — very important!
1 2 3 4 5
Always change the loop variable inside a while loop. If the condition never becomes False, you create an infinite loop.

9.8.2.2 – for loop

Repeats a known number of times, usually over a range() or a collection.

දන්නා වාර ගණනක් පුනරාවර්තනය වේ; සාමාන්‍යයෙන් range() එකක් හෝ එකතුවක් (collection) හරහා.

Python
for i in range(1, 6):     # 1,2,3,4,5 (6 not included)
    print(i)

for fruit in ["apple", "mango", "banana"]:
    print(fruit)
1 2 3 4 5 apple mango banana
range() formProduces
range(5)0, 1, 2, 3, 4
range(1, 5)1, 2, 3, 4
range(1, 10, 2)1, 3, 5, 7, 9 (step 2)

9.8.3 – Loop Control: break & continue

9.8.3 – Loop පාලනය: break සහ continue

StatementEffect
breakExits the loop immediately
continueSkips the rest of this pass and goes to the next
Python
for i in range(1, 6):
    if i == 3:
        continue      # skip 3
    if i == 5:
        break         # stop at 5
    print(i)
1 2 4
Loops are heavily tested. Practise: printing number series, sum/average of N numbers, counting, multiplication tables, and finding largest/smallest with a loop.
9.9
Types of Sub-Programmes (Functions)
උප වැඩසටහන් (Functions) වර්ග

A function (sub-programme) is a named block of code that performs a task. It helps avoid repetition and makes programs modular.

Function (උප වැඩසටහන) එකක් යනු කාර්යයක් ඉටු කරන, නමක් සහිත කේත කාණ්ඩයකි. එය පුනරාවර්තනය වළක්වා වැඩසටහන modular කරයි.

9.9.1 – Built-in Functions

9.9.1 – Built-in Functions

Python provides many ready-made functions:

Python සූදානම් කළ functions රාශියක් සපයයි:

FunctionPurposeExample
print()Display outputprint("Hi")
input()Read inputinput("Name: ")
len()Lengthlen("abc") → 3
int()/float()/str()Type castingint("5") → 5
max()/min()Largest / smallestmax(3,7) → 7
sum()Total of a listsum([1,2,3]) → 6
range()Sequence of numbersrange(5)

9.9.2 – User-Defined Functions

9.9.2 – පරිශීලක අර්ථදත් (User-Defined) Functions

You create your own functions with the def keyword.

def මූලපදය භාවිතයෙන් ඔබේම functions සෑදිය හැක.

9.9.2.1 – Defining and calling a function

Python
def greet():
    print("Hello, welcome!")

greet()      # calling the function
greet()      # can be called many times
Hello, welcome! Hello, welcome!

9.9.2.2 – Passing values with parameters

Python
def greet(name):
    print("Hello", name)

greet("Kamal")
greet("Nimal")
Hello Kamal Hello Nimal

9.9.2.3 – Return values

A function can send back a result with return.

Function එකකට return මඟින් ප්‍රතිඵලයක් ආපසු යැවිය හැක.

Python
def add(a, b):
    return a + b

result = add(10, 5)
print("Sum =", result)
Sum = 15
Parameter = the variable in the function definition. Argument = the actual value passed when calling the function.

9.9.3 – Types of Errors in Python

9.9.3 – Python හි දෝෂ (Errors) වර්ග

Error TypeWhen it happensExample
9.9.3.1 Syntax errorThe code breaks Python grammar rules; found before runningprint("Hi" (missing bracket)
9.9.3.2 Runtime errorOccurs while the program runs; it crashes10 / 0 (division by zero)
9.9.3.3 Logical errorProgram runs but gives the wrong answerUsing + instead of * in a formula
Syntax and runtime errors show messages. Logical errors are the hardest to find because there is no error message — the output is simply wrong. Use a trace table to catch them.
9.10
Data Structures in Programming
ක්‍රමලේඛනයේ දත්ත ව්‍යුහ

A data structure stores and organises a collection of related data so it can be used efficiently.

දත්ත ව්‍යුහයක් අදාළ දත්ත එකතුවක් කාර්යක්ෂමව භාවිතා කළ හැකි ලෙස ගබඩා කර සංවිධානය කරයි.

9.10.1 – Types of Data Structures in Python

9.10.1 – Python හි දත්ත ව්‍යුහ වර්ග

StructureSymbolOrdered?Changeable?Duplicates?
String" "YesNo (immutable)Yes
List[ ]YesYesYes
Tuple( )YesNo (immutable)Yes
Dictionary{ key:value }Yes*YesNo (keys)
Set{ }NoYesNo
Mutable means the contents can be changed after creation (list, dict, set). Immutable means they cannot (string, tuple).
9.11
String Data Structure & Functionality
String දත්ත ව්‍යුහය සහ ක්‍රියාකාරිත්වය

A string is a sequence of characters written inside quotes.

String එකක් යනු උද්ධෘත (quotes) තුළ ලියූ අක්ෂර අනුක්‍රමයකි.

9.11.1 – Accessing a String by Index

9.11.1 – Index මඟින් String එකකට ප්‍රවේශය

Each character has an index. Positive indexes start at 0 from the left; negative indexes start at -1 from the right.

සෑම අක්ෂරයකටම index එකක් ඇත. ධන index වමේ සිට 0 ලෙසත්, ඍණ index දකුණේ සිට -1 ලෙසත් ආරම්භ වේ.

Python
word = "PYTHON"
#       0 1 2 3 4 5   (positive)
#      -6-5-4-3-2-1   (negative)
print(word[0])     # P
print(word[-1])    # N
print(word[1:4])   # YTH  (slicing)
P N YTH

9.11.2 – Using Inverted Commas (Quotes)

9.11.2 – උද්ධෘත (Quotes) භාවිතය

Strings can use single ' ' or double " " quotes. Use one type to include the other inside.

String සඳහා තනි ' ' හෝ ද්විත්ව " " උද්ධෘත භාවිතා කළ හැක. එක් වර්ගයක් ඇතුළත අනෙක යෙදීමට අනෙක් වර්ගය භාවිතා කරන්න.

Python
a = 'Hello'
b = "It's a book"      # double quotes allow the apostrophe
print(a, b)

9.11.3 – Functions Used with Strings

9.11.3 – Strings සමඟ භාවිතා වන Functions

#TaskFunctionExample → Result
1Number of characterslen()len("Python") → 6
2Capitalise first letter of each word.title()"good day".title() → Good Day
3All UPPERCASE.upper()"abc".upper() → ABC
4All lowercase.lower()"ABC".lower() → abc
5Join lines / words.join()"-".join(["a","b"]) → a-b
6Accept only numeric.isdigit()"25".isdigit() → True
7Check lowercase.islower()"abc".islower() → True
8Check uppercase.isupper()"ABC".isupper() → True
9Split a sentence.split()"a b c".split() → ['a','b','c']
Python — string methods
s = "sri lanka"
print(len(s))          # 9
print(s.title())       # Sri Lanka
print(s.upper())       # SRI LANKA
print(s.split())       # ['sri', 'lanka']
print("123".isdigit()) # True
9 Sri Lanka SRI LANKA ['sri', 'lanka'] True

9.11.3.10 – String Operators

OperatorMeaningExample → Result
+Concatenation (join)"Sri" + "Lanka" → SriLanka
*Repetition"ab" * 3 → ababab
inMembership"a" in "cat" → True
9.12
Understanding the List Data Type
List දත්ත වර්ගය හඳුනා ගැනීම

A list stores multiple ordered, changeable items inside square brackets [ ]. Items can be of any type.

List එකක් square brackets [ ] තුළ පිළිවෙළ සහිත, වෙනස් කළ හැකි අයිතම කිහිපයක් ගබඩා කරයි. අයිතම ඕනෑම වර්ගයක විය හැක.

Python
fruits = ["apple", "mango", "banana"]
marks = [65, 78, 90, 45]
mixed = ["Kamal", 17, True]
print(fruits)
['apple', 'mango', 'banana']

9.12.1 – Nested Lists

9.12.1 – Nested Lists

Python
students = [["Kamal", 85], ["Nimal", 72]]
print(students[0])        # ['Kamal', 85]
print(students[0][1])     # 85

9.12.3 – Accessing Elements (Indexing & Slicing)

9.12.3 – මූලද්‍රව්‍යවලට ප්‍රවේශය (Indexing සහ Slicing)

Python
nums = [10, 20, 30, 40, 50]
print(nums[0])       # 10  (positive index)
print(nums[-1])      # 50  (negative index)
print(nums[2:])      # [30, 40, 50]  (from index 2)
print(nums[:3])      # [10, 20, 30]  (first 3)
print(nums[1:4])     # [20, 30, 40]  (several)
print(nums[::2])     # [10, 30, 50]  (step 2)
print(nums[::-1])    # [50, 40, 30, 20, 10]  (reverse)
10 50 [30, 40, 50] [10, 20, 30] [20, 30, 40] [10, 30, 50] [50, 40, 30, 20, 10]

9.12.9 – Basic List Functions

9.12.9 – මූලික List Functions

FunctionPurposeExample (n=[3,1,2])
len(n)Number of items3
n.append(9)Add to end[3,1,2,9]
n.insert(0,9)Add at a position[9,3,1,2]
n.remove(1)Remove a value[3,2]
n.pop()Remove & return lastreturns 2
n.count(3)How many times value appears1
n.sort()Sort ascending[1,2,3]
n.clear()Empty the list[ ]
sum(n)Total6
max(n) / min(n)Largest / smallest3 / 1
Python — list operations
marks = [65, 78, 90, 45]
marks.append(88)          # add 88 at end
marks.sort()              # ascending order
print(marks)              # [45, 65, 78, 88, 90]
print("Total:", sum(marks))
print("Highest:", max(marks))
print("Count:", len(marks))

# combine two lists
a = [1, 2]
b = [3, 4]
print(a + b)              # [1, 2, 3, 4]
[45, 65, 78, 88, 90] Total: 366 Highest: 90 Count: 5 [1, 2, 3, 4]
Lists appear in almost every practical: reading N marks into a list, then finding the total, average, highest and lowest. Know append(), sort(), sum(), max(), min() and len() well.
9.13
Working with Dictionaries
Dictionaries සමඟ වැඩ කිරීම

A dictionary stores data as key : value pairs inside curly braces { }. Values are accessed by their key, not by index.

Dictionary එකක් curly braces { } තුළ key : value යුගල ලෙස දත්ත ගබඩා කරයි. අගයන්ට ප්‍රවේශය key එක මඟිනි, index එකින් නොවේ.

Python
student = {"name": "Kamal", "age": 17, "grade": "A"}
print(student["name"])     # Kamal  (9.13.1 access value)

student["age"] = 18        # 9.13.2 add / change value
student["city"] = "Colombo"

del student["grade"]       # 9.13.3 remove a value

print(student.keys())      # 9.13.4 all keys
print(student.values())    # 9.13.5 all values
Kamal dict_keys(['name', 'age', 'city']) dict_values(['Kamal', 18, 'Colombo'])
TaskCode
Access a valued["key"]
Add / updated["key"] = value
Removedel d["key"]
All keysd.keys()
All valuesd.values()
Dictionary keys must be unique. If you assign to an existing key, its value is replaced rather than added.
9.14
Working with Tuples
Tuples සමඟ වැඩ කිරීම

A tuple is an ordered collection like a list, but immutable — its items cannot be changed after creation. It uses round brackets ( ).

Tuple එකක් list එකක් වැනි පිළිවෙළ සහිත එකතුවකි; නමුත් immutable — සෑදූ පසු අයිතම වෙනස් කළ නොහැක. round brackets ( ) භාවිතා කරයි.

Python
nums = (10, 20, 30, 20)
print(len(nums))          # 4   len()
print(max(nums))          # 30  max()
print(min(nums))          # 10  min()
print(sum(nums))          # 80  sum()
print(nums.index(30))     # 2   position of 30

# convert a list into a tuple
mylist = [1, 2, 3]
t = tuple(mylist)
print(t)                  # (1, 2, 3)
4 30 10 80 2 (1, 2, 3)
You cannot do nums[0] = 99 on a tuple — it raises an error. Use a tuple when the data must stay fixed (e.g. days of the week).
9.15
Understanding the Set
Set (කුලකය) හඳුනා ගැනීම

A set is an unordered collection with no duplicate values, written in curly braces { }.

Set එකක් යනු අනුපිළිවෙළක් නැති, අනුපිටපත් නොමැති අගයන් සහිත එකතුවකි; curly braces { } තුළ ලියයි.

Python
colors = {"red", "green", "blue"}

colors.add("yellow")             # 9.15.1 add one item
colors.update(["black", "red"])  # 9.15.2 add many (red ignored)
print(len(colors))               # 9.15.3 number of items
# colors.clear()                 # 9.15.4 empty the set

print("red" in colors)           # True
5 True
Because a set removes duplicates automatically, it is often used to find the unique values in a list: set([1,1,2,3]) → {1, 2, 3}.
9.16
Python Membership Operators
Python Membership කාරක

Membership operators check whether a value exists inside a sequence (string, list, tuple, set or dictionary keys).

Membership කාරක අගයක් අනුක්‍රමයක් (string, list, tuple, set හෝ dictionary keys) තුළ ඇත්දැයි පරීක්ෂා කරයි.

OperatorReturns True when…Example → Result
invalue is present3 in [1,2,3] → True
not invalue is absent5 not in [1,2,3] → True
Python
fruits = ["apple", "mango"]
print("apple" in fruits)       # True
print("banana" not in fruits)  # True
print("a" in "cat")            # True
True True True
9.17
Handling Databases & Text Files
දත්ත සමුදාය සහ Text Files හැසිරවීම

9.17.1 – File Handling

9.17.1 – ගොනු හැසිරවීම (File Handling)

File handling lets a program store data permanently by reading from and writing to text files. The steps are: open → read/write → close.

File handling මඟින් text files වෙතින් කියවීමෙන් හා ලිවීමෙන් වැඩසටහනකට දත්ත ස්ථිරව ගබඩා කළ හැක. පියවර: open → read/write → close.

ModeMeaning
"r"Read (file must exist)
"w"Write (creates/overwrites the file)
"a"Append (adds to the end)
Python — writing to a file
f = open("data.txt", "w")     # open for writing
f.write("Hello Python\n")
f.write("Second line\n")
f.close()                     # always close the file
Python — reading a file
f = open("data.txt", "r")
content = f.read()            # read the whole file
print(content)
f.close()
Hello Python Second line
Always close() a file after use, or use with open(...) as f: which closes it automatically. Opening a file in "w" mode erases existing contents.
9.18
Database Management Using Python
Python මඟින් දත්ත සමුදාය කළමනාකරණය

9.18.1 – Databases That Connect with Python

9.18.1 – Python සමඟ සම්බන්ධ වන දත්ත සමුදායන්

Python can connect to several databases, most commonly SQLite (built in), as well as MySQL and PostgreSQL. SQLite needs no separate server, so it is ideal for learning.

Python හට දත්ත සමුදායන් කිහිපයකට සම්බන්ධ විය හැක; වඩාත් ප්‍රචලිත වන්නේ SQLite (බිල්ට්-ඉන්) වන අතර MySQL සහ PostgreSQL ද භාවිතා වේ. SQLite වෙනම server එකක් අවශ්‍ය නොවන නිසා ඉගෙනීමට ඉතා සුදුසුය.

Python — create table & insert
import sqlite3

conn = sqlite3.connect("school.db")     # connect / create DB
cur = conn.cursor()

cur.execute("CREATE TABLE IF NOT EXISTS students (name TEXT, marks INT)")
cur.execute("INSERT INTO students VALUES ('Kamal', 85)")
cur.execute("INSERT INTO students VALUES ('Nimal', 72)")

conn.commit()      # save changes
conn.close()

9.18.2 – Data Retrieval

9.18.2 – දත්ත ලබා ගැනීම (Data Retrieval)

Python — retrieve data
import sqlite3
conn = sqlite3.connect("school.db")
cur = conn.cursor()

cur.execute("SELECT * FROM students")
rows = cur.fetchall()      # get all rows
for row in rows:
    print(row)

conn.close()
('Kamal', 85) ('Nimal', 72)
Key steps: connect() → cursor() → execute(SQL) → commit() (for changes) or fetchall() (for reading) → close().
9.19
Searching & Selecting Data
දත්ත සෙවීම සහ තේරීම

9.19.1 – Searching Techniques

9.19.1 – සෙවීම් ක්‍රම (Searching)

9.19.1.1 – Sequential (Linear) Search

Checks each item one by one from the start until the value is found. Works on any list (sorted or not) but is slow for large lists.

අගය හමුවන තෙක් මුල සිට එක් එක් අයිතමය පිළිවෙළින් පරීක්ෂා කරයි. ඕනෑම list එකක (sorted වූ හෝ නොවූ) ක්‍රියා කරයි; නමුත් විශාල lists සඳහා මන්දගාමීය.

Python — Linear Search
nums = [4, 8, 15, 16, 23, 42]
target = 16
found = False

for i in range(len(nums)):
    if nums[i] == target:
        print("Found at index", i)
        found = True
        break

if not found:
    print("Not found")
Found at index 3

9.19.1.2 – Binary Search

Works only on a sorted list. It repeatedly checks the middle value and discards half the list each time — much faster than linear search.

ක්‍රියා කරන්නේ sorted list එකක පමණි. සෑම වටයකම මැද අගය පරීක්ෂා කර list එකෙන් අඩක් ඉවත් කරයි — linear search එකට වඩා බෙහෙවින් වේගවත්ය.

Python — Binary Search
nums = [4, 8, 15, 16, 23, 42]     # must be sorted
target = 23
low = 0
high = len(nums) - 1
found = False

while low <= high:
    mid = (low + high) // 2
    if nums[mid] == target:
        print("Found at index", mid)
        found = True
        break
    elif nums[mid] < target:
        low = mid + 1
    else:
        high = mid - 1

if not found:
    print("Not found")
Found at index 4
Sequential SearchBinary Search
List must be sorted?NoYes
SpeedSlowerFaster
MethodCheck every itemHalve the list each time

9.19.2 – Sorting Techniques

9.19.2 – වර්ග කිරීමේ ක්‍රම (Sorting)

9.19.2.1 – Selection Sort

Repeatedly finds the smallest remaining value and moves it to its correct position.

ඉතිරි අගයන්ගෙන් කුඩාම අගය නැවත නැවත සොයාගෙන එය නිවැරදි ස්ථානයට ගෙන යයි.

Python — Selection Sort
nums = [29, 10, 14, 37, 13]
n = len(nums)

for i in range(n):
    small = i
    for j in range(i + 1, n):
        if nums[j] < nums[small]:
            small = j
    nums[i], nums[small] = nums[small], nums[i]   # swap

print(nums)
[10, 13, 14, 29, 37]

9.19.2.2 – Bubble Sort

Repeatedly compares neighbouring pairs and swaps them if they are in the wrong order, so large values "bubble" to the end.

යාබද යුගල නැවත නැවත සංසන්දනය කර වැරදි පිළිවෙළේ ඇත්නම් මාරු කරයි; එවිට විශාල අගයන් අගට "bubble" වේ.

Python — Bubble Sort
nums = [5, 1, 4, 2, 8]
n = len(nums)

for i in range(n - 1):
    for j in range(n - 1 - i):
        if nums[j] > nums[j + 1]:
            nums[j], nums[j + 1] = nums[j + 1], nums[j]  # swap

print(nums)
[1, 2, 4, 5, 8]
Searching and sorting are common structured-question topics. Be ready to (1) write or complete the code, and (2) trace each pass showing the list after every step.
Quick Reference
Python Exam Cheat Sheet
Python විභාග Cheat Sheet

Core syntax

මූලික Syntax

ConceptSyntax
Comment# comment
Outputprint("text")
Input (string)x = input("prompt")
Input (number)x = int(input())
If-elif-elseif c: … elif c: … else: …
While loopwhile c: …
For loopfor i in range(n): …
Functiondef name(params): return val
Break / Continuebreak / continue

Data structures at a glance

දත්ත ව්‍යුහ එක බැල්මෙන්

StructureCreateMutable?
String"abc"No
List[1, 2, 3]Yes
Tuple(1, 2, 3)No
Dictionary{"k": "v"}Yes
Set{1, 2, 3}Yes

Common functions

ප්‍රචලිත Functions

FunctionWorks onReturns
len(x)string, list, tuple, dict, setnumber of items
sum(x)list, tupletotal
max(x) / min(x)list, tuplelargest / smallest
sorted(x)list, tuplesorted list
type(x)anythingthe data type
Print this page (or use light mode) for a clean revision handout. Every heading number matches your textbook's Competency 09 contents.