Class 12 Computer Science Full Syllabus Notes PDF.pdf
Class 12 Computer Science Full Syllabus Notes PDF.pdf
4. Sta s cs Module:
import sta s cs
data = [1, 2, 3, 4, 5]
print(sta s cs.mean(data))
print(sta s cs.median(data))
print(sta s cs.mode(data))
NITIN PALIWAL
print(x)
6. Flow of Execution
func() # Output: 10
Functions follow a
b. Global Scope
top-down approach
and are executed only Defined outside any
function and
when called.
accessible throughout
Example:
the program.
def display():
Example:
print("Executing
x = 20
function!")
def show():
display()
print(x)
# Function call
show() # Output: 20
NITIN PALIWAL
c. Modifying Global
Variables
Example:
x = 10
def update():
global x
x += 5
update()
print(x) # Output: 15
Contact me:
MY WEBSITE: {HYPERLINK
"https://nitinpaliwal.odoo.com/"}
YOUTUBE: {HYPERLINK
"https://www.youtube.com/@NitinPaliwalOfficial
"}
INSTAGRAM: {HYPERLINK
"https://www.instagram.com/itz_paliwal_here/"}
TELEGRAM: {HYPERLINK
"https://t.me/nitinpaliwal_cs"}
Excep on Handling in Example:
Python try:
1. Introduc on to Excep on a = 10 / 0
Handling except ZeroDivisionError:
Excep on: An error that print("Cannot divide by
occurs during execu on, zero!")
disrup ng the program
b) Handling Mul ple
flow.
Excep ons
Common Excep ons:
Syntax:
ZeroDivisionError,
ValueError, IndexError, try:
KeyError, TypeError, etc. # Risky code
Handling Excep ons: except (Excep on1,
Python provides the try- Excep on2):
except-finally mechanism
# Handling code
to handle run me errors
gracefully. Example:
try:
2. Handling Excep ons Using num = int(input("Enter a
try-except-finally number: "))
a) try-except Block result = 10 / num
Syntax: except (ValueError,
ZeroDivisionError):
try:
print("Invalid input! Enter a
# Code that may raise an
non-zero number.")
excep on
c) Catching All Excep ons
except Excep onType:
Using except Excep on to
# Handling code
catch any error.
try: Executes if no excep on
x = int("abc") occurs.
Example:
except Excep on as e:
try:
print("Error occurred:", e)
d) finally Block num = int(input("Enter a
number: "))
Ensures execu on
regardless of excep ons. result = 10 / num
except ZeroDivisionError:
Syntax:
print("Cannot divide by
try:
zero!")
# Risky code
else:
except:
print("Result:", result)
# Handling code
finally:
finally:
print("End of program.")
# Cleanup code (executed
always)
Example:
Website:
try:
h ps://ni npaliwal.odoo.com
f = open("test.txt", "r")
except FileNotFoundError:
Youtube Channel:
print("File not found!")
h ps://www.youtube.com/@ni
finally: npaliwalofficial
print("Execu on
completed.")
e) else Block
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE
Example:
Reading from a File
f = open("demo.txt", "w") #
read(): Reads entire file.
Open in write mode
readline(): Reads one line.
Closing a File
readlines(): Returns list
Use close() to free
of all lines.
resources.
Example:
f.close()
with open("demo.txt", "r") as f:
Using with Clause
(Recommended) print(f.read(5)) # Reads
first 5 characters
Automatically closes the
file. print(f.readline()) # Reads
next line
with open("demo.txt", "r") as f:
print(f.readlines()) # Reads
data = f.read()
remaining lines as a list
Writing to a File
seek() and tell()
write(): Writes a string.
tell(): Returns current
writelines(): Writes a list cursor position.
of strings.
seek(offset, whence):
with open("demo.txt", "w") as f: Moves cursor to a
f.write("Hello World\n") specific position.
print(f.tell()) # Output: 0
f.seek(5) # Move
cursor to 5th byte
print(f.tell()) # Output: 5
3. Write back
using write()/writeli
nes().
data = f.read().replace("old",
"new")
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE
Example: try:
while True:
rows.append(row)
if row[0] == search_name:
print("Record Found:",
row)
rows = []
reader = csv.reader(file)
if row[0] == "Alice":
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE
Contact us:
Summary Website:
https://nitinpaliwal.odooo.com
Binary
Feature CSV File
File
Text Youtube:
Binary
Storage (Comma- https://youtube.com/@nitinpali
(0s &
Format separated walofficial
1s)
)
Module Instagram:
pickle csv
Used
https://www.instagram.com/itz
writerow() _paliwal_here/?igshid=MzNlNG
Methods for , NkZWQ4Mg%3D%3D
dump()
Writing writerows
()
Methods for
load() reader()
Reading
Supports No
No (must
Direct (must
rewrite
Modification rewrit
file)
? e file)
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE
# Push opera on
stack.append(10) # stack = [10]
stack.append(20) # stack = [10, 20]
# Pop opera on
popped = stack.pop() # popped = 20, stack = [10]
2|Page
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE
Class-Based Implementa on
class Stack:
def __init__(self):
Behind the Code:
self.items = [] __init__(): This is the constructor
method that ini alizes an empty list
def is_empty(self): self.items to store stack elements.
return len(self.items) == 0 is_empty(): Checks whether the stack is
empty by verifying if self.items has a
def push(self, item): length of 0. Returns True if the stack is
empty, otherwise False.
self.items.append(item)
push(item): Adds an item to the top of
def pop(self): the stack by appending it to self.items.
if not self.is_empty(): pop(): Removes and returns the top
return self.items.pop() element of the stack if it is not empty. If
else: the stack is empty, it returns "Stack
Underflow" to indicate an error.
return "Stack Underflow"
display(): Prints the current elements
def display(self): of the stack in list format.
print("Stack:", self.items)
# Example Usage
s = Stack()
s.push(5) # [5]
s.push(3) # [5, 3]
s.pop() # Removes 3
s.display() # Output: Stack: [5]
4. Examples
Example 1: Stack Opera ons
Ini al Stack: [ ]
Push 5: [5]
Push 8: [5, 8]
Pop: Returns 8, Stack: [5]
Example 2: Handling Errors
s = Stack()
s.pop() # Returns "Stack Underflow"
3|Page
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE
def is_empty(self):
return len(self.items) == 0
def pop(self):
if not self.is_empty():
return self.items.pop()
else:
return None
def reverse_string(s):
stack = Stack()
4|Page
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE
reversed_str = ""
return reversed_str
# Example Usage
input_string = "hello"
print("Original String:", input_string)
print("Reversed String:", reverse_string(input_string))
Output:
Original String: hello
Reversed String: olleh
5|Page
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE
Output:
Stack Overflow! Cannot push 6
Real-world Example:
Recursive func on calls without a base case can cause stack overflow,
leading to a "RecursionError" in Python.
(2) Stack Underflow
Defini on: It occurs when we try to pop an element from an empty
stack. Since there’s nothing to remove, this leads to an error.
Example:
stack = []
def pop(stack):
if len(stack) == 0:
print("Stack Underflow! Cannot pop")
else:
return stack.pop()
6|Page
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE
7. Summary Table
Concept Key Points
LIFO Last element added is the first to be removed.
Push/Pop O(1) me complexity in list implementa on.
Error Handling Check for overflow (fixed size) and underflow.
Real-World Use Browser history, recursion, parenthesis matching.
Visit us:
Website: h ps://ni npaliwal.odoo.com
Youtube: h ps://www.youtube.com/@ni npaliwalofficial
Instagram: h ps://www.instagram.com/itz_paliwal_here/
7|Page
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE
Key Terms:
Packet Switching: Data split into packets for ef icient transmission (used in
ARPANET).
TCP/IP: Protocol suite enabling internet communication.
2|Page
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE
1. Circuit Switching
A dedicated communication path is established between sender and receiver
before data transmission.
Used in traditional telephone networks.
2. Packet Switching
Data is divided into packets and sent individually over the network.
Used in the Internet and modern communication networks.
Circuit Switching vs. Packet Switching
Feature Circuit Switching Packet Switching
Connection Dedicated path is established No dedicated path; data is
Type before communication. broken into packets and sent
independently.
Data Continuous, in-order Packets may take different routes
Transmission transmission. and arrive out of order.
Setup Time Requires time to establish a No setup required; packets are
connection before data transfer. sent as soon as they are ready.
Resource Resources (bandwidth) are Resources are used on demand,
Allocation reserved for the entire session. making it more ef icient.
Ef iciency Less ef icient as resources Highly ef icient as resources are
remain reserved even if no data shared among multiple users.
is being sent.
Reliability Reliable, as data follows a ixed Less reliable due to dynamic
route. routing and potential packet loss.
Delay Low delay once the connection Can experience delays due to
is established. packet queuing and reassembly.
Example Traditional telephone Internet, VoIP (Skype, Zoom),
networks, ISDN (Integrated Email, Streaming Services.
Services Digital Network).
Key Takeaways
Circuit Switching is best for real-time communication (e.g., traditional phone
calls) where a dedicated connection ensures reliability.
Packet Switching is ideal for modern digital communication (e.g., the Internet),
as it ef iciently manages bandwidth and supports multiple connections
simultaneously.
3|Page
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE
Transmission Media
Wired Media:
Wireless Media:
Key Terms:
Guided Media: Uses physical cables (e.g., iber-optic).
Unguided Media: Wireless transmission (e.g., microwaves).
Network Devices
Device Function Example/Use Case
Directs data to speci ic devices (MAC- Used in LANs for ef icient data
Switch
based). transfer.
4|Page
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE
Network Types
Type Full Form Range Example
Network Topologies
Topology Structure Pros Cons
Linear backbone
Bus Simple, cost-effective. Single point of failure.
cable.
Dependent on central
Star Central hub/switch. Easy troubleshooting.
device.
Hierarchical (bus +
Tree Scalable. Complex cabling.
star).
Network Protocols
Protocol Purpose
5|Page
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE
Protocol Purpose
6|Page
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE
2|Page
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE
3|Page
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE
Key Terms
Data Redundancy: Unnecessary duplication of data.
Data Integrity: Accuracy and consistency of data.
Referential Integrity: Ensures valid relationships between tables
using foreign keys.
Syntax for Primary & Foreign Key:
CREATE TABLE Students (
StudentID INT PRIMARY KEY,
Name VARCHAR(50),
Email VARCHAR(100) UNIQUE
);
4|Page
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE
2. Data Types
Data Type Descrip on Example
2|Page
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE
Example:
CREATE TABLE employees (
emp_id INT,
emp_name VARCHAR(50),
salary FLOAT,
joining_date DATE
);
3. Constraints
Constraint Descrip on
Example:
CREATE TABLE users (
user_id INT PRIMARY KEY,
username VARCHAR(30) UNIQUE NOT NULL,
email VARCHAR(50) NOT NULL
);
3|Page
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE
4. Key Commands
Database Opera ons:
CREATE DATABASE dbname; | CREATE DATABASE school;
USE dbname; | USE school;
SHOW DATABASES; | SHOW DATABASES;
DROP DATABASE dbname; | DROP DATABASE school;
Table Opera ons:
CREATE TABLE tablename (col1 datatype, col2 datatype);
CREATE TABLE students (id INT, name VARCHAR(50));
DESCRIBE tablename;
DESCRIBE students;
ALTER TABLE tablename ADD colname datatype;
ALTER TABLE students ADD COLUMN age INT;
ALTER TABLE tablename DROP COLUMN colname;
ALTER TABLE students DROP COLUMN age;
DROP TABLE tablename;
DROP TABLE students;
5. DML Commands
Insert Data:
INSERT INTO tablename (col1, col2) VALUES (val1, val2);
INSERT INTO students (id, name, age) VALUES (1, 'Alice', 18);
Delete Data:
DELETE FROM tablename WHERE condi on;
DELETE FROM students WHERE id = 1;
4|Page
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE
Update Data:
UPDATE tablename SET col = new_value WHERE condi on;
UPDATE students SET age = 19 WHERE name = 'Alice';
6. SELECT Queries
Basic Syntax:
SELECT col1, col2 FROM tablename WHERE condi on;
SELECT name, age FROM students WHERE age > 18;
Clauses:
DISTINCT: SELECT DISTINCT col FROM tablename;
SELECT DISTINCT department FROM employees;
WHERE: Filters records.
SELECT * FROM employees WHERE salary > 50000;
ORDER BY: Sorts results. E.g., ORDER BY col ASC/DESC;
SELECT * FROM employees ORDER BY salary DESC;
GROUP BY: Groups rows by a column.
SELECT department, COUNT(*) FROM employees GROUP BY
department;
HAVING: Filters groups (used with GROUP BY).
SELECT department, AVG(salary) FROM employees GROUP BY
department HAVING AVG(salary) > 60000;
Operators:
Type Examples
Mathema cal +, -, *, /
5|Page
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE
Aliasing:
SELECT col AS aliasname FROM tablename;
SELECT name AS employee_name FROM employees;
7. Advanced Clauses
IN: SELECT * FROM tablename WHERE col IN (val1, val2);
SELECT * FROM students WHERE age IN (18, 20, 22);
BETWEEN: SELECT * FROM tablename WHERE col BETWEEN val1 AND
val2;
SELECT * FROM students WHERE age BETWEEN 18 AND 22;
LIKE: Pa ern matching with % (any chars) and _ (single char).
E.g., WHERE name LIKE 'A%'; (names star ng with A).
SELECT * FROM students WHERE name LIKE 'A%';
NULL Handling:
o IS NULL: Checks for NULL.
SELECT * FROM students WHERE age IS NULL;
o IS NOT NULL: Excludes NULL.
SELECT * FROM students WHERE age IS NOT NULL;
6|Page
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE
Example:
SELECT COUNT(*) FROM tablename WHERE condi on;
SELECT department, AVG(salary) FROM employees GROUP BY department;
9. Joins
Cartesian Product: Combines all rows from two tables.
o SELECT * FROM table1, table2;
SELECT * FROM students, courses;
Equi-Join: Joins tables using a common column.
o SELECT * FROM table1, table2 WHERE table1.col = table2.col;
SELECT * FROM students s, enrollments e WHERE s.id =
e.student_id;
Natural Join: Removes duplicate columns in Equi-Join.
o SELECT * FROM table1 NATURAL JOIN table2;
SELECT * FROM students NATURAL JOIN enrollments;
Primary Key CREATE TABLE student (id INT PRIMARY KEY, name VARCHAR(20));
7|Page
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE
Contact us:
Website: h ps://ni npaliwal.odoo.com
Instagram: h ps://www.instagram.com/itz_paliwal_here
Youtube: h ps://www.youtube.com/@ni npaliwalofficial
Scan QR to purchase
THE TOPPERS PACKAGE
8|Page
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE
db.commit()
db.close()
print("Record inserted successfully!")
print("\nEmployee Records:")
for record in records:
print(record)
if choice == 1:
create_table()
elif choice == 2:
e_code = input("Enter Employee Code: ")
name = input("Enter Name: ")
salary = int(input("Enter Salary: "))
insert_record(e_code, name, salary)
elif choice == 3:
fetch_records()
elif choice == 4:
e_code = input("Enter Employee Code to Update: ")
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE
CONTACT US:
WEBSITE: h ps://ni npaliwal.odoo.com
Youtube: h ps://www.youtube.com/@ni npaliwalofficial
Instagram: h ps://www.instagram.com/itz_paliwal_here
To purchase “THE
TOPPERS PACKAGE”
SCAN THIS QR