Advanced Programming & Software Engineering

Class 9 · Ages 14–15
And He taught man that which he knew not. (96:5)
Advanced Python · Data Structures · Algorithms · Web Dev · Computer Architecture · OS · Networks · Databases · Software Engineering · Islamic Ethics

Learning Objectives

Topic 1 Advanced Python Programming

Python Beyond the Basics

In previous classes, you learned the fundamentals of Python. Now it's time to explore more advanced features that make Python a powerful language for real-world applications.

Functions: Advanced Concepts

  • Default Arguments – Functions can have default values for parameters.
    def greet(name, greeting="Assalamu Alaikum"):
        print(f"{greeting}, {name}!")

    greet("Ahmed") # Assalamu Alaikum, Ahmed!
    greet("Fatima", "Salam") # Salam, Fatima!
  • Variable Arguments (*args, **kwargs) – Accept any number of arguments.
    def sum_all(*numbers):
        return sum(numbers)

    print(sum_all(1, 2, 3, 4, 5)) # 15
  • Lambda Functions – One-line anonymous functions.
    square = lambda x: x * x
    print(square(5)) # 25
Fun Fact!

Python's popularity has grown massively. It's now the most popular language for data science and artificial intelligence!

File Handling

  • Reading Files – Open and read data from files.
    with open('data.txt', 'r') as file:
        content = file.read()
        print(content)
  • Writing Files – Write data to files.
    with open('output.txt', 'w') as file:
        file.write("Hello, World!")
  • File Modes – 'r' (read), 'w' (write), 'a' (append), 'r+' (read and write).

Error Handling (Try/Except)

  • Try/Except – Catch and handle errors gracefully.
    try:
        num = int(input("Enter a number: "))
        print(10 / num)
    except ValueError:
        print("Please enter a valid number!")
    except ZeroDivisionError:
        print("Cannot divide by zero!")
  • Finally – Code that always runs, whether there's an error or not.
    try:
        file = open('data.txt', 'r')
        # Process file
    finally:
        file.close()
Try This!

Create a program that reads a file of student grades and calculates the average.

1. Create a file called "grades.txt" with numbers (one per line).
2. Write a Python program that reads the file.
3. Calculate the average using a function.
4. Handle errors if the file doesn't exist or has invalid data.

You're building real-world applications!

Activity

Write a Python program that:

1. Reads a file called "students.txt" with names and grades.
2. Calculates the average grade.
3. Finds the highest and lowest grade.
4. Writes the results to a file called "report.txt".
5. Uses error handling to manage file errors.

Test your program with different input files.

Reflect

Allah has given us the ability to create and solve problems. The Qur'an says: "And We have certainly made the Qur'an easy to remember..." (54:17)

Just as we learn to handle errors in programming, we should learn to handle challenges in life with patience and grace. Every error is an opportunity to learn and grow.

Key Takeaway

Advanced Python includes functions with default arguments and variable arguments, lambda functions for one-line expressions, file handling to read and write data, and error handling using try/except blocks. These skills are essential for building robust, real-world applications.

Topic 2 Data Structures

What are Data Structures?

Data structures are ways to organize and store data efficiently. Choosing the right data structure can make your programs faster and easier to write.

Lists (Review & Advanced)

  • List Comprehensions – Create lists in a single line.
    squares = [x**2 for x in range(10)]
    print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
  • List Methods – .append(), .extend(), .insert(), .remove(), .pop(), .sort().
Fun Fact!

The list is one of the most versatile data structures in Python. It can hold different data types and is used in almost every Python program.

Tuples

  • Tuples – Immutable lists (cannot be changed after creation).
    coordinates = (10, 20)
    x, y = coordinates # Tuple unpacking
    print(x, y) # 10 20
  • Why use tuples? They are faster and safer when you don't want data to change accidentally.

Dictionaries

  • Dictionaries – Key-value pairs for fast lookups.
    student = {"name": "Ahmed", "age": 14, "grade": "A"}
    print(student["name"]) # Ahmed
    student["subject"] = "Computer Science" # Add new key
  • Dictionary Methods – .keys(), .values(), .items(), .get(), .update().
📋 List Ordered, mutable
📦 Tuple Ordered, immutable
📖 Dictionary Key-value pairs
🔢 Set Unique, unordered
Python Data Structures

Sets

  • Sets – Unordered collections of unique elements.
    numbers = {1, 2, 3, 3, 4, 4, 5}
    print(numbers) # {1, 2, 3, 4, 5} (duplicates removed)
    numbers.add(6)
    numbers.remove(3)
  • Set Operations – Union (|), intersection (&), difference (-).
Think About It

When would you use each data structure?

List: When you need an ordered collection that can change.
Tuple: When you need an ordered collection that won't change.
Dictionary: When you need to look up values by key.
Set: When you need unique values and don't care about order.

Choosing the right data structure makes your code better!

Activity

Write a Python program that:

1. Creates a list of 10 random numbers.
2. Uses a set to find the unique numbers.
3. Uses a dictionary to count the frequency of each number.
4. Uses a tuple to store a student's name, age, and grade.

Print the results of each data structure.

Reflect

Allah has created the universe with order and organization. The Qur'an says: "And everything with Him is by measure." (13:8)

Data structures help us organize information in a logical way. This reflects the wisdom and order in Allah's creation. When we organize data well, we are following this divine principle.

Key Takeaway

Data structures organize data efficiently. Lists are ordered and mutable. Tuples are ordered and immutable. Dictionaries store key-value pairs. Sets store unique, unordered elements. Choosing the right data structure is key to writing efficient code.

Topic 3 Algorithms: Sorting & Searching

What are Algorithms?

An algorithm is a step-by-step procedure for solving a problem. In computer science, we study algorithms to make our programs faster and more efficient.

Sorting Algorithms

  • Bubble Sort – Repeatedly swaps adjacent elements if they are in the wrong order.
    def bubble_sort(arr):
        n = len(arr)
        for i in range(n):
            for j in range(0, n-i-1):
                if arr[j] > arr[j+1]:
                    arr[j], arr[j+1] = arr[j+1], arr[j]
        return arr
  • Selection Sort – Finds the minimum element and places it at the beginning.
    def selection_sort(arr):
        n = len(arr)
        for i in range(n):
            min_idx = i
            for j in range(i+1, n):
                if arr[j] < arr[min_idx]:
                    min_idx = j
            arr[i], arr[min_idx] = arr[min_idx], arr[i]
        return arr
  • Insertion Sort – Builds the sorted array one element at a time.
    def insertion_sort(arr):
        for i in range(1, len(arr)):
            key = arr[i]
            j = i-1
            while j >= 0 and key < arr[j]:
                arr[j+1] = arr[j]
                j -= 1
            arr[j+1] = key
        return arr
Fun Fact!

Bubble sort is one of the simplest sorting algorithms, but it's also one of the slowest. For large datasets, faster algorithms like Quick Sort are used.

Searching Algorithms

  • Linear Search – Checks each element one by one.
    def linear_search(arr, target):
        for i in range(len(arr)):
            if arr[i] == target:
                return i
        return -1 # Not found
  • Binary Search – Efficiently finds an element in a sorted array by repeatedly dividing in half.
    def binary_search(arr, target):
        left, right = 0, len(arr)-1
        while left <= right:
            mid = (left + right) // 2
            if arr[mid] == target:
                return mid
            elif arr[mid] < target:
                left = mid + 1
            else:
                right = mid - 1
        return -1 # Not found
📊 Bubble Sort O(n²)
📊 Selection Sort O(n²)
📊 Insertion Sort O(n²)
🔍 Linear Search O(n)
🔍 Binary Search O(log n)
Common Algorithms
Try This!

Compare the speed of different algorithms:

1. Create a list of 1000 random numbers.
2. Sort it using bubble sort, selection sort, and insertion sort.
3. Time each algorithm using Python's time module.

Which is fastest? Why?

Activity

Implement and test these algorithms:

1. Write bubble sort, selection sort, and insertion sort functions.
2. Test them with lists of different sizes (10, 100, 1000).
3. Count the number of comparisons each algorithm makes.
4. Write a report comparing the three algorithms.

What do you notice about the time complexity?

Reflect

Algorithms teach us about efficiency and problem-solving. The Qur'an says: "And We have made everything with measure." (54:49)

Just as we optimize algorithms to run faster, we should optimize our lives by using our time and resources wisely. Efficiency is a virtue.

Key Takeaway

Algorithms are step-by-step procedures for solving problems. Sorting algorithms include bubble sort, selection sort, and insertion sort. Searching algorithms include linear search and binary search. Binary search is much faster than linear search for sorted data. Understanding algorithms helps you write efficient programs.

Topic 4 Computer Architecture

How Does a Computer Work Internally?

In previous classes, you learned about the components of a computer. Now let's go deeper into computer architecture – how the components are designed and how they work together.

CPU Architecture

  • Fetch-Decode-Execute Cycle – The basic operation of a CPU:
    1. Fetch – Get the next instruction from memory.
    2. Decode – Figure out what the instruction means.
    3. Execute – Perform the instruction.
  • Registers – Small, very fast memory locations inside the CPU. Examples: Program Counter, Instruction Register, Accumulator.
  • ALU (Arithmetic Logic Unit) – Performs arithmetic and logical operations.
  • Control Unit – Directs the operation of the CPU.
Fun Fact!

The first CPU, the Intel 4004, was released in 1971 and had 2,300 transistors. Modern CPUs have billions of transistors!

Memory Hierarchy

  • Cache Memory – Very fast memory that stores frequently accessed data. Level 1 (L1) is fastest and smallest; L3 is slower and larger.
  • RAM – Main memory, larger but slower than cache. Volatile – loses data when power is off.
  • Storage – Hard drives and SSDs, large but slower. Non-volatile – retains data when power is off.
⚡ CPU Fetch-Decode-Execute
💾 Cache Fastest memory
🧠 RAM Main memory
💽 Storage Permanent storage
Speed: Cache > RAM > Storage
The Memory Hierarchy

Input/Output Systems

  • Interrupts – Signals that tell the CPU to pause and handle an event. Example: When you press a key, an interrupt is triggered.
  • DMA (Direct Memory Access) – Allows devices to access memory directly without the CPU. Used by hard drives and network cards.
  • Bus Systems – The pathways that carry data between components. Example: System bus, data bus, address bus.
Think About It

Why does your computer slow down when you open too many programs?

When you open many programs, they compete for limited resources:
• CPU time – The CPU has to switch between programs.
• RAM – Your computer may run out of RAM and use slower storage.
• Cache – The cache can't hold all the data, so it's less effective.

Understanding architecture helps you optimize performance!

Activity

Research the architecture of your computer:

1. What CPU does your computer have?
2. How many cores does it have?
3. How much RAM do you have?
4. What type of storage (HDD or SSD)?
5. How fast is your CPU (GHz)?

Write a short report about your computer's architecture.

Reflect

The complexity of computer architecture is a sign of Allah's creation. The Qur'an says: "And We have certainly created man in the best of forms." (95:4)

Just as computers have complex systems that work together, our bodies have systems (nervous, circulatory, etc.) that work together perfectly. This is a sign of Allah's power and wisdom.

Key Takeaway

Computer architecture describes how components are designed and work together. The CPU uses the fetch-decode-execute cycle. Cache is fast memory for frequently used data. RAM is the main memory. Storage is permanent memory. Interrupts and DMA manage input/output operations. Understanding architecture helps you optimize performance.

Topic 5 Software Engineering

What is Software Engineering?

Software engineering is the systematic approach to developing, maintaining, and managing software. It's not just about writing code – it's about planning, designing, testing, and managing software projects.

The Software Development Life Cycle (SDLC)

  • 1. Planning – Define what the software needs to do and how it will be built. Includes: feasibility study, requirements gathering.
  • 2. Analysis – Understand and document the user requirements. What does the user need?
  • 3. Design – Create the architecture and detailed design of the software. How will the software work?
  • 4. Implementation – Write the code (this is what you've been learning!). Programming, coding.
  • 5. Testing – Find and fix bugs to ensure quality. Unit testing, integration testing, system testing.
  • 6. Deployment – Release the software for users. Installation, user training.
  • 7. Maintenance – Fix issues and update the software over time. Bug fixes, new features.
📋 Planning 📊 Analysis ✏️ Design 💻 Implementation 🧪 Testing 🚀 Deployment 🔧 Maintenance
Software Development Life Cycle (SDLC)
Fun Fact!

The "Waterfall" model was the first formal SDLC model, introduced in 1970. Today, Agile methods are more popular because they allow for faster, more flexible development.

Agile Development

  • Agile – A flexible, iterative approach to software development. Instead of one big release, software is released in small increments.
  • Scrum – An Agile framework with sprints (2-4 week cycles), daily stand-ups, and retrospectives.
  • Agile Values:
    • Individuals and interactions over processes and tools.
    • Working software over comprehensive documentation.
    • Customer collaboration over contract negotiation.
    • Responding to change over following a plan.
Story: The Agile Team

A team of students was building a school management system using Agile. Instead of waiting until the end to see the final product, they:

• Planned in 2-week sprints – They decided what to build each sprint.
• Had daily stand-ups – 5-minute meetings to share progress.
• Showed working software – They demonstrated their progress every sprint.
• Adapted to feedback – The teachers gave feedback, and they changed the plan.

By the end of the semester, they had a working system!

The lesson: Agile methods help teams deliver value quickly and respond to change. It's a more effective way to build software.

Software Testing

  • Unit Testing – Testing individual components of code.
    def test_add():
        assert add(2, 3) == 5
        assert add(-1, 1) == 0
  • Integration Testing – Testing how components work together.
  • User Acceptance Testing (UAT) – Testing with actual users to ensure it meets their needs.
Activity

Plan a software project using the SDLC:

Choose a project: A library management system, a school app, or a to-do list app.

Write a plan covering:
1. Requirements (what the software should do).
2. Design (how it will work).
3. Implementation plan (what you will build first).
4. Testing plan (how you will test it).
5. Deployment plan (how you will release it).

Share your plan with your class.

Reflect

Allah is the perfect planner. The Qur'an says: "And He has made everything with measure." (54:49)

Software engineering teaches us to plan, organize, and execute projects effectively. These are skills that help us in all areas of life. When we plan well, we are following a divine principle.

Key Takeaway

Software engineering is the systematic development of software. The SDLC includes planning, analysis, design, implementation, testing, deployment, and maintenance. Agile is a flexible, iterative approach. Testing ensures quality and reliability. Software engineering is a disciplined approach to building software that meets users' needs.

Topic 6 Islamic Ethics in Technology

Technology and Islamic Ethics

As technology becomes more powerful, it's essential to consider the ethical implications of how we build and use it. Islam provides a comprehensive framework for ethical technology use.

Key Ethical Principles

  • 🤲 Tawhid (Oneness of Allah) – All technology should be used for purposes that please Allah and benefit humanity. "And We have not created the heavens and the earth and everything between them in play." (21:16)
  • ⚖️ Justice ('Adl) – Technology should be fair and accessible to all. "And act justly. Indeed, Allah loves those who act justly." (49:9)
  • 🧠 Intellectual Property – Respecting the work of others is essential. Plagiarism and software piracy are forbidden.
  • 🔒 Privacy – Protecting people's data is a trust. "And do not spy..." (49:12)
  • 🤝 Beneficence – Use technology to help and benefit others. "The best of people are those who are most beneficial to others." (Hadith)
🤲 Tawhid ⚖️ Justice 🧠 IP 🔒 Privacy 🤝 Beneficence
Islamic Ethics for Technology
Fun Fact!

The concept of intellectual property and giving credit to authors has roots in Islamic tradition. Scholars always cited their sources and acknowledged those who came before them.

Contemporary Issues

  • AI and Bias – AI systems can reflect and amplify human biases. As Muslims, we must ensure AI is fair and just.
  • Social Media Ethics – Using social media responsibly, avoiding gossip, slander, and spreading false information. "And do not spy nor backbite one another." (49:12)
  • Digital Divide – Ensuring access to technology for all people, regardless of their background. Technology should serve everyone, not just the privileged.
  • Environmental Impact – The technology industry has a significant environmental footprint. "And do not cause corruption upon the earth..." (7:56)
Story: The Ethical Developer

A developer named Ahmed was asked to build an app that collected user data for targeted advertising. He realized that the app would collect more data than necessary and share it without clear consent.

He spoke to his manager and said: "I can build this app, but I don't feel comfortable with how we're handling user data. We should be transparent about what we collect and give users a real choice."

The manager respected Ahmed's honesty. They revised the app to be more privacy-focused. The app was still successful, and users appreciated the transparency.

The lesson: Ethical developers speak up when they see something wrong. They build technology that is honest, fair, and respectful of users. This is what it means to be a Muslim technologist.

Activity

Write a code of ethics for a technology company:

Include:
1. How the company will protect user data.
2. How the company will ensure fairness in AI and algorithms.
3. How the company will give back to the community.
4. How the company will reduce its environmental impact.

Share your code of ethics with your class.

Reflect

Allah has given us knowledge and power to use technology. The Qur'an says: "And We have certainly honored the children of Adam..." (17:70)

With great power comes great responsibility. As Muslims, we must ensure that technology is used for good, justice, and the benefit of all humanity. Let us be leaders in ethical technology.

Key Takeaway

Islamic ethics guide the use of technology. Key principles include Tawhid, justice, respecting intellectual property, protecting privacy, and beneficence. Contemporary issues include AI bias, social media ethics, the digital divide, and environmental impact. As Muslims, we must be responsible and ethical in how we develop and use technology.

Class 9 Computer Science – Complete!

You've explored advanced Python programming, data structures, algorithms, computer architecture, software engineering, and Islamic ethics in technology. You are now equipped with foundational knowledge for advanced computer science studies and a career in technology! May Allah bless your learning and help you use technology for good!

Topic 1 Topic 2 Topic 3 Topic 4 Topic 5 Topic 6