Tuesday, June 16, 2026

Programming with Python – Complete Study Guide 2026 Latest Updated for beginners

UNIT 9 – PYTHON PROGRAMMING (A/L ICT Sri Lanka)
Complete guide covering Introduction to Programming, Algorithms, Flowcharts, Python Fundamentals, Control Structures, Data Structures, Functions, File Handling, and Error Handling. This covers the core theory expected for Unit 9 and aligns perfectly with the Sri Lankan A/L ICT syllabus.
9.1 Introduction to Programming

Basic Definitions

  • Program: A set of instructions given to a computer to perform a task.
  • Programming: The process of writing, testing, debugging, and maintaining computer programs.

Why Programming? Automates tasks, solves problems efficiently, reduces human errors, and saves time.

Programming Languages

  • 1GL (Machine Language): Binary code (e.g., 10110011). Fast execution but difficult to understand and error-prone.
  • 2GL (Assembly Language): Uses mnemonics (e.g., MOV A,10). Requires an Assembler.
  • 3GL (High-Level Languages): Python, Java, C++, Pascal. Easy to read, easy debugging, and portable. (Python belongs to this category).

Language Translators

Feature Compiler (C, C++) Interpreter (Python)
Translation Whole program at once Line by line
Execution Speed Faster Slower
Object Code Generates object code No object code
Debugging Harder Easier
A/L Exam Question: Python uses which translator?
Answer: Interpreter.
9.2 Algorithms

Definition & Characteristics

An algorithm is a finite sequence of instructions for solving a problem.

  • Input: Accepts data (e.g., INPUT A).
  • Output: Produces result (e.g., PRINT SUM).
  • Definiteness: Every step must be clear.
  • Finiteness: Must end after finite steps.
  • Effectiveness: Each step must be practical.

Example: Add Two Numbers

START
INPUT A
INPUT B
SUM ← A + B
PRINT SUM
STOP

Control Structures

1. Sequence: Instructions executed one after another.

INPUT A, B
SUM = A + B
PRINT SUM

2. Selection: Decision making.

IF MARK >= 50 THEN
   PRINT PASS
ELSE
   PRINT FAIL
ENDIF

3. Iteration: Repeating instructions.

FOR I = 1 TO 5
   PRINT I
NEXT I
9.3 Flowcharts

Definition

A graphical representation of an algorithm using standard symbols.

Standard Symbols

Symbol Shape Purpose
OvalStart / Stop
RectangleProcess (Calculations)
ParallelogramInput / Output
DiamondDecision (Yes/No)
ArrowFlow Direction

Example: Find Area of Rectangle

START
  ↓
INPUT L, W
  ↓
AREA = L × W
  ↓
PRINT AREA
  ↓
STOP
9.4 Python Fundamentals

Features & First Program

Features: Simple syntax, Interpreted language, Open source, Cross-platform.

# First Python Program
print("Hello World")

Comments

# Single line comment

"""
Multi-line 
comment
"""

Variables & Naming Rules

Variables store data. Valid: student, student_name, age1. Invalid: 1age, student-name, class.

name = "Amal"
age = 18

Data Types

  • Integer: x = 10
  • Float: x = 10.5
  • String: name = "Kamal"
  • Boolean: status = True

Input and Output

# Input
name = input("Enter name:")
age = int(input())      # Integer input
salary = float(input()) # Float input

# Output
print(name)
Operators in Python

Arithmetic Operators

OperatorMeaning
+Add
-Subtract
*Multiply
/Divide
//Integer Division
%Modulus (Remainder)
**Power

Example: print(10 % 3) outputs 1.

Relational Operators

Operators: ==, !=, >, <, >=, <=

Example: 10 > 5 outputs True.

Logical Operators

Operators: and, or, not

Example: 5 > 2 and 4 < 8 outputs True.

Selection Statements & Loops

Selection (IF Statements)

# Simple IF
mark = 70
if mark >= 50:
    print("Pass")

# IF ELSE
mark = 45
if mark >= 50:
    print("Pass")
else:
    print("Fail")

# IF ELIF ELSE
mark = 80
if mark >= 75:
    print("A")
elif mark >= 65:
    print("B")
else:
    print("C")

Loops (Iteration)

# For Loop
for i in range(5):
    print(i) 
# Output: 0, 1, 2, 3, 4

# While Loop
i = 1
while i <= 5:
    print(i)
    i = i + 1
Data Structures: Strings & Lists

Strings

name = "Python"

# Indexing (Starts at 0)
print(name[0])  # Output: P

# Length
print(len(name)) # Output: 6

Lists

# Creating & Accessing
marks = [45, 67, 89]
print(marks[0])  # Output: 45

# Updating
marks[1] = 90

List Methods

  • marks.append(100) - Adds to the end
  • marks.insert(1, 50) - Inserts at index 1
  • marks.remove(67) - Removes value 67
  • marks.sort() - Sorts ascending
  • marks.reverse() - Reverses the list
Functions

Function Types

# 1. Without Parameters
def display():
    print("ICT")
display() # Calling the function

# 2. With Parameters
def add(a, b):
    print(a + b)

# 3. With Return Value
def add(a, b):
    return a + b
result = add(5, 10)
File Handling

What is File Handling?

File handling means using a program to create, open, read, write, append, and close files stored on a computer.

If data is stored only in variables, it disappears when the program ends. Files allow data to be saved permanently.

Example Data File

marks.txt

Amal     75
Kamal    82
Nimal    68

Important Definition

File handling is the process of creating, opening, reading, writing, appending and closing files using a computer program.

open() Function

open(filename, mode)

f = open("students.txt", "r")

Here, f is the file object, students.txt is the file name, and "r" is the reading mode.

File Modes ⭐

Mode Meaning
"r" Read mode
"w" Write mode / overwrite
"a" Append mode
"x" Create a new file

Read Mode

f = open("students.txt", "r")

Write Mode

f = open("students.txt", "w")

Important: If the file already has data, "w" mode can replace the old contents.

Append Mode

f = open("students.txt", "a")

Append mode adds new data to the end of the file without deleting existing content.

Create Mode

f = open("newfile.txt", "x")

If the file already exists, an error occurs.

read()

f = open("students.txt", "r")
data = f.read()
print(data)
f.close()

readline()

f = open("students.txt", "r")
line = f.readline()
print(line)
f.close()

readline() reads only one line from the file.

readlines()

f = open("students.txt", "r")
data = f.readlines()
print(data)
f.close()

readlines() returns all lines as a list.

Reading Functions Summary

Function What it does
read() Reads entire file
readline() Reads one line
readlines() Reads all lines and returns a list

write()

f = open("students.txt", "w")

f.write("Amal\n")
f.write("Kamal\n")
f.write("Nimal\n")

f.close()

Important: write() needs a string.

f.write("75")      # Correct

f.write(75)        # Error
f.write(str(75))   # Correct

close()

f.close()

Closing a file releases resources and helps make sure data is properly saved.

with open()

with open("students.txt", "r") as f:
    data = f.read()
    print(data)

The with statement automatically closes the file after the block finishes.

Newline Character \n

f.write("Amal\n")
f.write("Kamal\n")

Without \n, the file may become:

AmalKamal

File Copy Program ⭐⭐⭐

Write a Python program to copy all contents of A.txt into B.txt.

with open("A.txt", "r") as f1:
    data = f1.read()

with open("B.txt", "w") as f2:
    f2.write(data)

File Handling Exam Questions

Question 1:

If data.txt contains:

ICT
Python
Programming

What is the output of this program?

f = open("data.txt", "r")
x = f.readline()
print(x)
f.close()

Answer:

ICT

Question 2:

What is the difference between "w" and "a" modes?

  • w mode: Writes data and can overwrite existing contents.
  • a mode: Adds data to the end of the file without removing existing contents.

Question 3:

Write Python code to add "ICT" to the end of subjects.txt.

f = open("subjects.txt", "a")
f.write("ICT\n")
f.close()

Question 4:

Write Python code to read all contents of marks.txt.

f = open("marks.txt", "r")
data = f.read()
print(data)
f.close()
Errors in Python

What is an Error?

An error is a problem in a program that causes the program to behave incorrectly or prevents it from executing properly.

For A/L ICT, understand these three major categories:

  • Syntax Errors
  • Runtime Errors
  • Logical Errors

Syntax Error

A syntax error occurs when the rules of the programming language are violated.

if x > 10
    print(x)

This is wrong because the colon : is missing.

if x > 10:
    print(x)

Runtime Error

A runtime error occurs while the program is running.

x = 10
y = 0

print(x / y)

This causes ZeroDivisionError.

x = int("ABC")

This causes ValueError.

Logical Error

The program executes, but produces the wrong result.

a = 10
b = 5

answer = a - b
print(answer)

The program runs, but if the programmer wanted a + b, the output is wrong.

Error Comparison

Error When? Example
Syntax Error Before/while interpreting code Missing :
Runtime Error During execution Divide by zero
Logical Error Program runs but gives wrong answer - instead of +

Memory Trick

  • Syntax → Rules
  • Runtime → Running
  • Logical → Wrong thinking/calculation
Exception Handling

What is an Exception?

An exception is an abnormal situation that occurs during program execution.

x = 10
y = 0

print(x / y)

This raises ZeroDivisionError.

try and except ⭐⭐⭐

try:
    x = 10 / 0
except:
    print("An error occurred")

Output:

An error occurred

Handling a Specific Exception

try:
    x = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero")

User Input Example

try:
    num = int(input("Enter a number: "))
    print(num)
except ValueError:
    print("Please enter a valid number")

Common Python Exceptions

Exception Example
ZeroDivisionError 10 / 0
ValueError int("ABC")
TypeError "10" + 5
IndexError Invalid list index
FileNotFoundError Opening a file that does not exist
KeyError Invalid dictionary key

File Handling + Error Handling ⭐⭐⭐

try:
    f = open("marks.txt", "r")
    data = f.read()
    print(data)
    f.close()

except FileNotFoundError:
    print("File does not exist")

else

try:
    x = int(input("Enter number: "))
except ValueError:
    print("Invalid number")
else:
    print("Number entered:", x)

The else block runs when there is no exception.

finally

try:
    x = 10 / 2
    print(x)

except ZeroDivisionError:
    print("Cannot divide by zero")

finally:
    print("Program finished")

The finally block always executes.

Full Exception Handling Example

try:
    num1 = int(input("Enter first number: "))
    num2 = int(input("Enter second number: "))

    answer = num1 / num2

except ValueError:
    print("Please enter numbers only")

except ZeroDivisionError:
    print("Cannot divide by zero")

else:
    print("Answer =", answer)

finally:
    print("End of program")
A/L Exam Style Questions

Question 1 — MCQ

Which Python mode is used to append data to an existing text file?

  1. r
  2. w
  3. a
  4. x

Answer: 3. a

Question 2 — MCQ

Which function reads the entire contents of a file?

  1. readline()
  2. read()
  3. write()
  4. append()

Answer: 2. read()

Question 3

What happens when the following code executes?

x = 20
y = 0
print(x / y)

Answer: A ZeroDivisionError occurs.

Question 4

Identify the type of error.

x = 10

if x > 5
    print(x)

Answer: Syntax Error

Reason: Missing : after the condition.

Question 5

Identify the error:

numbers = [10, 20, 30]

print(numbers[5])

Answer: IndexError

Question 6 — Coding ⭐

Write a Python program to read a file called students.txt and display its contents. If the file does not exist, display "File not found".

try:
    f = open("students.txt", "r")
    data = f.read()
    print(data)
    f.close()

except FileNotFoundError:
    print("File not found")

Question 7 — Coding ⭐⭐⭐

Write a Python program that asks the user to enter two numbers and displays their division. Handle the situation where the second number is zero.

try:
    a = int(input("Enter first number: "))
    b = int(input("Enter second number: "))

    print(a / b)

except ZeroDivisionError:
    print("Cannot divide by zero")

Question 8 — File Copy ⭐⭐⭐

A text file called A.txt contains data. Write Python code to copy all data from A.txt into B.txt.

with open("A.txt", "r") as f1:
    data = f1.read()

with open("B.txt", "w") as f2:
    f2.write(data)
Exam Memory Sheet

File Handling

open()       → Open file
read()       → Read entire file
readline()   → Read one line
readlines()  → Read lines as list
write()      → Write data
close()      → Close file

File Modes

r → Read
w → Write / overwrite
a → Append
x → Create

Errors

Syntax Error
     ↓
Wrong Python grammar

Runtime Error
     ↓
Problem while program runs

Logical Error
     ↓
Program runs but gives wrong answer

Exception Handling

try:
    # code that may cause exception
except:
    # handle exception
else:
    # runs if no exception
finally:
    # always runs

Priority Order for A/L Exam

  1. open() + file modes ⭐⭐⭐
  2. read(), readline(), write() ⭐⭐⭐
  3. File copy program ⭐⭐⭐
  4. close() and with open() ⭐⭐
  5. Syntax / Runtime / Logical errors ⭐⭐⭐
  6. try / except ⭐⭐⭐
  7. Common exceptions ⭐⭐
  8. else / finally ⭐⭐
🌟 Frequently Asked A/L Questions

Q1: What are the three control structures?
Answer: 1. Sequence, 2. Selection, 3. Iteration.

Q2: Differentiate Compiler and Interpreter.

Compiler Interpreter
Whole program translatedLine by line
Faster executionSlower execution
Generates object codeNo object code

Q3: Write a Python program to find the largest of two numbers.

a = int(input())
b = int(input())

if a > b:
    print(a)
else:
    print(b)

Q4: Write a program to print numbers from 1 to 10.

for i in range(1, 11):
    print(i)

Q5: Create a list and print all values.

num = [10, 20, 30, 40]

for x in num:
    print(x)

🎓 Expert ICT, Coding, School Classes, Digital Marketing & University Project Guidance

Struggling with your university final year project? Want to master coding, upscale your business with expert digital marketing, or learn absolute computer basics from scratch? We offer high-quality individual and group online classes conducted in English, Sinhala, or Tamil mediums. Get guaranteed academic success and professional growth with tailored guidance.


🎓 University Final Year Project Guidance & AI

Get specialized, end-to-end mentoring and technical support to pass your degree or master's program with flying colors:

  • 🏫 Targeted Institutes: Expert guidance tailored for BIT UCSC, UoM, SLIIT, NIBM, and other leading universities.
  • 🔬 Postgraduate Support: Comprehensive assistance for MSc Software Final Year Projects.
  • 🤖 AI & Smart Applications: Step-by-step implementation of AI, Machine Learning (ML), and automation modules.
  • Guaranteed Success: Help with documentation, system architecture, coding, and viva preparation.

🏫 School ICT & Corporate Beginner Classes

  • 💻 Non-IT Staff Computer Basics: Absolute beginner-friendly online classes covering essential computer skills, office tools, and internet operations.
  • 🎒 Primary & Secondary (Grades 1-10): Interactive online ICT classes tailored to build strong foundations from early ages.
  • 📝 Exam Prep: Dedicated training packages for GCE O/L, GCE A/L ICT, and GIT exams.
  • 🌍 Global Syllabuses: Complete curriculum coverage for Local, Edexcel, and Cambridge in English & Tamil Mediums.

📢 Software Development & Digital Marketing Services

  • ⚙️ Software & Web Development: Professional custom software application and website development built using PHP & MySQL.
  • 🎯 Social Media Management: Content creation, publishing, and channel management for Facebook, Instagram, TikTok, and YouTube.
  • 📈 Ad Boosting: Highly targeted paid advertising campaigns to drive leads, traffic, and sales to your business.

📞 Connect With Us Instantly

Book your slot for online classes or get a premium tech service quote today!

💬 WhatsApp: +94 729622034

📧 Email: ITClassSL@gmail.com


🌐 Explore Our Resources & Communities

Stay updated with our latest tutorials, project ideas, and student guides across all our official platforms:

No comments:

Post a Comment