Competency 09:
Python — Algorithms & Encoding
Complete teaching guide — problem solving, algorithms, and the full Python language, with theory, runnable-style code examples, output previews, and exam-focus notes.
සම්පූර්ණ ඉගැන්වීම් මාර්ගෝපදේශය — ගැටලු විසඳීම, ඇල්ගොරිතම සහ සම්පූර්ණ Python භාෂාව; න්යාය, ක්රියාත්මක කළ හැකි කේත උදාහරණ, ප්රතිදාන පෙරදසුන් සහ විභාගයට අවධානය යොමු කළ සටහන් සමඟ.
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.
කේත පේළියක් ලිවීමට පෙර, ක්රමලේඛකයෙකු ගැටලුව සම්පූර්ණයෙන් තේරුම් ගෙන විසඳුමක් සැලසුම් කළ යුතුය. ගැටලු විසඳීමේ ක්රියාවලියේ ප්රධාන අදියර හතරක් ඇත.
| Stage | What Happens |
|---|---|
| 1. Understanding the Problem | Read the problem carefully. Identify what is given (inputs), what is required (outputs), and any conditions. |
| 2. Definition of Problem & Boundaries | Clearly state the problem in your own words and set its limits — what the solution must and must not do. |
| 3. Planning the Solution | Design a step-by-step method (algorithm) using flowcharts or pseudocode. |
| 4. Check Solutions & Select the Best | Compare possible solutions and choose the most efficient and correct one. |
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
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 යනු එක් එක් පියවර කේත කිරීමට තරම් සරල වන තෙක් වඩාත් සවිස්තර පියවරවලට පිරිපහදු කිරීමේ ක්රමයයි.
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 පහළට අතු බෙදේ.
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:
ඇල්ගොරිතමයක් යනු ගැටලුවක් විසඳන, සීමිත හා පිළිවෙළකට සකසන ලද පැහැදිලි පියවර සමූහයකි. හොඳ ඇල්ගොරිතමයක මෙම ගුණාංග ඇත:
| Property | Meaning |
|---|---|
| Finiteness | Must end after a finite number of steps |
| Definiteness | Each step is clear and unambiguous |
| Input | Zero or more inputs are supplied |
| Output | Produces at least one result |
| Effectiveness | Each 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 එකක් ඇල්ගොරිතමයක පියවර ගලා යන ආකාරය පෙන්වීමට, ඊතලවලින් සම්බන්ධ කළ සම්මත සංකේත භාවිතා කරයි.
| Symbol | Name | Purpose |
|---|---|---|
| Oval / Rounded box | Terminator | Start or Stop of the algorithm |
| Parallelogram | Input / Output | Read data or display results |
| Rectangle | Process | A calculation or action |
| Diamond | Decision | A Yes/No (True/False) condition |
| Arrow | Flow line | Shows direction of flow |
Example flowchart — largest of two numbers
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 වෙත පරිවර්තනය කිරීම පහසුය.
BEGIN
READ A, B
IF A > B THEN
PRINT A
ELSE
PRINT B
ENDIF
ENDCommon 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 එකක සටහන් කිරීමයි. මෙමඟින් පරිගණකයේ ධාවනයට පෙර තර්කය නිවැරදිදැයි පරීක්ෂා වේ.
total = 0
FOR n = 1 TO 3
total = total + n
END FOR
PRINT totalTrace table
| Step | n | total | Output |
|---|---|---|---|
| Start | - | 0 | |
| n = 1 | 1 | 1 | |
| n = 2 | 2 | 3 | |
| n = 3 | 3 | 6 | |
| End | 3 | 6 | 6 |
9.4.1 – Evolution of Programming Languages
9.4.1 – ක්රමලේඛන භාෂාවල පරිණාමය
Programming languages developed through generations, moving from machine-level to human-friendly:
ක්රමලේඛන භාෂා පරම්පරා (generations) ඔස්සේ, යන්ත්ර මට්ටමේ සිට මිනිසාට හිතකර මට්ටම දක්වා වර්ධනය විය:
| Generation | Type | Description |
|---|---|---|
| 1GL | Machine language | Binary (0s and 1s) — directly understood by the CPU |
| 2GL | Assembly language | Uses mnemonics (ADD, MOV); needs an assembler |
| 3GL | High-level languages | English-like: C, Java, Python; needs a compiler/interpreter |
| 4GL | Very high-level | Closer to human language: SQL, report generators |
| 5GL | AI / logic | Problem-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 එකක් යනු වැඩසටහන් ලිවීමේ විලාසයක් හෝ ප්රවේශයකි.
| Paradigm | Idea | Examples |
|---|---|---|
| Procedural | Program is a sequence of procedures/functions that operate on data | C, Pascal, Python |
| Object-Oriented (OOP) | Program is built from objects that combine data and methods | Java, C++, Python |
| Functional | Computation as evaluation of mathematical functions; avoids changing state | Haskell, Lisp |
| Logic | Program is a set of facts and rules; you state what, not how | Prolog |
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.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
| Term | Meaning |
|---|---|
| Source Program | The code written by the programmer in a high-level (or assembly) language |
| Object Program | The translated machine-code version produced by the translator |
9.5.4 – Program Translators
9.5.4 – Program Translators (වැඩසටහන් පරිවර්තක)
| Interpreter | Compiler | |
|---|---|---|
| Translation | Line by line | Whole program at once |
| Output file | No separate object file | Produces an object/executable file |
| Speed of execution | Slower | Faster (after compiling) |
| Error reporting | Stops at the first error found | Reports all errors after scanning |
| Example | Python, JavaScript | C, C++ |
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 වැඩසටහනක් නිපදවයි.
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 එකක මූලික පහසුකම්
| Feature | Purpose |
|---|---|
| Code Editor | Where you type your program, with syntax highlighting |
| Syntax Highlighting | Colours keywords, strings and comments to improve readability |
| Auto-completion | Suggests code as you type |
| Debugger | Helps find and fix errors by running code step by step |
| Compiler / Interpreter | Runs the program from inside the IDE |
| Output / Console window | Displays program output and error messages |
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 (හිස්තැන්) භාවිතා කරයි.
# A simple Python program
name = input("Enter your name: ")
print("Hello,", name)
print("Welcome to Python")9.7.2 – Comments in Programs
9.7.2 – වැඩසටහන්වල Comments
Comments explain code and are ignored by the interpreter.
Comments කේතය පැහැදිලි කරයි; interpreter ඒවා නොසලකා හරියි.
# 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
age = 17 # integer price = 250.75 # float name = "Nimal" # string passed = True # boolean print(age, price, name, passed)
9.7.3.2 – Assign the same value to multiple variables
x = y = z = 0 print(x, y, z)
9.7.3.3 – Assign different values to several variables
a, b, c = 10, 20, 30 print(a, b, c)
9.7.3.4 – Rules & good practice for naming variables
| Rule | Valid | Invalid |
|---|---|---|
| Must start with a letter or underscore | name, _total | 2name |
| Can contain letters, digits, underscores | marks1 | marks-1 |
| No spaces | first_name | first name |
| Cannot be a keyword | total | if, for |
| Case-sensitive | Age and age are different variables | |
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 අකුරින් ලියූ විචල්යයක් වෙනස් නොකළ යුතු නියතයක් ලෙස සලකයි.
PI = 3.14159 MAX_MARKS = 100 print(PI, MAX_MARKS)
9.7.5 – Local & Global Variables
9.7.5 – Local සහ Global විචල්ය
| Type | Where it is defined | Where it can be used |
|---|---|---|
| Global | Outside all functions | Anywhere in the program |
| Local | Inside a function | Only inside that function |
total = 100 # global variable
def show():
msg = "Hello" # local variable
print(msg, total)
show()
print(total) # works
# print(msg) # ERROR: msg is local9.7.6 – Primitive Data Types
9.7.6 – ප්රාථමික දත්ත වර්ග
| Type | Keyword | Example | Meaning |
|---|---|---|---|
| Integer | int | 25, -7 | Whole numbers |
| Float | float | 3.14, -0.5 | Numbers with a decimal point |
| String | str | "Hello" | Text (in quotes) |
| Boolean | bool | True, False | Logical values |
print(type(25)) # <class 'int'>
print(type(3.14)) # <class 'float'>
print(type("Hi")) # <class 'str'>
print(type(True)) # <class 'bool'>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
| Op | Meaning | Example (a=7, b=2) | Result |
|---|---|---|---|
+ | Addition | a + b | 9 |
- | Subtraction | a - b | 5 |
* | Multiplication | a * b | 14 |
/ | Division (float) | a / b | 3.5 |
// | Floor division | a // b | 3 |
% | Modulus (remainder) | a % b | 1 |
** | Exponent (power) | a ** b | 49 |
Relational (comparison) operators
== equal, != not equal, > greater, < less, >= greater-or-equal, <= less-or-equal. All return True or False.
Logical operators
| Op | True when… | Example |
|---|---|---|
and | Both conditions are True | (a>0) and (b>0) |
or | At least one is True | (a>0) or (b>0) |
not | Reverses the result | not(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 සහිත කාරක පළමුව ක්රියාත්මක වේ. පිළිවෙළ පාලනයට වරහන් භාවිතා කරන්න.
| Priority | Operators |
|---|---|
| 1 (highest) | ( ) parentheses |
| 2 | ** exponent |
| 3 | * / // % |
| 4 | + - |
| 5 | relational < > == != |
| 6 (lowest) | not → and → or |
print(2 + 3 * 4) # 14 (× before +) print((2 + 3) * 4) # 20 (brackets first) print(2 ** 3 + 1) # 9 (power first)
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 එකක් ලෙස කියවයි.
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)input() always returns a string, you must use int() or float() before doing arithmetic. Forgetting this is a very common error.Control structures decide the order in which statements run. There are three basic types:
පාලන ව්යුහ මඟින් ප්රකාශ ක්රියාත්මක වන පිළිවෙළ තීරණය වේ. මූලික වර්ග තුනකි:
| Type | Meaning |
|---|---|
| Sequence | Statements run one after another, top to bottom |
| Selection | A 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
marks = int(input("Marks: "))
if marks >= 50:
print("Pass")9.8.1.2 – if...else
marks = int(input("Marks: "))
if marks >= 50:
print("Pass")
else:
print("Fail")9.8.1.3 – if...elif...else (nested selection)
marks = int(input("Marks: "))
if marks >= 75:
print("Distinction")
elif marks >= 65:
print("Credit")
elif marks >= 50:
print("Pass")
else:
print("Fail")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 වාර ගණන කලින් නොදන්නා විට භාවිතා කරන්න.
count = 1
while count <= 5:
print(count)
count = count + 1 # update — very important!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) හරහා.
for i in range(1, 6): # 1,2,3,4,5 (6 not included)
print(i)
for fruit in ["apple", "mango", "banana"]:
print(fruit)range() form | Produces |
|---|---|
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
| Statement | Effect |
|---|---|
break | Exits the loop immediately |
continue | Skips the rest of this pass and goes to the next |
for i in range(1, 6):
if i == 3:
continue # skip 3
if i == 5:
break # stop at 5
print(i)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 රාශියක් සපයයි:
| Function | Purpose | Example |
|---|---|---|
print() | Display output | print("Hi") |
input() | Read input | input("Name: ") |
len() | Length | len("abc") → 3 |
int()/float()/str() | Type casting | int("5") → 5 |
max()/min() | Largest / smallest | max(3,7) → 7 |
sum() | Total of a list | sum([1,2,3]) → 6 |
range() | Sequence of numbers | range(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
def greet():
print("Hello, welcome!")
greet() # calling the function
greet() # can be called many times9.9.2.2 – Passing values with parameters
def greet(name):
print("Hello", name)
greet("Kamal")
greet("Nimal")9.9.2.3 – Return values
A function can send back a result with return.
Function එකකට return මඟින් ප්රතිඵලයක් ආපසු යැවිය හැක.
def add(a, b):
return a + b
result = add(10, 5)
print("Sum =", result)9.9.3 – Types of Errors in Python
9.9.3 – Python හි දෝෂ (Errors) වර්ග
| Error Type | When it happens | Example |
|---|---|---|
| 9.9.3.1 Syntax error | The code breaks Python grammar rules; found before running | print("Hi" (missing bracket) |
| 9.9.3.2 Runtime error | Occurs while the program runs; it crashes | 10 / 0 (division by zero) |
| 9.9.3.3 Logical error | Program runs but gives the wrong answer | Using + instead of * in a formula |
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 හි දත්ත ව්යුහ වර්ග
| Structure | Symbol | Ordered? | Changeable? | Duplicates? |
|---|---|---|---|---|
| String | " " | Yes | No (immutable) | Yes |
| List | [ ] | Yes | Yes | Yes |
| Tuple | ( ) | Yes | No (immutable) | Yes |
| Dictionary | { key:value } | Yes* | Yes | No (keys) |
| Set | { } | No | Yes | No |
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 ලෙසත් ආරම්භ වේ.
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)
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 සඳහා තනි ' ' හෝ ද්විත්ව " " උද්ධෘත භාවිතා කළ හැක. එක් වර්ගයක් ඇතුළත අනෙක යෙදීමට අනෙක් වර්ගය භාවිතා කරන්න.
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
| # | Task | Function | Example → Result |
|---|---|---|---|
| 1 | Number of characters | len() | len("Python") → 6 |
| 2 | Capitalise first letter of each word | .title() | "good day".title() → Good Day |
| 3 | All UPPERCASE | .upper() | "abc".upper() → ABC |
| 4 | All lowercase | .lower() | "ABC".lower() → abc |
| 5 | Join lines / words | .join() | "-".join(["a","b"]) → a-b |
| 6 | Accept only numeric | .isdigit() | "25".isdigit() → True |
| 7 | Check lowercase | .islower() | "abc".islower() → True |
| 8 | Check uppercase | .isupper() | "ABC".isupper() → True |
| 9 | Split a sentence | .split() | "a b c".split() → ['a','b','c'] |
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()) # True9.11.3.10 – String Operators
| Operator | Meaning | Example → Result |
|---|---|---|
+ | Concatenation (join) | "Sri" + "Lanka" → SriLanka |
* | Repetition | "ab" * 3 → ababab |
in | Membership | "a" in "cat" → True |
A list stores multiple ordered, changeable items inside square brackets [ ]. Items can be of any type.
List එකක් square brackets [ ] තුළ පිළිවෙළ සහිත, වෙනස් කළ හැකි අයිතම කිහිපයක් ගබඩා කරයි. අයිතම ඕනෑම වර්ගයක විය හැක.
fruits = ["apple", "mango", "banana"] marks = [65, 78, 90, 45] mixed = ["Kamal", 17, True] print(fruits)
9.12.1 – Nested Lists
9.12.1 – Nested Lists
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)
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)
9.12.9 – Basic List Functions
9.12.9 – මූලික List Functions
| Function | Purpose | Example (n=[3,1,2]) |
|---|---|---|
len(n) | Number of items | 3 |
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 last | returns 2 |
n.count(3) | How many times value appears | 1 |
n.sort() | Sort ascending | [1,2,3] |
n.clear() | Empty the list | [ ] |
sum(n) | Total | 6 |
max(n) / min(n) | Largest / smallest | 3 / 1 |
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]append(), sort(), sum(), max(), min() and len() well.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 එකින් නොවේ.
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| Task | Code |
|---|---|
| Access a value | d["key"] |
| Add / update | d["key"] = value |
| Remove | del d["key"] |
| All keys | d.keys() |
| All values | d.values() |
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 ( ) භාවිතා කරයි.
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)
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).A set is an unordered collection with no duplicate values, written in curly braces { }.
Set එකක් යනු අනුපිළිවෙළක් නැති, අනුපිටපත් නොමැති අගයන් සහිත එකතුවකි; curly braces { } තුළ ලියයි.
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) # Trueset([1,1,2,3]) → {1, 2, 3}.Membership operators check whether a value exists inside a sequence (string, list, tuple, set or dictionary keys).
Membership කාරක අගයක් අනුක්රමයක් (string, list, tuple, set හෝ dictionary keys) තුළ ඇත්දැයි පරීක්ෂා කරයි.
| Operator | Returns True when… | Example → Result |
|---|---|---|
in | value is present | 3 in [1,2,3] → True |
not in | value is absent | 5 not in [1,2,3] → True |
fruits = ["apple", "mango"]
print("apple" in fruits) # True
print("banana" not in fruits) # True
print("a" in "cat") # True9.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.
| Mode | Meaning |
|---|---|
"r" | Read (file must exist) |
"w" | Write (creates/overwrites the file) |
"a" | Append (adds to the end) |
f = open("data.txt", "w") # open for writing
f.write("Hello Python\n")
f.write("Second line\n")
f.close() # always close the filef = open("data.txt", "r")
content = f.read() # read the whole file
print(content)
f.close()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.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 එකක් අවශ්ය නොවන නිසා ඉගෙනීමට ඉතා සුදුසුය.
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)
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()connect() → cursor() → execute(SQL) → commit() (for changes) or fetchall() (for reading) → close().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 සඳහා මන්දගාමීය.
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")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 එකට වඩා බෙහෙවින් වේගවත්ය.
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")| Sequential Search | Binary Search | |
|---|---|---|
| List must be sorted? | No | Yes |
| Speed | Slower | Faster |
| Method | Check every item | Halve 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.
ඉතිරි අගයන්ගෙන් කුඩාම අගය නැවත නැවත සොයාගෙන එය නිවැරදි ස්ථානයට ගෙන යයි.
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)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" වේ.
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)Core syntax
මූලික Syntax
| Concept | Syntax |
|---|---|
| Comment | # comment |
| Output | print("text") |
| Input (string) | x = input("prompt") |
| Input (number) | x = int(input()) |
| If-elif-else | if c: … elif c: … else: … |
| While loop | while c: … |
| For loop | for i in range(n): … |
| Function | def name(params): return val |
| Break / Continue | break / continue |
Data structures at a glance
දත්ත ව්යුහ එක බැල්මෙන්
| Structure | Create | Mutable? |
|---|---|---|
| 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
| Function | Works on | Returns |
|---|---|---|
len(x) | string, list, tuple, dict, set | number of items |
sum(x) | list, tuple | total |
max(x) / min(x) | list, tuple | largest / smallest |
sorted(x) | list, tuple | sorted list |
type(x) | anything | the data type |