Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Introduction

Welcome to the CBSE Grade 12 Computer Science textbook!

This book is designed specifically to cover the entire CBSE syllabus for Class XII (Subject Code - 083) for the academic year 2025-26.

Structure of the Book

The syllabus is divided into three main units:

  1. Computational Thinking and Programming - 2 (40 Marks): Deepens your understanding of Python, covering functions, exception handling, file handling (text, binary, CSV), and data structures like stacks.
  2. Computer Networks (10 Marks): Introduces the evolution of networking, communication terminologies, transmission media, network devices, topologies, and basic web services.
  3. Database Management (20 Marks): Covers database concepts, the relational data model, Structured Query Language (SQL), and how to connect your Python applications to an SQL database.

Competency-Based Learning

A core focus of this book is to prepare you for competency-based questions, which represent a significant portion of the CBSE board exams.

At the end of each unit, you will find a dedicated section filled with competency-based questions modeled closely on the previous five years of CBSE question papers and official sample papers. These questions will test your analytical skills, logical reasoning, and ability to apply theoretical and practical knowledge to solve real-world problems.

Let’s begin the journey into mastering Computer Science!

Copyright

© 2026 Abhishek Kumar. All rights reserved.

Website: abhishek-kumar.co.in

Contact: support@abhishek-kumar.co.in

No part of this publication may be reproduced, distributed, or transmitted in any form or by any means, including photocopying, recording, or other electronic or mechanical methods, without the prior written permission of the publisher, except in the case of brief quotations embodied in critical reviews and certain other noncommercial uses permitted by copyright law.

Chapter 1: Revision of Python Topics (Class XI)

Welcome to Unit 1! Before we dive into the new concepts of Class XII, it is essential to have a solid grasp of the foundational Python programming concepts you learned in Class XI.

This chapter provides a quick refresher on the core components of Python.

1.1 Python Basics

Python is a high-level, interpreted, interactive, and object-oriented scripting language. It uses indentation to define blocks of code instead of curly braces.

Variables and Data Types

A variable is a named location in memory used to store data. In Python, you do not need to explicitly declare the data type of a variable.

# Variables
age = 17          # Integer (int)
marks = 95.5      # Floating point (float)
name = "Alice"    # String (str)
is_student = True # Boolean (bool)

Core Data Types:

  • Numbers: Integers (int), Floating-point numbers (float), Complex numbers (complex).
  • Strings: (str) A sequence of characters enclosed in single or double quotes. They are immutable.
  • Lists: (list) An ordered, mutable collection of items enclosed in square brackets [].
  • Tuples: (tuple) An ordered, immutable collection of items enclosed in parentheses ().
  • Dictionaries: (dict) An unordered, mutable collection of key-value pairs enclosed in curly braces {}. Keys must be unique and immutable.
  • Boolean: (bool) Represents True or False.
  • None: represents the absence of a value.

Mutable vs. Immutable Types

  • Mutable (can be changed in place): Lists, Dictionaries, Sets.
  • Immutable (cannot be changed in place): Integers, Floats, Strings, Tuples, Booleans.

1.2 Operators and Expressions

Python supports various operators to perform operations on variables and values.

  • Arithmetic: + (addition), - (subtraction), * (multiplication), / (division - float), // (floor division), % (modulus/remainder), ** (exponentiation).
  • Relational (Comparison): == (equal), != (not equal), > (greater than), < (less than), >= (greater than or equal), <= (less than or equal). They return a boolean value.
  • Logical: and, or, not. Used to combine conditional statements.
  • Assignment: =, +=, -=, *=, /=, etc.
  • Identity: is, is not. Checks if two variables refer to the same object in memory.
  • Membership: in, not in. Checks if a sequence is present in an object.

1.3 Flow of Control

Control flow statements determine the order in which code executes.

Conditional Statements

Used for decision making.

score = 85

if score >= 90:
    print("Grade A")
elif score >= 80:
    print("Grade B")
else:
    print("Grade C")

Iterative Statements (Loops)

Used to repeat a block of code.

for Loop: Used to iterate over a sequence (list, tuple, dictionary, set, or string).

# Using range()
for i in range(1, 6): # Prints 1, 2, 3, 4, 5
    print(i)

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

while Loop: Executes a set of statements as long as a condition is true.

count = 0
while count < 3:
    print(count)
    count += 1

Jump Statements:

  • break: Stops the loop entirely.
  • continue: Stops the current iteration and continues with the next iteration.

1.4 Strings, Lists, Tuples, and Dictionaries (Quick Reference)

Strings (Immutable)

s = "Hello World"
print(len(s))       # Length: 11
print(s[0])         # Indexing: 'H'
print(s[0:5])       # Slicing: 'Hello'
print(s.upper())    # Methods: 'HELLO WORLD'
print(s.replace("World", "Python")) # 'Hello Python'

Lists (Mutable)

L = [10, 20, 30]
L.append(40)     # Adds 40 to the end [10, 20, 30, 40]
L.insert(1, 15)  # Inserts 15 at index 1 [10, 15, 20, 30, 40]
L.pop()          # Removes and returns the last element (40)
L.remove(20)     # Removes the first occurrence of 20

Tuples (Immutable)

T = (1, 2, 3)
# T[0] = 5 # Error! Tuples cannot be modified
print(T.count(2)) # Counts occurrences of 2

Dictionaries (Mutable, Key-Value Pairs)

D = {"name": "Bob", "age": 18}
print(D["name"])       # Access value by key: 'Bob'
D["marks"] = 90        # Add a new key-value pair
del D["age"]           # Delete a key-value pair

for key in D.keys():   # Iterate through keys
    print(key, D[key])

1.5 Introduction to Modules

A module is a file containing Python definitions and statements. You can use code from a module by importing it.

import math
print(math.sqrt(16)) # Prints 4.0

import random
print(random.randint(1, 6)) # Simulates rolling a die (1 to 6)

This brief revision covers the foundational tools you will need. In the next chapter, we will learn how to organize these tools into reusable blocks using Functions.

Chapter 2: Functions in Python

Functions are one of the most fundamental concepts in programming. They allow you to organize your code into manageable, reusable chunks.

2.1 What is a Function?

A function is a named block of code that performs a specific task. Instead of writing the same code repeatedly, you can define a function once and call it whenever you need that task to be performed.

Think of a function like a specialized tool in a toolbox. If you need to drive a nail, you grab a hammer. In programming, if you need to calculate an average, you call a function designed to do exactly that.

Advantages of using Functions:

  1. Reusability: Write once, use many times.
  2. Modularity: Breaks a large program into smaller, easily manageable pieces.
  3. Readability: Makes code easier to understand.
  4. Debugging: Easier to find and fix errors in isolated blocks of code.

2.2 Types of Functions

In Python, functions are generally categorized into three types:

  1. Built-in Functions: These are pre-defined functions built into Python that are always available for use (e.g., len(), print(), type(), input()).
  2. Functions Defined in Modules: These are functions that belong to specific modules (libraries) and must be imported before they can be used (e.g., math.sqrt(), random.randint()).
  3. User-Defined Functions: These are functions created by the programmer to perform specific tasks.

2.3 Creating User-Defined Functions

You define your own functions using the def keyword, followed by the function name, parentheses (), and a colon :. The block of code within the function must be indented.

Syntax:

def function_name(parameters):
    # Function body (statements)
    [return statement]

Example: A Simple Function

def say_hello():
    print("Hello, welcome to Python programming!")

# Calling the function
say_hello() 

2.4 Arguments and Parameters

Often, a function needs information to do its job. You pass this information to the function as arguments.

  • Parameters: The variables listed inside the parentheses in the function definition.
  • Arguments: The actual values passed to the function when it is called.
# 'name' is the parameter
def greet(name): 
    print("Hello, " + name + "!")

# "Alice" and "Bob" are arguments
greet("Alice") 
greet("Bob")

Types of Arguments

Python provides flexible ways to pass arguments to functions.

1. Positional Parameters (Required Arguments)

These are arguments passed to a function in the correct positional order. The number of arguments in the function call must exactly match the number of parameters defined.

def subtract(a, b):
    print(a - b)

subtract(10, 5) # Output: 5. 'a' gets 10, 'b' gets 5
subtract(5, 10) # Output: -5. Order matters!

2. Default Parameters

You can assign a default value to a parameter in the function definition. If an argument is missing during the function call, the default value is used.

Rule: Non-default arguments cannot follow default arguments.

def intro(name, msg="Good Morning"):
    print("Hello " + name + ", " + msg)

intro("Alice")                 # Output: Hello Alice, Good Morning
intro("Bob", "How are you?")   # Output: Hello Bob, How are you?

2.5 Returning Values from a Function

A function can send data back to the point where it was called using the return statement.

  • A function can return a single value.
  • A function can return multiple values (as a tuple).
  • If a function doesn’t have a return statement, it implicitly returns None.

Example: Returning a Single Value

def calculate_area(length, width):
    area = length * width
    return area

result = calculate_area(5, 4)
print("The area is:", result) # Output: The area is: 20

Example: Returning Multiple Values

def get_details():
    name = "John Doe"
    age = 30
    return name, age # Returns a tuple ('John Doe', 30)

user_name, user_age = get_details()
print(user_name, "is", user_age)

2.6 Scope of Variables (Global and Local)

The scope of a variable determines the portion of the program where you can access a particular identifier.

  1. Local Scope: Variables created inside a function belong to the local scope of that function. They can only be accessed within that specific function. Their lifetime ends when the function finishes execution.
  2. Global Scope: Variables created outside of any function (in the main program body) belong to the global scope. They can be read from anywhere within the file, including inside functions.

Example 1: Demonstrating Local Scope

def my_function():
    local_var = 10 # This variable only exists inside my_function
    print("Inside function:", local_var)

my_function()
# print(local_var) # ERROR! NameError: name 'local_var' is not defined

Example 2: Demonstrating Global Scope

global_var = 20 # Defined outside

def read_global():
    print("Inside function, reading global:", global_var)

read_global()
print("Outside function:", global_var)

The global Keyword If you need to modify a global variable from inside a function, you must use the global keyword. Otherwise, Python will simply create a new local variable with the same name.

count = 0 # Global variable

def increment():
    global count # Tell Python we want to use the global 'count'
    count += 1
    print("Count inside:", count)

increment()
print("Count outside:", count) # Output: 1

2.7 Flow of Execution

The flow of execution refers to the order in which statements are executed in a Python program.

  1. Execution always begins at the first statement of the script (often called the __main__ entry point).
  2. Statements are executed one at a time, in order, from top to bottom.
  3. Function Definitions (def blocks): When Python encounters a def statement, it simply “learns” the function (stores it in memory). It does not execute the code inside the function body at that time.
  4. Function Calls: The execution of the function body only occurs when the function is explicitly called.
  5. When a function is called, the flow jumps into the function body, executes it, and then returns to the point immediately following the function call in the main program.

Understanding how functions work, how to pass data to them, and how they return data is crucial for writing clean, structured, and professional Python code.

Chapter 3: Exception Handling

When writing programs, things don’t always go as planned. Unexpected situations can arise during the execution of a program, leading to errors. Python provides a robust mechanism called Exception Handling to deal with these situations gracefully.

3.1 What is an Exception?

An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions. When a Python script encounters a situation it cannot cope with, it “raises” an exception.

If the exception is not explicitly handled by the programmer, the program will abruptly terminate (crash) and display an error traceback.

Common Types of Errors

  1. Syntax Errors: Errors in the structure or grammar of the Python code (e.g., missing a colon : or incorrect indentation). The program won’t even run.
  2. Logical Errors: The program runs without crashing, but it produces incorrect results due to flawed logic.
  3. Runtime Errors (Exceptions): The statement is syntactically correct, but an error occurs during execution (e.g., trying to divide by zero, or trying to open a file that doesn’t exist). These are the errors we use exception handling for.

Examples of Built-in Exceptions:

  • ZeroDivisionError: Occurs when a number is divided by zero.
  • NameError: Occurs when a variable name is not found (used before being defined).
  • TypeError: Occurs when an operation or function is applied to an object of inappropriate type (e.g., adding a string to an integer).
  • ValueError: Occurs when a function receives an argument of the correct type but an inappropriate value.
  • IndexError: Occurs when trying to access an index that is out of range in a sequence (like a list or tuple).
  • FileNotFoundError: Occurs when trying to access a file that does not exist.

3.2 Introduction to Exception Handling

The core concept behind exception handling is to anticipate potential errors and write code that says, “Try to do this, but if an error occurs, do this instead of crashing.”

In Python, this is achieved using the try, except, and finally blocks.

The try-except Block

  • try block: This block contains the code that you think might raise an exception.
  • except block: This block contains the code that will execute only if an exception occurs in the corresponding try block.

Syntax:

try:
    # Code that may raise an exception
except ExceptionName:
    # Code to handle the specific exception

Example 1: Handling Division by Zero Without exception handling:

# If y is 0, this program crashes immediately.
x = 10
y = 0
result = x / y 
print(result)

With exception handling:

try:
    x = 10
    y = 0
    result = x / y
    print("Result:", result)
except ZeroDivisionError:
    print("Error: Cannot divide by zero! Please provide a non-zero denominator.")

print("Program execution continues normally...")

Example 2: Handling Invalid Input (ValueError) If you ask a user for an integer, but they type “hello”, it raises a ValueError.

try:
    age = int(input("Enter your age: "))
    print("You are", age, "years old.")
except ValueError:
    print("Invalid input. Please enter a valid number.")

3.3 Handling Multiple Exceptions

A single try block can have multiple except blocks to handle different types of errors differently.

try:
    numerator = int(input("Enter numerator: "))
    denominator = int(input("Enter denominator: "))
    result = numerator / denominator
    print("Result:", result)

except ValueError:
    print("Error: Please enter integer numbers only.")
except ZeroDivisionError:
    print("Error: Denominator cannot be zero.")
except Exception as e:
    # This acts as a catch-all for any other unexpected errors
    print("An unexpected error occurred:", e)

(Note: While except Exception: catches almost everything, it’s generally best practice to catch specific, anticipated exceptions rather than using broad catch-alls.)


3.4 The finally Block

The finally block offers a place to put code that must be executed no matter what happens in the try and except blocks.

Whether an exception is raised or not, and whether an exception is handled or not, the code inside the finally block will always run. This is extremely useful for cleanup operations, such as closing files or releasing network/database connections.

Syntax:

try:
    # Code that may cause an exception
except SomeException:
    # Handle the exception
finally:
    # Code that will ALWAYS execute

Example:

file_obj = None
try:
    print("Attempting to open file...")
    # This will raise FileNotFoundError if 'data.txt' doesn't exist
    file_obj = open("data.txt", "r") 
    content = file_obj.read()
    print("File read successfully.")

except FileNotFoundError:
    print("Error: The file 'data.txt' was not found.")

finally:
    print("Executing 'finally' block.")
    # Always attempt to clean up
    if file_obj:
        file_obj.close()
        print("File closed.")

Summary of the Flow:

  1. The try block is executed.
  2. If no exception occurs, the except block is skipped, the finally block executes, and execution continues.
  3. If an exception occurs, the rest of the try block is skipped. If the exception type matches the except block, the except block is executed. Then, the finally block executes.
  4. If an exception occurs but is not handled by any except block, the finally block is still executed. After that, the program halts with a traceback error.

Exception handling allows you to write robust, professional programs that handle errors gracefully, providing a better experience for the user and preventing catastrophic failures.

Chapter 4: File Handling in Python

So far, the programs we have written store their data in variables in the computer’s primary memory (RAM). However, data in RAM is volatile—it disappears when the program ends or the computer shuts down.

To store data permanently, we must save it to a file on a secondary storage device (like a hard drive or SSD). The process of working with files (reading, writing, and manipulating them) is called File Handling.

4.1 Types of Files

Python primarily deals with two main types of files:

  1. Text Files:
    • Store data in ASCII or Unicode formats (plain text).
    • Human-readable.
    • Each line ends with an End-of-Line (EOL) character (usually \n in Python).
    • Examples: .txt, .py, .html, .xml.
  2. Binary Files:
    • Store data in the exact same format as it is held in memory (0s and 1s).
    • Not human-readable (looks like gibberish if opened in a text editor).
    • Faster and more efficient for storing complex data structures (like objects, images, audio, etc.).
    • Examples: .dat, .jpg, .mp3.

We will also cover CSV (Comma Separated Values) files, which are a specific type of text file used to store tabular data.


4.2 Absolute and Relative Paths

To access a file, the Python interpreter needs to know where it is located natively on your computer’s filesystem.

  • Absolute Path: The complete path from the root directory to the file (e.g., C:\Users\Student\Documents\data.txt or /home/user/data.txt).
  • Relative Path: The path to the file relative to the current working directory (the folder where your Python script is running). If script.py and data.txt are in the same folder, the relative path is just data.txt.

4.3 Text File Operations

4.3.1 Opening and Closing a Text File

You must open a file before reading or writing to it. The open() function returns a file object which you use to interact with the file.

# Syntax: file_object = open(file_name, access_mode)

Common Text File Open Modes:

  • 'r': Read (default). Opens for reading. Errors if the file doesn’t exist.
  • 'w': Write. Opens for writing. Creates a new file or overwrites an existing file completely.
  • 'a': Append. Opens for appending. Adds new data to the end of the file. Creates a new file if it doesn’t exist.
  • 'r+': Read & Write. Opens for reading and writing. The file pointer is at the beginning.
  • 'w+': Write & Read. Opens for writing and reading. Overwrites if exists, creates if not.
  • 'a+': Append & Read. Opens for appending and reading. The file pointer is at the end.

Always remember to close a file after you are done! This saves changes and frees up system resources.

file_obj = open("story.txt", "r") 
# ... perform operations ...
file_obj.close() 

Using the with statement (Recommended Approach): The with statement automatically manages closing the file, even if exceptions occur. You don’t need a close() statement!

with open("story.txt", "w") as f:
    f.write("Chapter 1: The Beginning")
# 'f' is automatically closed here

4.3.2 Writing to a Text File

  • write(string): Writes a specified string to the file.
  • writelines(list_of_strings): Writes a list of strings to the file. (You must add \n manually if you want them on separate lines).
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]

with open("output.txt", "w") as file:
    file.write("This is a single line.\n")
    file.writelines(lines)

4.3.3 Reading from a Text File

  • read([size]): Reads and returns the entire file contents as a single string. If size is specified, it reads at most size bytes (characters).
  • readline(): Reads and returns exactly one line, including the newline character \n.
  • readlines(): Reads all lines and returns them as a list of strings, where each string is a line.
with open("output.txt", "r") as file:
    content = file.read()
    print("Full Content:\n", content)

with open("output.txt", "r") as file:
    line1 = file.readline()
    print("First Line:", line1)

with open("output.txt", "r") as file:
    line_list = file.readlines()
    print("List of Lines:", line_list)

4.3.4 The seek() and tell() Methods

Python maintains a file pointer (like a cursor) that indicates the current position within the file.

  • file.tell(): Returns the current byte location of the file pointer.
  • file.seek(offset, from_what): Moves the file pointer to a new location.
    • offset: Number of bytes to move.
    • from_what: Reference point:
      • 0: Beginning of the file (default).
      • 1: Current position (only works in binary mode!).
      • 2: End of the file (only works in binary mode!).

4.4 Binary File Operations

Binary files store data exactly as it is represented in memory. To work with complex Python objects (like dictionaries or lists) in binary files, we use the pickle module. The process of converting objects to a byte stream is called pickling (or serialization), and converting them back is unpickling (deserialization).

File modes for binary: rb, wb, ab, rb+, wb+, ab+. (Notice the b appended to the text modes).

4.4.1 Pickling (Writing to a Binary File)

Use the pickle.dump(object, file_object) method.

import pickle

student_record = {"Roll": 1, "Name": "Amit", "Marks": 85}

with open("student.dat", "wb") as f:
    pickle.dump(student_record, f) # Serializes dictionary to binary file

4.4.2 Unpickling (Reading from a Binary File)

Use the pickle.load(file_object) method. It reconstructs the object.

import pickle

with open("student.dat", "rb") as f:
    # Deserializes the binary data back into a dictionary
    retrieved_data = pickle.load(f) 
    print(retrieved_data['Name']) # 'Amit'

4.5 CSV File Operations

CSV (Comma Separated Values) files are a simple, text-based format for storing tabular data (like spreadsheets or databases). Each line is a row, and values are separated by commas.

Python provides the built-in csv module to handle these files easily.

4.5.1 Writing to a CSV File

  • csv.writer(file_object): Creates a writer object.
  • writerow(list): Writes a single row.
  • writerows(list_of_lists): Writes multiple rows.
import csv

data = [
    ["ID", "Name", "Department"],
    [101, "Aarav", "IT"],
    [102, "Kavya", "HR"]
]

# We use newline='' to prevent blank lines between rows in Windows
with open("employees.csv", "w", newline='') as file:
    csv_writer = csv.writer(file)
    csv_writer.writerows(data)

4.5.2 Reading from a CSV File

  • csv.reader(file_object): Creates a reader object that you can iterate over.
import csv

with open("employees.csv", "r") as file:
    csv_reader = csv.reader(file)
    for row in csv_reader:
        print(row) # Each row is returned as a list of strings

Mastering file handling is crucial because almost every real-world application requires saving and loading persistent data!

Chapter 5: Data Structures - Stacks

A data structure is a specialized format for organizing, processing, retrieving and storing data. Python has built-in data structures like Lists, Tuples, and Dictionaries. In this chapter, we will learn how to implement an abstract data type called a Stack using Python lists.


5.1 Introduction to Stacks

A Stack is a linear data structure that follows the LIFO (Last In First Out) or FILO (First In Last Out) principle.

Imagine a stack of plates in a cafeteria. You can only comfortably add a new plate to the top of the stack, and you can only remove the plate from the top of the stack. The plate that was added last is the first one to be removed.

Real-world analogies:

  • A pile of books.
  • The “Undo” (Ctrl+Z) feature in a text editor (undoes the most recent action first).
  • Browser history (clicking the “Back” button returns you to the most recently visited page).
  • Function call stack in programming execution.

5.2 Core Stack Operations

A typical stack data structure supports the following fundamental operations:

  1. Push: Adding a new element to the top of the stack.
  2. Pop: Removing and returning the top element from the stack.
  3. Peek (or Top): Returning the top element of the stack without removing it.
  4. isEmpty: Checking whether the stack contains any elements.
  5. Size: Finding the number of elements currently in the stack.

Important Condition: Underflow

If you try to perform a Pop operation on an empty stack, it results in a condition known as Underflow. You must always check if the stack is empty before popping!

(Note: While some programming languages have a fixed-size stack which can lead to ‘Overflow’ if you try to push too many items, Python lists grow dynamically, so Overflow is rarely a concern unless the system runs entirely out of memory).


5.3 Implementing a Stack using Python Lists

Python does not have a built-in Stack class, but we can easily implement one using the versatile Python list. We design it so that the end of the list serves as the top of the stack.

  • Adding to the top (Push) is equivalent to list.append().
  • Removing from the top (Pop) is equivalent to list.pop().

Step-by-Step Implementation

Let’s build a programmatic stack handling system:

# Initialize an empty stack (represented by a list)
stack = []

# 1. Implementation of is_empty function
def is_empty(stk):
    if len(stk) == 0:
        return True
    else:
        return False

# 2. Implementation of Push operation (adding to the top)
def push(stk, item):
    stk.append(item)
    print(f"Pushed: {item}")

# 3. Implementation of Pop operation (removing from the top)
def pop(stk):
    if is_empty(stk):
        return "Underflow! Stack is empty."
    else:
        removed_item = stk.pop() # Removes and returns the last element
        return removed_item

# 4. Implementation of Peek operation (viewing the top element)
def peek(stk):
    if is_empty(stk):
        return "Stack is empty."
    else:
        top_index = len(stk) - 1 # The last index
        return stk[top_index]

# 5. Implementation of Display operation
def display(stk):
    if is_empty(stk):
        print("Stack is empty.")
    else:
        print("Current Stack Content:")
        # Displaying elements starting from the Top (the end of the list)
        top = len(stk) - 1
        for i in range(top, -1, -1):
            if i == top:
                print(f"{stk[i]} <-- Top")
            else:
                print(stk[i])

# 6. Implementation of Size operation
def size(stk):
    return len(stk)

Let’s Test It!

Let’s use the functions we just defined to simulate stack operations:

# Execution starts here
print("Is Stack empty?", is_empty(stack)) # Expected: True

print("--- Pushing Elements ---")
push(stack, 10)
push(stack, 20)
push(stack, 30)

print("\n--- Current Status ---")
display(stack)
# Output should look like:
# 30 <-- Top
# 20
# 10

print("Stack size:", size(stack)) # Expected: 3

print("Peek Top Element:", peek(stack)) # Expected: 30

print("\n--- Popping an Element ---")
popped_value = pop(stack)
print(f"Popped value: {popped_value}") # Expected: 30

print("\n--- Final Status ---")
display(stack)
# Output should look like:
# 20 <-- Top
# 10

By understanding Stacks, you are taking your first step into understanding complex software architectures, such as how programming languages manage function memory and evaluate expressions!

Unit 1: Competency-Based Questions

In accordance with the latest CBSE guidelines, a significant portion of your exam will consist of competency-based questions. These questions test your ability to apply the concepts of Python programming to real-world scenarios, debug code, and understand the logic behind algorithms.

This section provides a set of questions modeled on the previous 5 years of CBSE Question Papers and Official Sample Papers.


1. Output Based Questions (Tracing and Logic)

Question 1.1 What will be the output of the following Python code snippet? Explain the logic.

def changeList(L, n):
    for i in range(len(L)):
        if L[i] % n == 0:
            L[i] = L[i] // n
        else:
            L[i] = L[i] * n
    return L

myList = [10, 20, 30, 40, 50]
print(changeList(myList, 10))

Expected Answer: [1, 2, 3, 4, 5] Logic: The loop iterates through each element. Since every element in myList is divisible by n (which is 10), the if condition is always true. Thus, each element is replaced by its integer division by 10. List is mutable, so changes persist.

Question 1.2 Find and write the output of the following python code:

x = "Global"
def func1():
    x = "Enclosing"
    def func2():
        global x
        x = "Local"
    func2()
    print("Inner:", x)

func1()
print("Outer:", x)

Expected Answer:

Inner: Enclosing
Outer: Local

Logic:

  1. func1() starts. A local variable x (“Enclosing”) is created.
  2. func2() is called. Inside func2(), the global x statement binds the local name x to the global variable. It then sets the global x to “Local”.
  3. Inside func1(), print("Inner:", x) prints the local x belonging to func1, which is still “Enclosing”.
  4. Finally, the main program prints the global x, which was modified by func2() to “Local”.

2. Debugging and Error Spotting

Question 2.1 Raman has written the following code to find the sum of all digit characters in a string. However, his code has some errors. Rewrite the correct code and underline the corrections made.

def sumDigits(s)
    sum == 0
    for char in s:
        if char.isdigit():
            sum = sum + char
    Print("Sum is", sum)

sumDigits("Abc12d3")

Corrected Code:

def sumDigits(s):  # Correction: Added colon ':'
    sum = 0        # Correction: Assignment operator '=' instead of '=='
    for char in s:
        if char.isdigit():
            sum = sum + int(char) # Correction: Converted string character to int
    print("Sum is", sum) # Correction: 'print' must be all lowercase

sumDigits("Abc12d3")

3. Advanced File Handling Scenarios

Question 3.1 (Text Files) A text file named "STORY.txt" contains some text. Write a user-defined function count_words() in Python that counts and displays the number of words in the file that start with an uppercase vowel (A, E, I, O, U).

Solution Idea:

def count_words():
    count = 0
    vowels = ['A', 'E', 'I', 'O', 'U']
    try:
        with open("STORY.txt", "r") as file:
            data = file.read()
            words = data.split() # Splits text into a list of words
            for word in words:
                if word[0] in vowels: # Checks if the first letter is an uppercase vowel
                    count += 1
        print("Total words starting with uppercase vowel:", count)
    except FileNotFoundError:
        print("File not found.")

Question 3.2 (Binary Files - Case Study Based) A binary file "book.dat" has structure [BookNo, Book_Name, Author, Price]. Write a function Search_Author(Author_Name) in Python that searches and displays the details of all books written by the author whose name is passed as an argument. Assume the module pickle is already imported.

Solution Idea:

import pickle

def Search_Author(Author_Name):
    found = False
    try:
        with open("book.dat", "rb") as file:
            while True:
                try:
                    book_record = pickle.load(file)
                    # Check if the 3rd element (index 2) matches the Author_Name
                    if book_record[2] == Author_Name:
                        print(book_record)
                        found = True
                except EOFError:
                    break # Reached the End of File
        if not found:
            print(f"No books found by author {Author_Name}")
    except FileNotFoundError:
        print("File 'book.dat' not found.")

4. Stack Implementation (Application Based)

Question 4.1 A list Names contains names of students. Write a program to implement a stack allowing Push and Pop operations for the students whose name starts with the alphabet ‘A’. For example: If Names = ["Amit", "Rohit", "Akash", "Suman"], the stack should store “Amit” and “Akash”.

Solution Idea:

Names = ["Amit", "Rohit", "Akash", "Suman"]
stack_A = []

def Push_A(names_list, stk):
    for name in names_list:
        if name[0].upper() == 'A':
            stk.append(name)
            print(f"Pushed: {name}")

def Pop_A(stk):
    if len(stk) == 0:
        print("Underflow")
    else:
        removed = stk.pop()
        print(f"Popped: {removed}")

# Execution
Push_A(Names, stack_A)
Pop_A(stack_A)
Pop_A(stack_A)
Pop_A(stack_A) # Tests underflow

Study Tip

Practicing these types of questions regularly is the key to scoring well. Focus heavily on identifying what kind of data structure or file operation is best suited for the scenario presented in the exam.

Chapter 6: Evolution of Networking & Terminologies

A Computer Network is a collection of interconnected computers and devices that can communicate with each other and share resources like data, hardware (printers), and software.

6.1 Evolution of Networking

The Internet as we know it didn’t appear overnight. It evolved through several key research projects.

  1. ARPANET (Advanced Research Projects Agency Network):

    • Considered the grandfather of the Internet.
    • Created in 1969 by the US Department of Defense (ARPA).
    • Its primary goal was to connect computers at different universities and research institutions to allow scientists to share data and resources optimally, even over unreliable military lines.
  2. NSFNET (National Science Foundation Network):

    • Created in the mid-1980s by the US National Science Foundation.
    • It was a high-capacity network designed to connect supercomputer centers across the country. It was much faster than ARPANET and had broader access, but initially restricted to research use only.
  3. The INTERNET:

    • As ARPANET and NSFNET grew, eventually smaller regional and local networks were interconnected, forming a massive “network of networks.” This global interconnection of networks became known as the Internet.

6.2 Data Communication Terminologies

Data communication is the exchange of data between two devices via some form of transmission medium.

6.2.1 Core Components of Communication

  1. Sender: The device (computer, phone) sending the data.
  2. Receiver: The device receiving the data.
  3. Message: The information (text, audio, video) being communicated.
  4. Communication Media (Medium): The physical path (e.g., cables, radio waves) over which the message travels.
  5. Protocols: A set of strict rules governing the communication process (so the sender and receiver understand each other).

6.2.2 Measuring Network Capacity

  • Bandwidth: The difference between the highest and lowest frequencies that can be transmitted on a channel. In computer networks, bandwidth often loosely refers to the amount of data that can be transmitted in a fixed amount of time. It’s measured in Hertz (Hz).
  • Data Transfer Rate (DTR): The actual speed at which data is transferred over a network. Common units include:
    • bps (bits per second)
    • Kbps (Kilobits per second)
    • Mbps (Megabits per second)
    • Gbps (Gigabits per second)

6.2.3 IP Address

Every device connected to an IP network (like the Internet) is assigned a unique numerical label called an Internet Protocol (IP) Address. It serves two principal functions: host identification and location addressing.

(Example: 192.168.1.1 in IPv4). A computer’s real physical address baked into its network card is called the MAC address, which never changes, unlike an IP address.

6.2.4 Switching Techniques

When data travels across a complex network, it must be routed efficiently from the source to the destination. There are two primary techniques:

  1. Circuit Switching:

    • A dedicated physical path (circuit) is established between the sender and receiver before data transmission begins.
    • The path remains dedicated to that connection until communication ends.
    • Analogy: Making a traditional landline telephone call.
  2. Packet Switching:

    • No dedicated path is established.
    • The message is divided into small chunks called packets.
    • Each packet carries the source and destination addresses.
    • Packets are routed independently through the network. They may take different paths and arrive out of order. The receiving computer reassembles them.
    • Analogy: Sending a letter via the postal service. This is how the modern Internet works.

Chapter 7: Transmission Media & Devices

For computers to communicate, they must be physically or wirelessly connected.

7.1 Transmission Media (Channels)

Transmission media are the pathways that carry data signals from one computer to another. They are broadly divided into two categories.

7.1.1 Wired Communication Media (Guided Media)

Data travels through solid physical conductors.

  1. Twisted Pair Cable:
    • Consists of pairs of insulated copper wires twisted together. Twisting reduces electromagnetic interference (noise).
    • Common in older telephone systems and standard local networks (Ethernet).
    • Pros: Inexpensive, easy to install.
    • Cons: Susceptible to noise, lower bandwidth, short range.
  2. Coaxial Cable:
    • Has an inner copper core surrounded by an insulating layer, covered by a braided metal shield, and an outer plastic jacket.
    • Often used for cable television lines.
    • Pros: Better shielding than twisted pair, higher bandwidth, longer range.
    • Cons: Thicker, less flexible, slightly more expensive.
  3. Fiber-Optic Cable:
    • Made of thin strands of glass or plastic.
    • Uses pulses of light to transmit data instead of electrical signals.
    • Pros: Extremely high bandwidth, very fast, immune to electromagnetic interference, very secure, transmits over very long distances.
    • Cons: Very expensive, fragile, difficult to install and splice.

7.1.2 Wireless Media (Unguided Media)

Data travels through the air or space using electromagnetic waves.

  1. Radio Waves:
    • Used for AM/FM radio, television, and mobile phones.
    • Omnidirectional (travel in all directions). Can penetrate solid objects (walls).
  2. Microwaves:
    • Used for point-to-point communication (like between tall antennas) and satellite communication.
    • They require line-of-sight (antennas must see each other without obstacles). Cannot easily penetrate solid objects.
  3. Infrared Waves:
    • Used for short-range communication.
    • Cannot penetrate solid objects (e.g., a TV remote control sending signals to a TV).

7.2 Network Devices

Network devices are physical hardware components used to connect computers together and regulate traffic.

  1. Modem (Modulator-Demodulator): Converts digital signals from a computer into analog signals to travel over telephone lines, and vice versa. It literally connects your home to your Internet Service Provider (ISP).
  2. Ethernet Card (Network Interface Card - NIC): A hardware component installed in a computer that allows it to connect to a network. It provides the physical connection port.
  3. RJ45 (Registered Jack 45): This is the physical plastic connector (the plug) at the end of an Ethernet twisted-pair cable.
  4. Repeater: An electronic device that receives a weak signal, cleans it, amplifies it, and retransmits it so the data can travel longer distances without degradation.
  5. Hub: A simple device that connects multiple computers. It operates via broadcasting: when it receives an incoming data packet, it blindly sends it out to all other connected ports. It is considered “dumb” and creates a lot of unnecessary network traffic.
  6. Switch: A much “smarter” alternative to a hub. A switch connects devices, but it learns the MAC addresses of connected devices. When it receives a packet, it sends it only to the specific intended destination port, reducing network congestion significantly.
  7. Router: Operates at a higher level than switches. Routers connect completely different networks together (like connecting your home network to the global Internet). They read IP addresses and determine the best path (route) for packets to travel to reach their final destination.
  8. Gateway: A device (or software) that acts as a bridge between two networks that use completely different protocols. It translates the data so the two incompatible networks can communicate.
  9. Wi-Fi Card: Similar to an Ethernet card, but it contains a radio antenna to allow a computer to connect to a network wirelessly.

Chapter 8: Topologies, Protocols & Web Services

8.1 Network Types

Depending on their geographical span, networks can be grouped into:

  1. PAN (Personal Area Network): Covers a very small area (up to a few meters). Usually connects personal devices like Bluetooth headphones to a smartphone, or a wireless mouse to a computer.
  2. LAN (Local Area Network): Spans a single building or a small geographical area, such as a school campus, office, or home. Very fast and privately owned.
  3. MAN (Metropolitan Area Network): Connects two or more LANs across a larger area, typically a city or a large campus. For example, a cable TV network.
  4. WAN (Wide Area Network): Covers vast geographical regions, such as countries or even spanning the globe. The Internet is the world’s largest WAN. They often use public infrastructure (like telephone lines or satellites).

8.2 Network Topologies

Topology refers to the physical or logical layout of a network.

  1. Bus Topology:
    • All devices are connected to a single central cable, called the main trunk or backbone.
    • Pros: Easy to install, uses the least cable, cheap.
    • Cons: If the main cable breaks, the entire network fails. Hard to find where the fault is. Performance drops under heavy traffic.
  2. Star Topology:
    • All computers are connected to a central device, such as a Hub or Switch.
    • Pros: Most common and reliable. If one cable breaks, only that single computer goes down. Easy to add new devices. Easy to troubleshoot.
    • Cons: If the central Hub/Switch fails, the entire network crashes. Requires more cable than a Bus topology.
  3. Tree Topology (Hierarchical):
    • A combination of Bus and Star topologies. It relies on a central “root” node, with branches fanning out (like an inverted tree). Common in hierarchical large organizations.
    • Pros: Highly scalable. Easy to manage individual segments (branches).
    • Cons: If the main bus cable fails, the entire network drops. Complex to configure compared to Star.

8.3 Network Protocols

A protocol is a set of rules that computers use to communicate over a network.

  • HTTP (HyperText Transfer Protocol): Governs how web pages are transmitted over the Internet from web servers to your browser. Uses port 80.
  • HTTPS (HTTP Secure): A secure version of HTTP that encrypts data between the server and the client to protect sensitive information (like passwords or credit card numbers). Uses port 443.
  • FTP (File Transfer Protocol): Standard protocol used for transferring files between a client and a server on a computer network.
  • TCP/IP (Transmission Control Protocol / Internet Protocol): The foundational suite of protocols for the Internet.
    • TCP: Handles the reliable delivery of packets (breaking data down, verifying delivery, reassembling).
    • IP: Handles the physical addressing (routing) of packets so they reach the correct destination.
  • SMTP (Simple Mail Transfer Protocol): Used universally for sending email messages from an email client to an email server.
  • POP3 (Post Office Protocol version 3): Used for receiving/downloading emails from a server to a local client.
  • PPP (Point-to-Point Protocol): Used to establish a direct connection between two nodes (e.g., dial-up connection).
  • TELNET: An older protocol used for remote login into a computer over a network. Security is a concern because it sends data in plain text.
  • VoIP (Voice over Internet Protocol): Allows making voice calls using a broadband Internet connection instead of a regular analog phone line (e.g., WhatsApp calls, Skype).

8.4 Introduction to Web Services

The Internet provides the infrastructure, but various services run on top of it. One of them is the World Wide Web (WWW). The web consists of interconnected documents (web pages).

  1. HTML (HyperText Markup Language): The standard language used to create the structure and content of a web page.
  2. XML (eXtensible Markup Language): Used primarily to structure and transport data, rather than display it (like HTML). It allows users to define their own tags.
  3. URL (Uniform Resource Locator): The unique global address of a specific resource on the web (e.g., https://www.google.com/images/logo.png).
  4. Domain Name: A human-readable name that identifies an IP address on the Internet (e.g., google.com). This makes it easier for humans to remember addresses instead of memorizing numerical IP strings.
  5. Website: A collection of related web pages hosted under a single domain name.
  6. Web Browser: A software application (like Chrome, Firefox, Safari) used to access, retrieve, and display information from the World Wide Web.
  7. Web Server: A specialized computer or software program that stores website files and delivers them back to clients’ web browsers upon request over the Internet.
  8. Web Hosting: The business of providing storage space and access for websites on a web server so they are accessible on the Internet 24/7.

Unit 2: Competency-Based Questions

The Computer Networks unit heavily features case-study based questions. You will typically be given a scenario of an organization setting up a new campus network, and you will have to make engineering decisions based on the concepts learned in Chapters 6-8.


Case Study Type Questions

Question 2.1 Tech Vidya is an educational NGO that is setting up its new central campus in Delhi. They have 4 main buildings: Administrative Block (Admin), Computer Science Block (CS), Library, and Science Block (Science).

The distances between the buildings are:

  • Admin to CS: 50 meters
  • Admin to Library: 150 meters
  • CS to Library: 70 meters
  • CS to Science: 60 meters
  • Library to Science: 120 meters

The number of computers expected in each building:

  • Admin: 30
  • CS: 150
  • Library: 20
  • Science: 60

Based on the above specifications, answer the following questions:

a) Suggest the most appropriate building to house the server. Provide a reason for your choice. Answer: The Computer Science (CS) block. Reason: In network design, the server should ideally be placed in the building with the maximum number of computers (150 computers). This minimizes network traffic on the main backbone cables connecting other buildings, ensuring faster response times for the majority of users.

b) Suggest the cable layout design (topology) for connecting all the buildings to the server. Draw a simple diagram or describe it. Answer: A Star Topology spanning out from the Server in the CS block. Description: Connect Admin, Library, and Science blocks directly to the main switch/server located in the CS block.

Admin Block <----(50m)----> CS Block (SERVER)
                              |  \
                           (70m)  (60m)
                              |     \
                        Library      Science Block

c) Suggest the placement of the following network devices with justification:

  • (i) Repeater
  • (ii) Hub/Switch

Answer:

  • (i) Repeater: None of the distances between the buildings in the star layout exceed 100 meters (the typical limit for unshielded twisted pair cables without signal loss). However, if they were connecting Admin to Library directly (150m), a repeater would be needed after 100m. In the suggested star layout, no repeater is strictly necessary.
  • (ii) Hub/Switch: A switch should be placed in every building (Admin, CS, Library, Science) to connect all the individual computers within that building together.

d) Suggest the best wired medium to connect the buildings together to ensure high-speed data transfer. Answer: Fiber-Optic Cable. Reason: It provides very high bandwidth, immunity to electromagnetic interference, and is ideal for connecting building backbones over moderate distances.


2. Differentiate / Concept Based Questions

Question 2.2 Differentiate between HTTP and HTTPS protocols. Why is HTTPS preferred for banking websites? Answer: HTTP transmits data across the web in plain, readable text. HTTPS is its secure version; it uses encryption to scramble data during transmission. Banking websites prefer HTTPS to ensure that sensitive user data (like passwords, account numbers, PINs) cannot be intercepted and read by hackers while travelling across the network.

Question 2.3 Your friend is setting up a cyber cafe and wants all computers to share the same internet connection effectively without causing unnecessary broadcast traffic. Should he buy a Hub or a Switch? Give a reason. Answer: He should buy a Switch. Reason: A Hub is a dumb device that broadcasts incoming data to all its ports, leading to heavy network congestion and security risks. A Switch is intelligent; it learns the MAC addresses of connected devices and forwards data packets only to the specific port where the destination device is connected, thereby reducing traffic.

Question 2.4 Write down the expanded forms of:

  1. SMTP: Simple Mail Transfer Protocol
  2. VoIP: Voice over Internet Protocol
  3. ARPANET: Advanced Research Projects Agency Network
  4. MAC: Media Access Control

Chapter 9: Database Concepts & Relational Data Model

In the modern world, immense amounts of data are generated every second. Managing this data efficiently is crucial for any organization. This is where Databases come in.

9.1 Introduction to Database Concepts

A Database is an organized collection of structured data, typically stored electronically in a computer system. The software used to manage this database is called a Database Management System (DBMS) (e.g., MySQL, Oracle, PostgreSQL).

Why do we need Databases?

Before databases, data was often stored in traditional file systems (like text files or Excel sheets). This led to numerous problems:

  1. Data Redundancy: Duplication of the same data across multiple files wastes storage space.
  2. Data Inconsistency: If duplicate data exists, updating it in one place but forgetting another leads to mismatched, inconsistent data.
  3. Data Isolation: It’s difficult to retrieve and combine data spread across multiple disjointed files.
  4. Security Problems: File systems offer very limited user access controls.

A DBMS solves these problems by providing centralized control, reducing redundancy, ensuring consistency, and offering robust security mechanisms.


9.2 The Relational Data Model

There are different ways to structure a database. The most popular and widely used model is the Relational Data Model, proposed by E.F. Codd in 1970.

In the relational model, data is organized into two-dimensional tables called Relations.

Terminology Mapping

  • Relation: A Table. It stores data about a specific entity (e.g., a “Student” table, an “Employee” table).
  • Tuple: A Row (or Record) in a table. It represents a single, complete set of related data about one specific instance of the entity.
  • Attribute: A Column (or Field) in a table. It represents a specific property or characteristic of the entity.
  • Domain: The set of all possible permissible values for a specific attribute (e.g., the domain for “Gender” might be just ‘M’ or ‘F’).
  • Degree: The total number of attributes (columns) in a relation.
  • Cardinality: The total number of tuples (rows) in a relation.

Example Table: STUDENT

AdmNoNameAgeStream
S01Amit16Science
S02Neha17Commerce
S03Rahul16Arts
  • Degree of STUDENT: 4 (AdmNo, Name, Age, Stream)
  • Cardinality of STUDENT: 3 (Number of rows of data)

9.3 Keys in a Relational Database

Keys are attributes (or sets of attributes) that uniquely identify a row within a table or establish relationships between tables.

  1. Candidate Key: An attribute, or combination of attributes, that can uniquely identify a tuple in a relation. A table can have multiple Candidate Keys. (e.g., AdmNo, RollNo, AadharCardNumber).
  2. Primary Key: The specific Candidate Key chosen by the database designer to uniquely identify tuples in the relation. There can be only one Primary Key per table. Crucially, a Primary Key cannot contain NULL values. (e.g., we choose AdmNo as the Primary Key).
  3. Alternate Key(s): The Candidate Keys that were not chosen as the Primary Key. (If AdmNo is the Primary Key, then RollNo and AadharCardNumber become Alternate Keys).
  4. Foreign Key: A non-key attribute in one table whose values are drawn from the Primary Key of another table. It is used to establish and enforce a link (relationship) between the two tables.

Understanding these concepts is vital before we start writing queries to manipulate the database using SQL.

Chapter 10: Structured Query Language (SQL)

SQL (Structured Query Language) is the standard language for interacting with Relational Database Management Systems (RDBMS). It is used to create, modify, retrieve, and delete data within databases.

SQL commands are broadly categorized into two main groups:

  1. DDL (Data Definition Language): Used to define or alter the database structure (schema). These commands affect the tables themselves, not just the data inside them.
    • Examples: CREATE, ALTER, DROP
  2. DML (Data Manipulation Language): Used to manage and manipulate the actual data stored within the tables.
    • Examples: INSERT, UPDATE, DELETE, SELECT

10.1 DDL Commands: Creating & Modifying Tables

1. Data Types and Constraints

When creating a table, you must define the type of data each column will hold.

  • CHAR(n): Fixed-length character string. (e.g., CHAR(10) always uses 10 bytes, padding with spaces if needed).
  • VARCHAR(n): Variable-length character string. (Uses only the storage needed, up to a maximum of n characters. Better for storage efficiency).
  • INT / INTEGER: Whole numbers.
  • FLOAT: Decimal numbers.
  • DATE: Stores dates (format usually ‘YYYY-MM-DD’).

Constraints are rules applied to columns to enforce data integrity:

  • NOT NULL: Ensures that a column cannot have a NULL (empty) value.
  • UNIQUE: Ensures all values in a column are entirely distinct.
  • PRIMARY KEY: A combination of a NOT NULL and UNIQUE. Uniquely identifies each row in a table.

2. Basic Database Commands

  • CREATE DATABASE School; (Creates a new database)
  • USE School; (Selects the active database to work on)
  • SHOW DATABASES; (Lists all databases on the server)
  • DROP DATABASE School; (Deletes the entire database)

3. Creating a Table

CREATE TABLE Student (
    RollNo INT PRIMARY KEY,
    Name VARCHAR(30) NOT NULL,
    DOB DATE,
    Fee FLOAT
);

4. Viewing Table Structure

  • SHOW TABLES; (Lists all tables in the current database)
  • DESCRIBE Student; or DESC Student; (Shows the column definitions of the table)

5. Altering and Dropping Tables

-- Adding a completely new column
ALTER TABLE Student ADD City VARCHAR(20);

-- Modifying the data type of an existing column
ALTER TABLE Student MODIFY Name VARCHAR(50);

-- Removing a primary key (Note: there can be only one, so you don't name it)
ALTER TABLE Student DROP PRIMARY KEY;

-- Deleting the entire table
DROP TABLE Student;

10.2 DML Commands: Manipulating Data

1. Inserting Data

-- Inserting a single row (must match the column order exactly)
INSERT INTO Student VALUES (1, 'Ravi', '2005-04-12', 4500.50, 'Delhi');

-- Inserting explicitly into specific columns
INSERT INTO Student (RollNo, Name, Fee) VALUES (2, 'Priya', 5000.00);

2. The Powerful SELECT Command (Retrieval)

The SELECT command is the most frequently used SQL command. It allows you to query the database and retrieve specific data.

-- 1. Display all columns for every row
SELECT * FROM Student;

-- 2. Display specific columns
SELECT Name, City FROM Student;

-- 3. ALIASING (Renaming columns in the output for readability)
SELECT Name AS 'Student Name', Fee AS 'Monthly Fee' FROM Student;

-- 4. DISTINCT (Removing duplicate values from the result)
SELECT DISTINCT City FROM Student;

3. Filtering and Conditions (WHERE clause)

SELECT * FROM Student WHERE City = 'Delhi';
SELECT * FROM Student WHERE Fee > 4000;

-- Relational Operators: =, >, <, >=, <=, != or <>
-- Logical Operators: AND, OR, NOT

SELECT * FROM Student WHERE City = 'Delhi' AND Fee > 4500;

4. Special Operators (IN, BETWEEN, LIKE, IS NULL)

-- IN: Matches any value in a defined list
SELECT * FROM Student WHERE City IN ('Delhi', 'Mumbai', 'Pune');

-- BETWEEN: Specifies a range (inclusive)
SELECT * FROM Student WHERE Fee BETWEEN 3000 AND 5000;

-- LIKE: Pattern matching. 
-- '%' matches zero or more characters. '_' matches exactly ONE character.
SELECT * FROM Student WHERE Name LIKE 'A%';   -- Starts with 'A'
SELECT * FROM Student WHERE Name LIKE '%A';   -- Ends with 'A'
SELECT * FROM Student WHERE Name LIKE '_a%';  -- Second letter is 'a'

-- IS NULL: Checks for empty values. (Do NOT use '= NULL')
SELECT * FROM Student WHERE City IS NULL;
SELECT * FROM Student WHERE City IS NOT NULL;

5. Sorting Data (ORDER BY)

Sorts the result set. Default is Ascending (ASC). Use DESC for Descending.

SELECT * FROM Student ORDER BY Name ASC;
SELECT * FROM Student ORDER BY Fee DESC, Name ASC;

6. Updating Data (UPDATE)

Modifies existing records. Always use a WHERE clause! If you forget it, every single row in the table will be updated.

UPDATE Student SET Fee = Fee + 500 WHERE City = 'Delhi';

7. Deleting Data (DELETE)

Removes existing records. Again, always use a WHERE clause!

DELETE FROM Student WHERE RollNo = 2;
-- (If you wrote `DELETE FROM Student;`, the table would be emptied)

10.3 Advanced SQL Concepts

1. Aggregate Functions

These functions perform a calculation on a set of values and return a single value. They ignore NULL values (except COUNT(*)).

  • MAX(): Returns the largest value.
  • MIN(): Returns the smallest value.
  • AVG(): Returns the average value.
  • SUM(): Returns the total sum.
  • COUNT(): Returns the number of rows.
    • COUNT(*) counts all rows including NULLs.
    • COUNT(column_name) counts non-NULL values in that column.
SELECT MAX(Fee), MIN(Fee), AVG(Fee) FROM Student;
SELECT COUNT(*) FROM Student WHERE City = 'Delhi';

2. Grouping Data (GROUP BY and HAVING)

GROUP BY groups rows that have the same values into summary rows. It is almost always used in conjunction with aggregate functions.

-- Count how many students are in each city
SELECT City, COUNT(*) FROM Student GROUP BY City;

The HAVING clause was added to SQL because the WHERE keyword cannot be used with aggregate functions. HAVING applies conditions after the grouping has occurred.

-- Find cities that have MORE than 5 students
SELECT City, COUNT(*) FROM Student GROUP BY City HAVING COUNT(*) > 5;

3. Joins (Combining Tables)

A JOIN is used to combine rows from two or more tables based on a related column (usually Primary Key and Foreign Key) between them.

Suppose we have an Employee table and a Department table.

  • Cartesian Product (Cross Join): Combines every row in the first table with every row in the second table. Rarely useful on its own, produces massive output. (Used when no condition is specified).
  • Equi-Join: Joins tables based on an equality condition (=) between two columns.
    SELECT Employee.Name, Department.DeptName 
    FROM Employee, Department 
    WHERE Employee.DeptId = Department.DeptId;
    
  • Natural Join: A simpler way to write an Equi-Join. If the two tables share a column with the exact same name (like DeptId), a Natural Join automatically connects them based on that column, without needing a WHERE clause.
    SELECT * FROM Employee NATURAL JOIN Department;
    

Mastering SQL is the key to interacting effectively with databases of any size. Practices these queries extensively!

Chapter 11: Interfacing Python with SQL

While SQL is great for manipulating databases, users rarely interact with a database directly through an SQL command line. They interact through applications (like websites or desktop software). In this chapter, we will learn how to write a Python application that connects to an SQL database (like MySQL) to perform database operations programmatically.

11.1 The Architecture

To connect Python to MySQL, we need a connector module. The most common one used in the CBSE curriculum is mysql-connector-python.

Steps for Database Connectivity:

  1. Import the module: Bring the connector library into your Python script.
  2. Establish a connection: Open a connection to the MySQL server using credentials (host, user, password, database).
  3. Create a cursor instance: A cursor is an object that executes SQL queries and retrieves results.
  4. Execute a query: Pass your SQL command as a string to the cursor.
  5. Extract the results: If it was a SELECT query, fetch the data. If it was INSERT, UPDATE, or DELETE, commit() the changes.
  6. Clean up: Close the cursor and the connection.

11.2 Connecting to the Database

import mysql.connector

try:
    # 1. Establish connection
    mydb = mysql.connector.connect(
      host="localhost",
      user="yourusername",
      password="yourpassword",
      database="SchoolDB" # Assuming this database already exists
    )

    print("Connection established successfully!")

except mysql.connector.Error as err:
    print(f"Error connecting to database: {err}")

# Optional: Close connection immediately if just testing
# if mydb.is_connected():
#     mydb.close()

11.3 Executing Queries using the Cursor

1. Retrieving Data (SELECT Queries)

To fetch data, we use the cursor’s execute() method to run the query, and then fetch the results.

  • fetchone(): Returns the next row of the result set as a tuple. Returns None if no more rows are available.
  • fetchall(): Returns all remaining rows as a list of tuples.
  • rowcount: An attribute of the cursor that tells you how many rows were returned or affected by the last executed statement.
import mysql.connector

# ... (Connection code from above) ...
mydb = mysql.connector.connect(host="localhost", user="root", password="", database="SchoolDB")

# 2. Create the cursor
mycursor = mydb.cursor()

# 3. Execute the query
mycursor.execute("SELECT * FROM Student")

# 4. Extract results
results = mycursor.fetchall()

print("Total rows retrieved:", mycursor.rowcount)

for row in results:
    # row is a tuple containing the data for exactly one record
    print(f"RollNo: {row[0]}, Name: {row[1]}, City: {row[3]}")

# 5. Clean up
mycursor.close()
mydb.close()

2. Modifying Data (INSERT, UPDATE, DELETE)

When you make structural changes to the database or modify the data, you MUST call the commit() method on the connection object. If you don’t commit, the changes will be rolled back (undone) when the script ends!

import mysql.connector

mydb = mysql.connector.connect(host="localhost", user="root", password="", database="SchoolDB")
mycursor = mydb.cursor()

# Example: UPDATE operation
sql = "UPDATE Student SET Fee = Fee + 100 WHERE City = 'Delhi'"
mycursor.execute(sql)

# IMPORTANT: Commit the transaction to save changes
mydb.commit()

# Output the number of rows affected
print(mycursor.rowcount, "record(s) updated.")

mycursor.close()
mydb.close()

11.4 Parameterized Queries (Handling Dynamic Input)

Often, you don’t want to hardcode the SQL query. You want to insert data provided by a user (e.g., from an input() statement).

Warning: Never use simple string concatenation (+ or f-strings) to inject user input directly into an SQL query string. This makes your application vulnerable to SQL Injection attacks, where a malicious user could potentially delete your entire database.

Instead, use the %s format specifier. The connector will safely sanitize the inputs before executing the query.

import mysql.connector

mydb = mysql.connector.connect(host="localhost", user="root", password="", database="SchoolDB")
mycursor = mydb.cursor()

# Get data from the user
new_roll = int(input("Enter Roll No: "))
new_name = input("Enter Name: ")
new_city = input("Enter City: ")
new_fee = float(input("Enter Fee: "))

# The SQL query string uses %s placeholders
sql = "INSERT INTO Student (RollNo, Name, City, Fee) VALUES (%s, %s, %s, %s)"

# The data MUST be provided as a tuple
val = (new_roll, new_name, new_city, new_fee)

# Execute by passing both the query string and the data tuple
mycursor.execute(sql, val)

mydb.commit()
print(mycursor.rowcount, "record inserted.")

mycursor.close()
mydb.close()

(Note: While some older Python code uses the string .format() method to achieve parameterization, using the %s binding built into the MySQL connector is the safest and most standard practice).

By combining the logic of Python with the data management power of SQL, you can build incredibly robust, data-driven applications.

Unit 3: Competency-Based Questions

Database Management competency questions usually involve providing you with one or two tables populated with data and asking you to write SQL queries to achieve specific results, or to predict the output of given SQL queries. Another common format involves debugging incomplete Python-SQL connectivity code.


1. SQL Query Writing (Based on a Table)

Consider the following table named INVENTORY.

ItemCodeItemNameCategoryQtyPrice
A101MotherboardHardware504500.00
A102KeyboardHardware120850.50
C201AntivirusSoftware2001100.00
C202OfficeSuiteSoftware805000.00
A105MouseHardware150400.00

Question 3.1 Write SQL queries for the following: (a) To display the details of all items in the ‘Hardware’ category, sorted by their price in descending order. Answer: SELECT * FROM INVENTORY WHERE Category = 'Hardware' ORDER BY Price DESC;

(b) To count the number of items in each category. Answer: SELECT Category, COUNT(*) FROM INVENTORY GROUP BY Category;

(c) To display the ItemName and total value of stock (Qty * Price) for all items where the total value is greater than 100,000. Answer: SELECT ItemName, Qty * Price FROM INVENTORY WHERE (Qty * Price) > 100000;

(d) To increase the price of all ‘Software’ category items by 10%. Answer: UPDATE INVENTORY SET Price = Price * 1.10 WHERE Category = 'Software';


2. Output Prediction (SQL)

Question 3.2 Based on the INVENTORY table above, what will be the output of the following queries?

(a) SELECT MAX(Price), MIN(Price) FROM INVENTORY; Output:

MAX(Price)  | MIN(Price)
5000.00     | 400.00

(b) SELECT ItemName FROM INVENTORY WHERE ItemName LIKE '%board'; Output:

ItemName
Motherboard
Keyboard

3. Python-SQL Connectivity Debugging

Question 3.3 Sunita has written a Python script to insert a new record into a STUDENT table in a MySQL database. However, the code has missing segments labeled Statement-1 and Statement-2. Fill in the blanks to make the code functional.

import mysql.connector

mycon = mysql.connector.connect(host="localhost", user="root", password="pwd", database="school")
cursor = mycon.cursor()

query = "INSERT INTO STUDENT (RollNo, Name) VALUES (%s, %s)"
data = (10, 'Aman')

# Statement-1: Execute the query
____________________________________

# Statement-2: Save the changes permanently to the database
____________________________________

print("Record Inserted")
mycon.close()

Answer:

  • Statement-1: cursor.execute(query, data)
  • Statement-2: mycon.commit()

4. Database Theory & Keys

Question 3.4 An airline company maintains two tables: PASSENGER (PnrNo, Name, Age, FlightNo) and FLIGHT (FlightNo, Start, Destination, Airline).

(a) Identify the Primary Keys in both tables. Answer: Primary Key of PASSENGER is PnrNo. Primary Key of FLIGHT is FlightNo.

(b) Which attribute acts as a Foreign Key in the PASSENGER table? How does it help? Answer: FlightNo acts as the Foreign Key in the PASSENGER table. It helps establish a relationship between the two tables, allowing us to query and link a specific passenger to the details of the flight they are travelling on.

Appendix A: Suggested Practical List

This section details the practical programming assignments as suggested by the CBSE syllabus. These practicals are crucial for the Lab Test portion of the exam (12 marks) and the Report File (7 marks).

A.1 Python Programming (Minimum 15 Programs)

Your report file should include at least 15 Python programs covering the concepts learned in Class XI and XII.

Fundamental Logic & Strings/Lists

  1. Read a text file line by line and display each word separated by a #.
  2. Read a text file and display the number of vowels, consonants, uppercase, and lowercase characters in the file.
  3. Remove all the lines that contain the character ‘a’ in a file and write the remaining lines to another file.
  4. Write a random number generator that generates random numbers between 1 and 6 (simulating a dice roll).

Stacks

  1. Write a Python program to implement a stack using a list. (Include push, pop, display, and peek operations).

Binary File Handling

  1. Create a binary file with user records (Name and Roll Number). Search for a given roll number and display the name; if not found, display an appropriate message.
  2. Create a binary file with RollNo, Name, and Marks. Input a roll number from the user and update the marks for that student.

CSV File Handling

  1. Create a CSV file by entering user_id and password. Write a script to read and search for a password given a specific user_id.

(Add 7 more programs of similar complexity involving functions, complex lists/dictionaries manipulation, and basic algorithms like linear search or bubble sort to fulfill the minimum requirement of 15).


A.2 SQL Queries (Minimum 5 Sets)

Your report file should include basic to advanced SQL operations. For example, create a target database like “SchoolManagement” or “InventorySystem”.

Set 1: Basic DDL and DML

  1. Create a STUDENT table with attributes like RollNo, Name, Class, DOB, Gender, City, Marks.
  2. Insert at least 5 rows of sample data.
  3. Display all records from the table.

Set 2: Modifying Structure and Data 4. Use ALTER TABLE to add a new attribute (e.g., Email). 5. Use UPDATE to modify the marks of a specific student. 6. Use DELETE to remove a student’s record based on their RollNo.

Set 3: Filtering and Sorting 7. Display names of students belonging to a specific city. 8. Use ORDER BY to display data sorted by their marks in descending order.

Set 4: Aggregate Functions and Grouping 9. Find the minimum, maximum, and average marks of the class. 10. Use GROUP BY to find the count of male and female students separately.

Set 5: Specific Constraints 11. Write an ALTER TABLE query to drop an attribute. 12. Modify the table to change the data type of an existing attribute.


A.3 Python - SQL Connectivity (Minimum 4 Programs)

These programs demonstrate the integration of the database backend with the Python frontend application.

  1. Read: Write a Python program to connect to your SQL database, execute a SELECT * query on a table, and print all the fetched records in a formatted way.
  2. Insert: Write a Python program that takes user input (using input()) for a new record and inserts it into an SQL table using parameterized queries (%s).
  3. Update: Write a Python script that takes a specific ID (like RollNo or EmployeeID) from the user and a new value (like updated marks or salary), and executes an UPDATE query.
  4. Delete: Write a script to prompt the user for an ID and safely execute a DELETE command to remove that specific record from the SQL table. Ensure the script reports how many rows were affected.

Appendix B: Project Guidelines

The class project carries 8 marks in your practical examination. The objective is to apply the concepts learned in Classes XI and XII (specifically Python file handling and Python-SQL connectivity) to create a tangible, useful application that solves a real-world problem.


B.1 Project Requirements

  1. Group Size: The project should be done in groups of two to three students.
  2. Timeline: It should be started at least 6 months before the final submission deadline.
  3. Core Technology: The project must utilize either:
    • Python File Handling (Text, Binary, or CSV files) for data storage.
    • Python-SQL Connectivity, using a backend database like MySQL. (This is generally preferred and leads to more robust applications).
  4. Originality: Students must avoid plagiarism and copyright violations. Do not download pre-made projects from the internet. The code must be written by your group.

B.2 Finding a Problem to Solve

You are encouraged to look around your community, school, or local businesses for inspiration. A good project solves a specific problem.

Ideas from the CBSE Syllabus:

  • Business Invoice System: Visit a local shop. If they struggle with filing GST claims or generating bills manually, create a Python app that takes transaction data, calculates tax rates, groups items by category, and generates formatted invoices (saving them to CSV or a Database).
  • School Management Software: Create a system for the school library to track books issued and returned, or a system for managing student attendance and generating reports.
  • Accessibility Software: Build software designed to help disabled fellow students learn or interact with computers more easily.
  • Educational Games: Build a quiz game or an interactive learning application using pygame or standard Tkinter GUI, storing high scores in a database.

B.3 Project Phases & Documentation

Your final submission must include entirely functional code and a detailed Project Report File.

Phase 1: Analysis & Design

  • Problem Statement: Clearly define what the project does and who it is for.
  • Requirements specification: Hardware and software needed.
  • Database Design: If using SQL, draw an Entity-Relationship (ER) diagram or clearly list the tables, their attributes, primary keys, and relationships.

Phase 2: Development

  • Write modular code using functions.
  • Implement robust Exception Handling to ensure the program doesn’t crash on invalid user input.
  • Comment your code extensively so the examiner understands your logic.

Phase 3: Testing

  • Test all features with various inputs (valid and invalid) to ensure accuracy.

Phase 4: Creating the Report File The printed report file should typically contain:

  1. Title Page (Project Name, Group Members, School Info).
  2. Certificate of Authenticity (Signed by the teacher).
  3. Acknowledgement.
  4. Index/Table of Contents.
  5. Introduction / Problem Statement.
  6. Hardware & Software Requirements.
  7. Database Design (Schema).
  8. Source Code (Printed neatly).
  9. Output Screens (Screenshots proving the program works).
  10. Bibliography / References.

B.4 Tips for Success

  • Don’t overcomplicate it: A simple project that works flawlessly and is thoroughly understood by the group is much better than a heavily complex project that is broken or was copied from somewhere else.
  • Focus on the interface: Use basic menus in the console (e.g., “Press 1 to Add Book, Press 2 to Search…”) to make the application user-friendly. If you are ambitious, look into learning Tkinter for graphical interfaces, but standard console menus are perfectly acceptable.
  • Prepare for the Viva: During the practical exam, the external examiner will ask you questions about your code (the Viva Voce, worth 3 marks). You must be able to explain how your code works line by line.