0% found this document useful (0 votes)
44 views

Class 12 Computer Science Full Syllabus Notes PDF.pdf

The document provides an overview of Python programming, highlighting its advantages such as readability, extensive libraries, and ease of use, as well as disadvantages like speed limitations and memory consumption. It covers fundamental concepts including tokens, operators, data types (strings, lists, tuples, dictionaries), and basic syntax for expressions, statements, and input/output. Additionally, it discusses error types and operator precedence in Python.

Uploaded by

yaswanth270308
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views

Class 12 Computer Science Full Syllabus Notes PDF.pdf

The document provides an overview of Python programming, highlighting its advantages such as readability, extensive libraries, and ease of use, as well as disadvantages like speed limitations and memory consumption. It covers fundamental concepts including tokens, operators, data types (strings, lists, tuples, dictionaries), and basic syntax for expressions, statements, and input/output. Additionally, it discusses error types and operator precedence in Python.

Uploaded by

yaswanth270308
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 58

PYTHON REVISION 5) Integra on Capabili es:

Easily integrates with other


TOUR FOR CLASS 12 languages.
6) Rapid Development: Quick
prototyping and
GETTING STARTED WITH development.
PYTHON 7) Cross-Pla orm: Compa ble
with major opera ng systems.
Introduc on to Python: 8) Scalability: Can be used in
 Python is an interpreted, large-scale applica ons.
high-level, and general-
purpose programming Disadvantages of Python:
language.
 It emphasizes code readability 1) Speed: Interpreted nature
with its notable use of may be slower than compiled
significant indenta on. languages.
2) Global Interpreter Lock (GIL):
Features of Python: Limits thread execu on on
 Easy to learn and use. mul -core systems.
 Open-source and free. 3) Mobile Development: Not the
 Extensive library support. primary choice for mobile app
 Pla orm-independent. development.
4) Design Restric ons: Some
Advantages of Python: developers may find design
philosophies limi ng.
1) Readability: Clear and easy- 5) Memory Consump on: May
to-understand syntax. use more memory, especially
2) Large Standard Library: in resource-constrained
Extensive pre-built modules environments.
for various tasks. 6) Threading Limita ons:
3) Versa lity: Suitable for web Challenges in leveraging
development, data science, mul -core processors.
and more. 7) Packaging Issues: Managing
4) Community Support: Ac ve dependencies can be
community providing challenging.
resources and libraries. 8) Less Suitable for Resource-
Intensive Tasks: Performance
may not match languages 3) Literals:
designed for resource- Fixed values in a program.
intensive tasks Types of literals:
Numeric Literals:
TOKENS Integers, floats,
complex numbers.
Introduc on to Tokens: x = 10
 Tokens are the smallest units y = 3.14
of a Python program. They z = 2 + 3j
are the building blocks of a i. String Literals:
Python script. s = "Hello"
 ii. Boolean Literals:
Types of Tokens: True and False.
1) Keywords: status = True
Reserved words in Python 4) Operators:
that have predefined Operators are special symbols or
meanings. keywords in Python that perform
Examples: if, else, while, operations on operands. Operands
for, import, True, False. are the values or variables on which
if True: the operation is performed. Python
print("This is a keyword example") supports a wide range of operators
classified into several categories.
2) Iden fiers:
Names used to iden fy Types of Operators:
variables, func ons, a) Arithmetic Operators:
classes, etc. These operators are
used to perform
Must begin with a le er
mathematical
(A-Z or a-z) or an
operations.
underscore (_), followed
Operato
by le ers, digits (0-9), or Description Example
r
underscores. + Addition 5+3→8
Examples: my_var, _temp, - Subtraction 10 - 4 → 6
Counter. * Multiplication 6 * 3 → 18
my_var = 10 / Division 15 / 2 → 7.5
print(my_var) // Floor Division 15 // 2 → 7
Modulus
% 15 % 4 → 3
(Remainder)
Operato used to assign values to
Description Example
r variables.
2 *
*
Exponentiatio 3 Operator Description Example
**
n → = Assign x = 10
8
x += 5 →
+= Add and assign
15
b) Relational x -= 3 →
(Comparison) -= Subtract and assign
12
Operators: These x *= 2 →
*= Multiply and assign
operators compare two 24
values and return a /= Divide and assign x /= 4 → 6
Boolean (True or False). Floor divide and
//= x //= 2 → 3
Operator Description Example assign
5 == 5 → Exponent and
== Equal to **= x **= 2 → 9
True assign
5 != 3 → Modulus and
!= Not equal to %= x %= 2 → 1
True
assign
7>5→
> Greater than
True
e) Bitwise Operators:
3<5→
< Less than These operators
True
Greater than or 5 >= 5 →
perform operations at
>=
equal to True the bit level.
Less than or equal 4 <= 5 → Operator Description Example
<=
to True & AND 5&3→1
` ` OR
c) Logical Operators: ^ XOR 5^3→6
These operators are ~ NOT ~5 → -6
used to combine << Left Shift 5 << 1 → 10
conditional statements.
5 >> 1 →
Operator Description Example >> Right Shift
2
Returns True if (5 > 3) and (6
and
both are true > 4) → True
f) Membership
Returns True if (5 > 3) or (3 > Operators These
or
one is true 7) → True
operators test
Reverses the not(5 > 3) → membership in a
not
Boolean result False
sequence (e.g., list,
string).
d) Assignment Operators:
These operators are
Operator Description Example
'a' in 'apple' → Strings
in True if present
True
Introduc on:
True if not 'x' not in
not in  Strings in Python are
present 'apple' → True
sequences of characters
g) Identity Operators enclosed in quotes.
These operators s = "Hello"
compare memory
locations of two String Opera ons:
objects.
Operator Description Example  Concatena on:
is True if same object x is y "Hello" + " World"
is not
True if not the same x is not # Output: "Hello World"
object y
 Repe on:
Python Execu on Modes: "Hi " * 3
 Interac ve Mode: Commands # Output: "Hi Hi Hi "
are executed one at a me in
a Python shell.  Membership:
 Script Mode: A program is 'a' in 'apple'
wri en in a file with .py # Output: True
extension and executed.
String Slicing:
Basic Syntax:  Slicing allows you to extract
por ons of a string using
Comments: indices.
# This is a comment Syntax:
string[start:stop:step]
Variables:
x = 10 Examples:
y = "Hello" s = "Hello, World!"
Example Program:
print("Hello, Python!") print(s[1:5])
x=5 # Output: "ello"
print(x * 2)
# Output: 10 print(s[:5])
# Output: "Hello" (start is omi ed,  upper(): Converts the string
default is 0) to uppercase.
print("hello".upper())
print(s[7:]) #Output: "HELLO"
# Output: "World!" (stop is omi ed,
goes ll the end)  strip(): Removes leading and
trailing spaces.
print(s[::2]) print(" hello ".strip())
# Output: "Hlo ol!" (every second # Output: "hello"
character)
 replace(): Replaces a
print(s[::-1]) substring with another
# Output: "!dlroW ,olleH" (reverses substring.
the string) print("apple".replace("a", "A"))
# Output: "Apple"
Nega ve Indexing:
Nega ve indices count from the  find(): Returns the index of
end of the string. the first occurrence of a
print(s[-1]) substring.
# Output: "!" (last character) print("banana".find("na"))
# Output: 2
print(s[-6:-1])
# Output: "World" (slicing with Example Program:
nega ve indices) s = "Hello, World!"
print(s.lower())
Built-in String Methods:

 len(): Returns the length of Lists


the string. Introduc on:
print(len("Hello"))  A list is a collec on of items,
# Output: 5 which can be of different data
types.
 lower(): Converts the string to
lowercase. lst = [1, 2, "Apple", 3.5]
print("HELLO".lower())
# Output: "hello" List Opera ons:
 Concatena on:
[1, 2] + [3, 4]  insert(): Inserts an element at
# Output: [1, 2, 3, 4] a specified posi on.
lst.insert(2, "New")
 Repe on:
["Hi"] * 3  remove(): Removes the first
# Output: ["Hi", "Hi", "Hi"] occurrence of a value.
lst.remove(3)
 Membership:
3 in [1, 2, 3]  pop(): Removes and returns
# Output: True the element at the specified
posi on.
List Slicing: lst.pop(1)
Similar to string slicing.
lst = [1, 2, 3, 4, 5]  sort(): Sorts the list in
ascending order.
print(lst[1:4]) lst.sort()
# Output: [2, 3, 4]
 reverse(): Reverses the order
print(lst[:3]) of elements in the list.
# Output: [1, 2, 3] lst.reverse()

print(lst[3:]) Example Program:


# Output: [4, 5] lst = [1, 3, 2]
lst.sort()
print(lst[::-1]) print(lst)
# Output: [5, 4, 3, 2, 1] (reverses # Output: [1, 2, 3]
the list)

Built-in List Methods:


 append(): Adds an element to
the end of the list.
lst.append(6)

 extend(): Adds elements of Tuples


another list.
lst.extend([7, 8]) Introduc on:
 A tuple is a collec on of print((1, 2, 1).count(1))
immutable items. # Output: 2
tpl = (1, 2, "Apple")
 index(): Returns the index of
Tuple Opera ons: the first occurrence of a
 Concatena on: value.
(1, 2) + (3, 4) print((1, 2, 3).index(2))
# Output: (1, 2, 3, 4) # Output: 1

 Repe on: Example Program:


("Hi",) * 3 tpl = (1, 2, 3)
# Output: ("Hi", "Hi", "Hi") print(tpl.index(2))
# Output: 1
 Membership:
3 in (1, 2, 3)
# Output: True
Dic onary
Tuple Slicing: Introduc on:
Similar to lists.  A dic onary is a collec on of
tpl = (1, 2, 3, 4, 5) key-value pairs.

print(tpl[1:4]) dct = {"name": "Alice", "age": 25}


# Output: (2, 3, 4)
Dic onary Opera ons:
print(tpl[:3])  Accessing Values:
# Output: (1, 2, 3) print(dct["name"])
# Output: "Alice"
print(tpl[3:])
# Output: (4, 5)  Adding Items:
dct["city"] = "New York"
print(tpl[::-1])
# Output: (5, 4, 3, 2, 1) (reverses  Removing Items:
the tuple) dct.pop("age")

Built-in Tuple Methods: Built-in Dic onary Methods:


 count(): Counts the
occurrences of a value.
 keys(): Returns all keys in the
dic onary.
print(dct.keys())

 values(): Returns all values in


the dic onary.
print(dct.values())

 items(): Returns all key-value


pairs as tuples.
print(dct.items())

 get(): Returns the value for a


specified key.
print(dct.get("name"))
# Output: "Alice"

 update(): Updates the


dic onary with key-value
pairs from another dic onary.
dct.update({"age": 26})

 clear(): Removes all items


from the dic onary.
dct.clear()
PYTHON REVISION result = 10 - 5 - 2 # Le to right;
result = 3
TOUR -2 FOR
3. Type Conversion:
CLASS 12
Implicit Conversion: Python
EXPRESSIONS, STATEMENT, TYPE automa cally converts one type to
CONVERSION, AND INPUT/OUTPUT another.
result = 5 + 3.2 # int + float -> float;
1. Expressions and Statements: result = 8.2

Expression: A combina on of Explicit Conversion (Type Cas ng):


values, variables, and operators that Manually conver ng a type.
produces a result. Examples: x = int(3.7) # x = 3
x+y y = float(5) # y = 5.0
3 * (4 + 5)
"Hello" + " World" 4. Input and Output:

Statement: A complete instruc on Accep ng input:


to the interpreter. Examples: name = input("Enter your name: ")
x = 10 age = int(input("Enter your age: "))
print("Hello World")
Displaying output:
2. Operator Precedence and print("Hello", name)
Expression Evalua on: print(f"You are {age} years old")

Precedence: Determines the order


in which operators are evaluated. Errors
Higher precedence operators are 1. Syntax Errors:
evaluated first. Occur when the Python parser
result = 2 + 3 * 4 detects incorrect syntax.
# Mul plica on has higher if x > 5 # Missing colon
precedence; result = 14
2. Logical Errors:
Associa vity: Determines the order The program runs but produces
of evalua on for operators of the incorrect results.
same precedence. Example:
result = 10 / 2 # Intended to Condi onal Statements
calculate mul plica on, but used
division 1. Syntax and Examples:

3. Run- me Errors: if Statement:


Occur during program execu on. if x > 0:
x = int("abc") # ValueError print("Posi ve")
y = 10 / 0 # ZeroDivisionError
if-else Statement:
if x % 2 == 0:
print("Even")
Flow of Control else:
print("Odd")
1. Introduc on:
Determines the execu on sequence if-elif-else Statement:
of statements in a program. if x < 0:
print("Nega ve")
2. Use of Indenta on: elif x == 0:
Python uses indenta on to define print("Zero")
blocks of code. else:
if x > 0: print("Posi ve")
print("Posi ve")
2. Flowcharts:
3. Types of Control Flows: Use flowcharts to visualize
condi onal logic.
Sequen al: Executes
statements line by line. 3. Example Programs:

Condi onal: Executes Absolute Value:


based on condi ons using x = int(input("Enter a number: "))
if, if-else, if-elif-else. if x < 0:
x = -x
Itera ve: Executes a block print("Absolute value:", x)
of code mul ple mes
using loops (for, while). Sort 3 Numbers:
# Program to sort three numbers
a = int(input("Enter the first number: Con nue:
")) for i in range(10):
b = int(input("Enter the second if i % 2 == 0:
number: ")) con nue
c = int(input("Enter the third print(i)
number: "))
4. Example Programs:
# Sor ng logic
if a > b: Generate Pa ern:
a, b = b, a for i in range(1, 6):
if b > c: print("*" * i)
b, c = c, b
if a > b: Summa on of Series:
a, b = b, a n = int(input("Enter n: "))
print(sum(range(1, n+1)))
print(f"Sorted order: {a}, {b}, {c}")
Factorial:
Itera ve Statements n = int(input("Enter a number: "))
fact = 1
1. For Loop: for i in range(1, n + 1):
Syntax and Example: fact *= i
for i in range(5): print("Factorial:", fact)
print(i)
Introduc on to Python Modules
2. While Loop:
Syntax and Example: 1. Impor ng Modules:
x=5 Syntax:
while x > 0: import module_name
print(x) from module_name import
x -= 1 specific_func on

3. Break and Con nue: 2. Math Module:


Break: import math
for i in range(10): print(math.pi)
if i == 5: print(math.sqrt(16))
break print(math.ceil(4.2))
print(i)
3. Random Module:
import random
print(random.random())
print(random.randint(1, 10))
print(random.randrange(0, 10, 2))

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

Functions o len(): Returns the


length of a
1. What is a Function?
sequence.
 Definition: A function
b. Functions Defined in
is a block of code
designed to perform a Modules

specific task. It  Provided by external


executes only when libraries; requires
called. importing the module.

 Analogy: Think of a  Example:


function as a vending
import math
machine. You provide
print(math.sqrt(16)) #
inputs (money and
Output: 4.0
selection), and it
returns an output c. User-Defined Functions
(your item).  Created by the
programmer to
perform specific
2. Types of Functions
tasks.
a. Built-in Functions
 Example:
 Predefined in Python
def greet():
and readily available.
print("Hello, World!")
 Examples:
greet() # Output: Hello,
o print(): Prints
World!
output to the
screen.
NITIN PALIWAL

3. Creating a User- print(subtract(10, 3)) #


Defined Function Output: 7

 Syntax: b. Default Parameters

def func(parameters):  Parameters with


predefined values.
# Function body
 Example:
return value(s) #
Optional def greet(name="User"):

 Example: print(f"Hello, {name}!")

def add(a, b): greet()

return a + b # Output: Hello, User!

print(add(5, 3)) greet("Nitin") # Output:

# Output: 8 Hello, Nitin!

4. Arguments and 5. Function Returning


Value(s)
Parameters

a. Positional Parameters  Functions can return


one or multiple values
 Arguments must
using the return
match the order of
keyword.
parameters.
 Single Value:
 Example:
def multiply(a, b):
def subtract(a, b):
return a * b
return a - b
NITIN PALIWAL

print(multiply(4, 5)) 7. Scope of a Variable

# Output: 20 a. Local Scope

 Multiple Values:  Defined within a


function and
def calc(a, b):
accessible only inside
return a + b, a - b
it.
result = calc(10, 5)
 Example:
print(result)
def func():
# Output: (15, 5)
x = 10

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

 Use the global


keyword to modify
global variables inside
a function.

 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

FILE HANDLING – 1  Relative Path: Path


relative to the current
1. Introduction To Files working directory.
What is a File? o Example: Documents
 A file is a container for /file.txt
storing data (text, binary,
CSV) on a storage device.
3. Text File Operations
Types of Files:
Key Methods & Concepts:
Type Description Example
Opening a File
Human-
 Use open(filename,
Text readable,
.txt, .py mode) function.
File stores
characters.  Modes Table:

Non-readable, Mode Description


Binary
stores bytes .jpg, .dat Read-only (default).
File r
(images, audio). File must exist.
Stores tabular Read + write. File
CSV data in plain r+
must exist.
.csv
File text (comma-
Write-only.
separated).
w Creates/overwrites
file.
2. File Paths Write + read.
 Absolute Path: Full path w+ Creates/overwrites
from the root directory. file.

o Example: C:\Users\ Append-only.


Name\Documents\fi a Creates file if not
le.txt exists.
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

Mode Description Appending to a File

Append + read. with open("demo.txt", "a") as f:


a+ Creates file if not f.write("Appended text")
exists.

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.

f.writelines(["Line 1\n", "Line o whence=0 (default):


2\n"]) Start of file.
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

o whence=1: Current f.seek(0)


position.
f.write(data)
o whence=2: End of
f.truncate() # Remove
file.
remaining old data
Example:

with open("demo.txt", "r") as f:

print(f.tell()) # Output: 0

f.seek(5) # Move
cursor to 5th byte

print(f.tell()) # Output: 5

4. Data Manipulation Tips


 To modify data:

1. Read the file


using read()/readlin
es().

2. Process data (e.g.,


string operations).

3. Write back
using write()/writeli
nes().

Example (Replace a Word):

with open("demo.txt", "r+") as


f:

data = f.read().replace("old",
"new")
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

File Handling - 2 Mode Description

Read & Write


1. Binary Files in Python
'rb+' (binary, without
Binary files store data in a truncating)
non-human-readable format
Read & Write
(0s and 1s) and are commonly
'wb+' (binary, truncates
used for storing images, audio,
file if exists)
video, or serialized Python
objects. Append & Read
'ab+'
Opening and Closing a Binary (binary)
File  Closing a File:
 A binary file is opened file.close()
using the open() function.
This ensures that all changes
 Syntax: are saved, and the file is
file = open("filename", mode) properly closed.

 File Modes for Binary


Files: Working with the pickle
Mode Description Module

Since binary files store data in


'rb' Read (binary)
byte format, Python provides
Write (binary, the pickle module to serialize
'wb' overwrites existing (convert to binary) and
data) deserialize (convert back to
Python object) data.
Append (binary,
'ab' adds new data at Importing pickle
the end) import pickle
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

Writing Data to a Binary File Appending Data to a Binary


(dump()) File

 We use Appending means adding new


pickle.dump(object, file) data without overwriting
to write data to a binary existing content.
file.
with open("student.dat", "ab")
 Example: as file:

import pickle new_data = {"Name": "Alice",


"Age": 20, "Grade": "B"}
with open("student.dat", "wb")
as file: pickle.dump(new_data, file)

data = {"Name": "John", Reading Multiple Records


"Age": 18, "Grade": "A"} from a Binary File

pickle.dump(data, file) Since multiple records are


stored in binary files, we use a
Reading Data from a Binary
loop with EOFError handling.
File (load())
with open("student.dat", "rb")
 We use pickle.load(file) to
as file:
retrieve data from a
binary file. while True:

 Example: try:

with open("student.dat", "rb") record =


as file: pickle.load(file)

data = pickle.load(file) print(record)

print(data) # Output: except EOFError:


{'Name': 'John', 'Age': 18,
break # Stops reading
'Grade': 'A'}
when end of file is reached
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

Searching for a Specific


Record records.append(pickle.load(file)
)
search_name = "Alice"
except EOFError:
with open("student.dat", "rb")
as file: break

while True:

try: # Updating a record

record = for record in records:


pickle.load(file)
if record["Name"] == "Alice":
if record["Name"] ==
record["Grade"] = "A+" #
search_name:
Updating AliceÕs grade
print("Record
Found:", record)
# Writing updated records
except EOFError:
back to file
break
with open("student.dat", "wb")
Updating a Record in a Binary as file:
File
for record in records:
To update data in a binary file,
pickle.dump(record, file)
we need to read all records,
modify the required record,
and rewrite everything back. 2. CSV Files in Python
records = [] CSV (Comma-Separated
with open("student.dat", "rb") Values) files store tabular data
as file: where each row is a record,
and values are separated by
while True:
commas. These files can be
try: opened in spreadsheet
software like MS Excel.
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

Working with CSV Files in Writing Multiple Rows


Python (writerows())

Python provides the csv module data = [["John", 18, "A"],


to handle CSV files. ["Alice", 20, "B"], ["Bob", 19,
"C"]]
Importing csv Module
with open("students.csv", "a",
import csv
newline='') as file:
Opening and Closing a CSV
writer = csv.writer(file)
File
writer.writerows(data) #
 Opening a CSV file:
Writing multiple rows
file = open("data.csv", "w",
newline='') # Open in write
mode Reading Data from a CSV File

 Closing a CSV file: We use the reader() method to


read data from a CSV file.
file.close()
Reading and Displaying All
Writing Data into a CSV File
Rows
CSV files store data in rows
with open("students.csv", "r")
and columns. We use writer()
as file:
and writerow() to write data.
reader = csv.reader(file)
Writing a Single Row
(writerow()) for row in reader:

with open("students.csv", "w", print(row) # Output:


newline='') as file: ['John', '18', 'A']

writer = csv.writer(file) Reading Data Row by Row

writer.writerow(["Name", with open("students.csv", "r")


"Age", "Grade"]) # Writing as file:
the header row
reader = csv.reader(file)

for row in reader:


#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

print(f"Name: {row[0]}, row[2] = "A+" #


Age: {row[1]}, Grade: {row[2]}") Updating Alice's grade

rows.append(row)

Searching for a Specific


Record in a CSV File
# Writing the updated data
search_name = "Alice" back to the file

with open("students.csv", "r") with open("students.csv", "w",


as file: newline='') as file:

reader = csv.reader(file) writer = csv.writer(file)

for row in reader: writer.writerows(rows)

if row[0] == search_name:

print("Record Found:",
row)

Updating a Record in a CSV


File

Since CSV files do not support


direct modification, we read
the file, modify the data,
and rewrite it.

rows = []

with open("students.csv", "r")


as file:

reader = csv.reader(file)

for row in reader:

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

STACKS - Class 12 CBSE Computer Science Notes


1. What is a Stack?
 Linear data structure following LIFO (Last In First Out) principle.
 Example: Stack of plates; the last plate added is the first to be removed.
 Key Terms:
o Top: Points to the last element inserted.
o Push: Add an element to the stack.
o Pop: Remove the top element from the stack.

2. Opera ons on Stack


Time
Opera on Descrip on Error Condi ons
Complexity
Adds element to the top Stack Overflow (if stack is
Push O(1)
of the stack full)
Removes element from Stack Underflow (if stack
Pop O(1)
the top is empty)
Push Algorithm
1. Check if the stack is full (if size is fixed).
2. If not full, increment top by 1.
3. Insert the element at top posi on.
Pop Algorithm
1. Check if the stack is empty.
2. If not empty, return the element at top.
3. Decrement top by 1.

3. Implementa on of Stack Using List (Python)


Using Python List
stack = [] # Empty stack

# 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

5. Applica ons of Stack


1. Undo/Redo in text editors.
2. Func on call management in programming (call stack).
3. Expression evalua on (e.g., infix to pos ix conversion).
4. Backtracking algorithms (e.g., maze solving).

6. Important Exam Ques ons


Q1. Write a Python program to reverse a string using a stack.
Q2. Explain stack overflow and underflow with examples.
Q3. Differen ate between stack and queue.

Q1. Write a Python program to reverse a string using a stack.


Concept Involved:
A stack follows the Last In, First Out (LIFO) principle, meaning the last element
added is the first to be removed. To reverse a string using a stack:
1. Push each character of the string onto the stack.
2. Pop characters from the stack one by one and append them to form the
reversed string.
Python Program:
class Stack:
def __init__(self):
self.items = []

def is_empty(self):
return len(self.items) == 0

def push(self, item):


self.items.append(item)

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

# Push all characters onto the stack


for char in s:
stack.push(char)

reversed_str = ""

# Pop characters to get the reversed string


while not stack.is_empty():
reversed_str += stack.pop()

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

Q2. Explain stack overflow and underflow with examples.


(1) Stack Overflow
 Defini on: It occurs when we try to push an element onto a stack that is
already full. This happens in fixed-size stacks, like those used in memory
management and recursion.
 Example:
stack = [1, 2, 3, 4, 5]
max_size = 5

def push(stack, item):


if len(stack) >= max_size:
print("Stack Overflow! Cannot push", item)
else:
stack.append(item)

push(stack, 6) # A empt to push when stack is full

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()

pop(stack) # A empt to pop when stack is empty


Output:
Stack Underflow! Cannot pop
Real-world Example:
 Trying to undo an ac on when there are no previous ac ons stored in
the undo history.

Q3. Differen ate between Stack and Queue


Feature Stack Queue
A stack follows LIFO (Last A queue follows FIFO (First In,
Defini on
In, First Out) order. First Out) order.
Inser on (Push) and Inser on (Enqueue) happens at
Inser on &
dele on (Pop) happen at the rear, and dele on
Dele on
the same end (top). (Dequeue) happens at the front.
push(), pop(), peek(), enqueue(), dequeue(), peek(),
Basic Opera ons
is_empty() is_empty()
Implemented using arrays Implemented using arrays,
Implementa on
or linked lists. linked lists, or circular arrays.

6|Page
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

Feature Stack Queue


- Undo/Redo opera ons in
- Print queue in a printer.
editors.
Example Usage - Request handling in web
- Func on call stack in
servers.
recursion.
- Circular Queue
- Bounded Stack
Varia ons - Priority Queue
- Dynamic Stack
- Double-ended Queue (Deque)

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

COMPUTER NETWORKS – Class 12 Computer


Science
Evolution of Networking
 Computer Network: Interconnected devices sharing resources via
communication channels.
 Evolution Timeline:

Network Year Purpose

ARPANET 1969 First network for military/research (packet switching).

Upgraded ARPANET for academic use; backbone of early


NSFNET 1986
internet.

Internet 1990s Global network of networks using TCP/IP.

Key Terms:
 Packet Switching: Data split into packets for ef icient transmission (used in
ARPANET).
 TCP/IP: Protocol suite enabling internet communication.

Data Communication Terminologies


1. Components of Communication:
o Sender: Initiates data transmission.
o Receiver: Receives data.
o Message: Information transmitted.
o Media: Physical/non-physical path (e.g., cables, Wi-Fi).
o Protocols: Rules for communication (e.g., HTTP, FTP).
2. Capacity Measurement:
o Bandwidth: Max data transfer rate (measured in bps/Mbps/Gbps).
o Data Transfer Rate: Actual speed (e.g., 100 Mbps).
3. IP Address: Unique numerical identi ier for devices (e.g., 192.168.1.1).
o IPv4: 32-bit address (4 billion devices).
o IPv6: 128-bit address (trillions of devices).
4. Switching Techniques: Circuit Switching and Packet Switching are two
fundamental techniques used for data transmission in networks.

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:

Type Speed Use Case Example

Twisted Pair Up to 1 Gbps LANs (Ethernet). CAT6 cable.

Co-axial 10-100 Mbps Cable TV, broadband. RG-6 cable.

Fiber-optic Up to 100 Tbps Long-distance, high-speed. FTTH (Fiber to Home).

Wireless Media:

Type Range Use Case Example

Radio Waves Long Wi-Fi, AM/FM radio. Bluetooth.

Microwaves Medium Satellite communication. Radar systems.

Infrared Short TV remotes, data transfer. IR sensors.

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

Modem Converts digital ↔ analog signals. Dial-up internet connection.

Ethernet Enables wired network connectivity


Desktop PC network connection.
Card via RJ45.

RJ45 Connector for Ethernet cables (8-pin). Used in CAT6 cables.

Ampli ies signals to extend network


Repeater Used in long Ethernet cables.
range.

Broadcasts data to all connected


Hub Obsolete; replaced by switches.
devices.

Directs data to speci ic devices (MAC- Used in LANs for ef icient data
Switch
based). transfer.

Routes data between different Connects home LAN to the


Router
networks. internet.

4|Page
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

Device Function Example/Use Case

Connects networks with different


Gateway Links a LAN to a WAN.
protocols.

WiFi Card Enables wireless network connectivity. Laptops, smartphones.

Network Types
Type Full Form Range Example

PAN Personal Area Network 10 meters Bluetooth, USB.

LAN Local Area Network Building/campus School/of ice network.

MAN Metropolitan Area Network City Cable TV network.

WAN Wide Area Network Global Internet.

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

HTTP (Hypertext Transfer Protocol) Transfers web pages.

HTTPS (Hypertext Transfer Protocol Secure) Secure web transfer (encrypted).

FTP (File Transfer Protocol) File transfer.

SMTP (Simple Mail Transfer Protocol) Sending emails.

POP3 (Post Of ice Protocol) Retrieving emails from server.

5|Page
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

Protocol Purpose

TCP/IP (Transmission Control


Core internet protocol suite.
Protocol/Internet Protocol)

Direct communication between two


PPP (Point to Point Protocol)
nodes (e.g., dial-up).

TELNET (Telecommunication Network) Remote terminal access (unsecured).

Voice calls over the internet. (Skype,


VoIP (Voice-over Internet Protocol)
Zoom

Introduction to Web Services


1. WWW (World Wide Web): System of interlinked hypertext documents accessed
via the internet.
2. HTML:
o HyperText Markup Language: Structures web content using tags
(e.g., <h1>, <p>).
3. XML:
o Extensible Markup Language: Stores/transports data (self-descriptive
tags).
4. Domain Name: Human-readable address (e.g., www.example.com).
5. URL: Full web address with
parts: Protocol (HTTPS), Domain (example.com), Path (/page1).
6. Website: Collection of web pages (e.g., Wikipedia).
7. Web Browser: Software to access websites (e.g., Chrome, Firefox).
8. Web Server: Hosts websites (e.g., Apache, Nginx).
9. Web Hosting: Service providing server space (types: Shared, VPS, Dedicated).

Reach out to me:


Website: https://nitinpaliwal.odoo.com
Youtube: https://www.youtube.com/@nitinpaliwalof icial
Instagram: https://www.instagram.com/itz_paliwal_here

To purchase THE TOPPERS PACKAGE,


Scan this QR code

6|Page
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

DBMS AND RDBMS – Class 12


Computer Science
1. Database Concepts
Database: Organized collection of related data stored electronically.
DBMS (Database Management System): Software to create, manage, and
manipulate databases (e.g., MySQL, Oracle).
Need for Databases:
 Eliminates data redundancy (duplication).
 Reduces data inconsistency.
 Ensures data integrity and security.
 Allows concurrent access and data sharing.
Traditional File System vs. Database
Parameter File System Database
Data Redundancy High Low/None
Data Access Manual Easy via queries
Security Limited Robust
Example:
 File System: Separate iles for students, classes, grades.
 Database: Single database with tables like Students, Classes, Grades.

2. Relational Data Model


Organizes data into relations (tables) with rows and columns.
Term De inition Example
Relation Table with rows and columns Students table
Attribute Column ( ield) in a table StudentID, Name, Age

2|Page
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

Term De inition Example


Tuple Row (record) in a table A student’s data entry
Set of valid values for an
Domain Age domain: 10–30
attribute
Number of attributes in a
Degree Degree of Students: 3
relation
100 students →
Cardinality Number of tuples in a relation
cardinality=100

3. Keys in Relational Model


Key Type De inition Example
Minimal set of attributes
Candidate
uniquely identifying a StudentID or Email in Students
Key
tuple
Primary Chosen candidate key to
StudentID (selected as primary key)
Key uniquely identify tuples
Alternate Candidate keys not
Email (if StudentID is primary key)
Key chosen as primary key
Attribute(s) referencing
Foreign CourseID in Enrollments table links
primary key of another
Key to Courses
table
Example:
Table 1: Students
StudentID (PK) Name Email (Alternate Key)
101 Alice [email protected]
102 Bob [email protected]
Table 2: Enrollments

3|Page
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

EnrollID StudentID (FK) CourseID


1 101 C001
2 102 C002

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
);

Summary: Databases organize data ef iciently using tables (relations) with


attributes, tuples, and keys to ensure uniqueness and relationships.

Reach out to me:


Website: https://nitinpaliwal.odoo.com
Youtube: https://www.youtube.com/@nitinpaliwalof icial
Instagram: https://www.instagram.com/itz_paliwal_here

To purchase THE TOPPERS PACKAGE,


Scan this QR Code

4|Page
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

SQL – Class 12 Computer Science


1. SQL Basics
 DDL (Data Defini on Language): Commands to define/modify database
structure. Example: CREATE, ALTER, DROP, TRUNCATE, RENAME.
o CREATE: Create databases, tables, etc.
o Example: CREATE TABLE students (id INT, name VARCHAR(50));
o ALTER: Modify existing database objects.
o Example: ALTER TABLE students ADD COLUMN age INT;
o DROP: Delete database objects.
o Example: DROP TABLE students;
o TRUNCATE: Remove all records from a table without deleting its
structure.
o Example: TRUNCATE TABLE students;
o RENAME: Rename a database object.
o Example: ALTER TABLE students RENAME TO learners;

 DML (Data Manipula on Language): Commands to manipulate data.


Example: SELECT, INSERT, UPDATE, DELETE.
o SELECT: Retrieve data.
o Example: SELECT * FROM students;
o INSERT: Add new records.
o Example: INSERT INTO students (id, name, age) VALUES (1,
'John', 20);
o UPDATE: Modify existing records.
o Example: UPDATE students SET age = 21 WHERE id = 1;
o DELETE: Remove records.
o Example: DELETE FROM students WHERE id = 1

2. Data Types
Data Type Descrip on Example

CHAR(n) Fixed-length string (max 255 chars) CHAR(10)

VARCHAR(n) Variable-length string (max 65535 chars) VARCHAR(50)

INT Integer values INT

2|Page
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

Data Type Descrip on Example

FLOAT Decimal numbers FLOAT

DATE Date in YYYY-MM-DD format DATE

Example:
CREATE TABLE employees (
emp_id INT,
emp_name VARCHAR(50),
salary FLOAT,
joining_date DATE
);

3. Constraints
Constraint Descrip on

NOT NULL Column cannot have NULL values

UNIQUE All values in column are dis nct

PRIMARY KEY Uniquely iden fies a row (NOT NULL + UNIQUE)

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 +, -, *, /

Rela onal =, >, <, >=, <=, !=

Logical AND, OR, NOT

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;

8. Aggregate Func ons


Func on Descrip on

MAX() Returns maximum value

MIN() Returns minimum value

AVG() Returns average value

SUM() Returns sum of values

COUNT() Returns number of rows

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;

Quick Revision Table


Concept Syntax/Example

Create DB CREATE DATABASE school;

Primary Key CREATE TABLE student (id INT PRIMARY KEY, name VARCHAR(20));

Delete Row DELETE FROM student WHERE id = 5;

Aggregate SELECT AVG(marks) FROM result;

Group By SELECT dept, COUNT(*) FROM emp GROUP BY dept;

7|Page
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

Tips for Exams:


 Focus on syntax of JOINs, GROUP BY-HAVING, and ALTER TABLE.
 Prac ce wri ng queries with mul ple condi ons (AND/OR).
 Revise constraints and data types thoroughly.

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

INTERFACE OF PYTHON WITH MYSQL

import mysql.connector as mysql

# Func on to connect to MySQL


def connect_db():
return mysql.connect(host="localhost", user="root", passwd="root",
database="emp")

# Func on to create a table


def create_table():
db = connect_db()
cursor = db.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS employees (E_code
VARCHAR(10) PRIMARY KEY, Name VARCHAR(50), Salary INT)")
db.commit()
db.close()
print("Table created successfully!")

# Func on to insert a record


def insert_record(e_code, name, salary):
db = connect_db()
cursor = db.cursor()
query = "INSERT INTO employees (E_code, Name, Salary) VALUES (%s, %s,
%s)"
values = (e_code, name, salary)
cursor.execute(query, values)
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

db.commit()
db.close()
print("Record inserted successfully!")

# Func on to fetch records {IMP}


def fetch_records():
db = connect_db()
cursor = db.cursor()
cursor.execute("SELECT * FROM employees")
records = cursor.fetchall()
db.close()

print("\nEmployee Records:")
for record in records:
print(record)

# Func on to update a record {IMP}


def update_record(e_code, new_salary):
db = connect_db()
cursor = db.cursor()
query = "UPDATE employees SET Salary = %s WHERE E_code = %s"
values = (new_salary, e_code)
cursor.execute(query, values)
db.commit()
db.close()
print("Record updated successfully!")
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

# Func on to delete a record {IMP}


def delete_record(e_code):
db = connect_db()
cursor = db.cursor()
query = "DELETE FROM employees WHERE E_code = %s"
cursor.execute(query, (e_code,))
db.commit()
db.close()
print("Record deleted successfully!")

# Func on to drop (delete) the table


def drop_table():
db = connect_db()
cursor = db.cursor()
cursor.execute("DROP TABLE IF EXISTS employees")
db.commit()
db.close()
print("Table dropped successfully!")
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

*THIS IS NOT IMPORTANT FROM EXAM POV {SKIP THIS}


# Func on to handle user choices
def menu():
while True:
print("\n*** MySQL Database Management ***")
print("1. Create Table")
print("2. Insert Record")
print("3. Fetch Records")
print("4. Update Record")
print("5. Delete Record")
print("6. Drop Table")
print("7. Exit")

choice = int(input("Enter your choice: "))

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

new_salary = int(input("Enter New Salary: "))


update_record(e_code, new_salary)
elif choice == 5:
e_code = input("Enter Employee Code to Delete: ")
delete_record(e_code)
elif choice == 6:
drop_table()
elif choice == 7:
print("Exi ng Program...")
break
else:
print("Invalid choice! Please try again.")

# Run the program


menu()

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

You might also like