This note covers advanced programming constructs in Python as required by the FBISE Grade 12 curriculum, including data structures (lists), file handling (disk I/O), and an introduction to using databases in Python.
All Python programs are built from three fundamental constructs:
| Construct | Description | Example Keyword |
|---|---|---|
| Sequence | Statements execute top-to-bottom in order | (default) |
| Selection | Decisions based on conditions | if, elif, else |
| Iteration | Repeating a block of code | for, while |
The default mode — Python executes each line one after another.
name = "Ali"
age = 17
print(name, "is", age, "years old")
Python uses indentation (4 spaces) to define code blocks — no curly braces needed.
marks = 75
if marks >= 80:
print("A Grade")
elif marks >= 60:
print("B Grade")
else:
print("C Grade")
for loop — collection-controlled; iterates over a sequence:
for i in range(1, 6): # prints 1 to 5
print(i)
while loop — condition-controlled; repeats while a condition is True:
count = 0
while count < 5:
print(count)
count += 1
Loop control statements:
break — exits the loop entirelycontinue — skips the current iteration and moves to the nextpass — does nothing (placeholder)A list is a mutable, ordered collection that can store mixed data types.
students = ["Ali", "Sara", "Ahmed"]
scores = [85, 92, 78]
| Operation | Syntax | Result |
|---|---|---|
| Access element | students[0] | "Ali" |
| Slice | students[1:3] | ["Sara", "Ahmed"] |
| Append | students.append("Zara") | adds to end |
| Remove | students.remove("Ali") | removes first match |
| Length | len(students) | 3 |
| Sort | scores.sort() | sorts in place |
for name in students:
print(name)
squares = [x**2 for x in range(1, 6)]
# Result: [1, 4, 9, 16, 25]
File handling allows a program to persist data to storage (hard disk) so it survives after the program ends.
| Mode | Description |
|---|---|
'r' | Read (default). File must exist. |
'w' | Write. Creates file or overwrites existing. |
'a' | Append. Creates file or adds to end. |
'x' | Create. Fails if file already exists. |
'rb' / 'wb' | Read/Write in binary mode. |
with open('students.txt', 'w') as f:
f.write("Ali\n")
f.write("Sara\n")
The with statement automatically closes the file even if an error occurs.
# Read entire file
with open('students.txt', 'r') as f:
content = f.read()
print(content)
# Read line by line
with open('students.txt', 'r') as f:
for line in f:
print(line.strip())
with open('students.txt', 'a') as f:
f.write("Ahmed\n")
scores = [85, 92, 78, 90]
with open('scores.txt', 'w') as f:
for score in scores:
f.write(str(score) + '\n')
print("Scores saved successfully.")
Python can interact with databases using the built-in sqlite3 module (no installation needed).
import sqlite3
# 1. Connect (creates DB file if not exists)
conn = sqlite3.connect('school.db')
# 2. Create a cursor
cursor = conn.cursor()
# 3. Create a table
cursor.execute('''
CREATE TABLE IF NOT EXISTS students (
id INTEGER PRIMARY KEY,
name TEXT,
marks INTEGER
)
''')
# 4. Insert data
cursor.execute("INSERT INTO students VALUES (1, 'Ali', 85)")
# 5. Query data
cursor.execute("SELECT * FROM students")
rows = cursor.fetchall()
for row in rows:
print(row)
# 6. Commit and close
conn.commit()
conn.close()
connect() — opens/creates a database filecursor() — object used to execute SQL commandsexecute() — runs an SQL statementfetchall() — retrieves all results as a list of tuplescommit() — saves changes permanentlyclose() — closes the connection| Topic | Key Concept |
|---|---|
| Lists | Mutable ordered sequences; support indexing, slicing, append, remove |
| File Handling | open() with modes 'r', 'w', 'a'; use with block |
| Databases | sqlite3 module; connect → cursor → execute → commit → close |
| Selection | if / elif / else with indentation |
| Iteration | for (collection) and while (condition) loops |