100%(1)100% found this document useful (1 vote) 527 views14 pagesCS (12th) Mindmaps
quick revision sheet covering all in-syllabus topics for cs class xii
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
CHAPTER-1
PYTHON-REVISION-1
s that can be performed on
the data and the way itis stored in memory.
Number Types
JO Integer: Represents whole numbers without «
decimal point,
Example: age = 25
IO Floating Point: Represents real numbers with a
decimal point.
Example: temperature = 37.5
3 Complex: Represents numbers with areal part and
an imaginary part, written as a+ bj.
Example: 2=2+3}
Boolean Type
IC Boolean: Represents truth values: True or False.
Example: is_valid= True
Sequence Types
IO String: Represents a sequence of characters.
Example: name = “Alice”
IO List: Ordered collection of items. Mutable,
Example: fruits = [‘apple’, ‘banana’, ‘cherry']
IO Tuple: Ordered collection of items. Immutable,
Example: coordinates = (10, 20)
None Type
IC None: Represents the absence of a value.
Example: result = None
[Mapping Type
IO Dictionary: Collection of key-value pairs
Mutable,
Example: person = {‘name’: ‘Alice’, ‘age’: 30}
ab)
agate
Revere)
Cole) TN Fay
SCIENCE
Python Tokens
IG) Python is a high-level, interpreted|
programming language known for its
simplicity and readability. It supports
‘multiple programming paradigms,
including procedural, object-oriented, and
functional programming.
Features of Python
(CI Simplicity: Easy to lear and use.
Readability: Emphasizes clear and concise!
syntax.
Interpreted: Executes code line by line.
(C1 Cross-platform: Runs on various operating]
systems.
IO Interactive Mode: Line-by-line code!
execution inthe interpreter.
IG Script Mode: Runs Python scripts from
start to finish,
Execution Modes
Keywords: Reserved words with special meanings.
G Identifiers: Names for variables, functions, etc.
(Literals: Constants like numbers and strings.
symbols for operations.
tion that can be accessed and manipulated
‘during the execution of a program.
if Conventions:
Variables can include letters, digits, and|Example | Description
ry", | Perform basic Purpose:
ty mathematical 2 [Co Comments in Python are used to exptain
tions code and make it more understandable for
Ta> bx | Compare values others and for future reference.
ay and return True ‘They are ignored by the interpreter duting
or False execution.
Syntax:
[5 Single-tine comments start with #.
IC) Multi-line comments are enclosed in triple
quotes ("" or").
‘pand q’,
“not p
| Python Ce
0°, ‘y | Assign values to.
eS variables
“a= | Perform
=7 arithmetic and
assign in one
statement
s,s not’ | Xisy’, x | Compare object
isnot y’ | identities
“Sin list, | Check if
“6 not in| value exists in a
sequence
IC) Mutable: Data types whose values can be
changed after they are created.
Examples: Lists, Dictionaries.
Immutable: Data types whose values
‘cannot be changed after they are created.
Examples: Numbers, Strings, Tuples.
Data Types
i
a
z
2
:
[5 Operators in programming are symbols NTT
cor keywords that perform operations on
variables and values. They enable you to
‘manipulate data and control the flow of]
‘execution in your programs.
‘Conditional Statements “Iterative Statements
[Statement
ir ite
print |
ifelse fife [| Statement Description
: else | for Loop Executes a block of code for each
item in an iterable (e.g. list, tuple
itelitelse range).
| while Loop Executes a block of code as Jong
pri as the condition is true.
P
> 3
COMPUTER SCIENCECHAPTER-2 COMPUTER
PYTHON-REVISION-II Sela\le 3
(F Lists are ordered collections of tems, which
can be of any type,
Lists are mutable, meaning their elements can
be changed after they are created.
Example: numbers = (1, 2,3, 4, 5)
IO Indexing:
ID Lists in Python are zero-indexed, meaning
the first clement has an index of O.
Example: first clement = numbers)
characters enclosed within either single
quotes ("), double quotes (
quotes (°° op #™ my.
Example: message = “Hello, Worl
Python- :
List methods Gear Gareth
Method Deseription Example
Ten [Returns the number of | length = lenfnumbers) Method Description] — Example
elements in the list. Usage
list() Converts an iterable (like a Jen) Returns the Jen("Python")
string or tuple) into a list. length of the
P,°, 01 string.
‘append. | Adds an element tothe end | numbers append(@)” capitalize) | Converts the
ames of the list, first character to
extend) | Extends the list by appending | numbers exend((, Soper and te
elements from another list, | 8, 9)) Uo lowers.
: Title) Converts the “python
insen() [Inserts an element at a | numbers.insert(0, 0) ;
ae |
ini
er) Converts all "HELLO".
: =
specified position. #10)
1,25 3).495,56)
an)
am
ai =
count) | Returns the number of
‘occurrences of an element.
index) | Returns the index of the first
occurrence of an element.
remove() | Removes the first ocourrencel|
ofa value fom thelist |
‘Pop() Removes and.
element at a
(default is
"hello" upper)
“hello world”.
ccount("!")1 Tupiles in Python are immutable sequences,
‘meaning their elements cannot be changed
‘or modified after the tuple is created. They
ate defined using parentheses () and can)
‘contain any number of elements separated
by commas, Tuples are often used t0 grouP]
related data together.
Example: my_tuple= (1,2, 3,‘
6 Like lists, tuples support indexing and)
slicing to access elements. Indexing starts
at 0 for the first element and continues
sequentially.
Example: print(my_tuple{0]) # Accesses
the first element: 1
Gy Tuples support various operations: Concatenaton
tuples using the + operator.
‘Example: tuptel = (1,2)
tuple2 = G3, 4)
cambined tuple = tuplel + tuple? # Result: (1, 5
Repetition: Replicating tuples using the * operator. M4)
Example: repeated_tuple = (‘a',‘b") * 3
# Result: (‘a",‘b’, ‘a’, 'b’, ‘a', “b")
3 Membership: Checking if an element exists in a tple wy
i
keyword.
‘Example: print(‘a’ in repeated_tuple) # Result: True
Gj Slicing: Extracting portions of @ tuple using slice nay,
[start:end:step].
Example: sliced_tuple = my_tuple{1:4] #
Result: (2, 3. ‘a’
Tuple methods
CoS
—— a
Built-In methods
iccaaaeaasle Diciauarre Method Description ‘Example | Ret
ae cresiny in Pytnos ia sn unordered jen) [Returns the number of elements “Ten (my_ [6
collection of key-value pairs. Itis mutable, in a tuple. tuple)’
meaning you can modify its contents after Tountd) | Retums the number of occurrences | my tuple. |"
rato. Ea ey Ina dionary sate of a specified value in the tuple. | count(a')
ue and immutable (such as strings, i i 5
Se ee aes ate index) [Retums the index of the first|°my tuple. 4
Pap tye eT ‘occurrence of a specified value. | index('b)”
: at Zorted() [Returns a new sorted list from the "sorted
elements of the tuple. (ony_tuple)’ {12,31
ing square brackets []- min] Returns the minimum value in the |'min(@, 1, ['T
Example: employee = { tuple. 4, 5))°
‘name’: “John Doe”, maxQ | Returns the maximum value in the |“max((3, 1, /5
“department”: “HR”
}
print(employee{”
»)
1. Math Module:
(5 Provides access to mathematical functions and constants.
ude sq, eild, floor), pow, fs
1,2, 3,4, 5,5,6,6,7)
:mean(data)) # Outputs: 4,333333333333333
COMPUTER SCIEN?CHAPTER-3
FUNCTIONS
Global variables are accessible from any part of
the program, including functions.
© Changes made to global variables inside
~ function affect their values globally.
Examples: x= 10
‘def my_function(:
print(f"Inside function: x = (x}")
‘my_funetion()
rint(P*Outside function: x
ay)
local to that function, They cannot be accessed
outside of the function or in any other function,
ID Once the function completes execution, the
local variables are destroyed, and their values
are no longer accessible.
Examples: def my_function(:
x= 10 # Local variable
+ print(P"Inside function: x= {x}")
rmy_function)
# print(x) # Error: x is not defined
‘outside the function
[5 The flow of execution refers to the sequence
in which statements re executed in a program,
Functions execute when called, and control
retums to the caller after execution.
/Example:
def greet(name):
print(f"Hello, {name} ")
print(“Start of program”)
sreet(“Alice”)
prini(“End of program”)
0 Positional parameters are passed to @
based on their position in the function cal
‘order of arguments matters, s each a
assigned to its corresponding parameter
on their positions.
Example:
def greet(name, greeting):
Print(f*{greeting}, {name}
sreet(“‘Alice”, “Hi”) # Outputs
[6 Variables defined inside a function are typically
4
COMPUTER
Giell-iNlei=3
Sree
Functions are pre-defined functions
provided by Python. These functions are
ready to use and serve various purposes like
performing operations on data, handling
input/output, and more. Examples of built-in
function:
IC print: Outputs data to the console.
Icy len: Retums the length of an object (e.g.,
string, list),
max0, min: Retums the maximum or
‘minimum value in a sequence.
‘adoog Teq01D,
( Functions defined in modules are functions
created in extemal files or libraries that can
be imported into your Python program. They
extend Python's capabilities by providing
additional functionality.
fExample:
1. math.sqrtQ: Computes the square root of
number (from the math module).
random.randintQ: Generates a random
integer within a specified range (from the
‘Scope of Variable
Functions Defined
in Modules
2.
adoag [e907
co User-defined functions are functions created
by the programmer to perform specific tasks.
Example:
def greet(name):
prini(f"Hello, {name}!”)
# Call the function
sgreet(“Alice”)
aaa
User-Defined
Functions
(Ciparaieters|are variables used in the function
RBGRGbe hile arguments are values passed
ion when itiscalled
(Parameters and
(6 Default parameters have predefined values that
are used when no argument is provided for
those parameters during function call.
JExample:
def greet(name="Guest”):
prini(f"Hello, {name}
‘greet() # Outputs: Hello, Guest!COMPUTER
CHAPTER-4
FILE HANDLING mee
1 Datnisreadable fromatext file using methods
like read(), readline(), and readlines(:
() # Reading entire content
‘with open(‘data.txt’,‘r”) as file:
content = filexread()
print(content)
(i) # Reading line-by-line
with open(‘data.txt’, ‘rs file:
Tine = file.eadline)
while line:
print(line)
line = file readline)
{cece eee ees
Reading from a Text
File
—_——
(J Data can be written a file using the writed|
‘method and appending of data can be done|
file using append() or writelines():
© # Writing toa file
+ with open(‘output.txt’, w’) as file:
« file.wite("Hello, World!\n")
‘© #Appending toa file
+ with open(‘output.ix’, a) as file:
« file. write(*Appending additional
content in”)
‘Types of Files
Gistentlins)
Writing/Appending
Data to a Text File
( The with statement ensures that the file is
properly closed after its suite finishes, even
if'an exception is raised:
« file_path = ‘data.txt
‘© with open(file_path, ‘as file:
# # Perform operations on the file
# data = filexreadO,
2
= print(data) I ae 5
Relative and
Absolute Paths
(6 Opent) funetion ean be|used|(o open tex
-—
Example: Opening a fen file 0
close it using the elo
system resources: |
file.close() # Close
Introduction to Files
location on a disk to store related information Wis wey,
permanent data storage and retrieval.
Files store data persistently, allowing information 1 4!
saved even after the program terminates.
In programming, a file is a
Text File 3)
0 Text files store data in the form of plan tx
which can be human-readable.
Example: .txt files.
Binary File
[Cy Binary files store data in a binary form,
human-readable.
Example: jpg, mp3, .exe files.
CSV (Comma-Separated Values) File
ID CSV files store tabular data (rows ax
columns) in plain text, with each li
representing a row of data.
Example: .csv files.
PE Eeeeeeeereeeececeeeeeeeee en
(0 Relative Path: A relative path specific)
the location of a file relative to the curen}
‘working directory (the directory from whic
Example: data/file.txt, .Jimages/photojpg
Absolute Path: An absolute path specifi
the complete path starting from the rl
directory.
Example (on Unix-like systems):
‘Mrome/user/data/file.txt,
Wwarfwww/htmV/index.html
saareananaaaaaaaareeanenanaeeeeee aaa
_
F Python provides several modes to open tt
file
[Cy «1°: Opens a file for reading. (default moe)
0 ‘r#: Opens a file for both reading
writing.
| ‘w’: Opens a file for writing. ‘Truncate
existing file or creates a new file.
1 ‘w+: Opens a file for reading cand writing
‘Truncates existing file of creates a new file:
0) ‘a’: Opens a file for appending data. Creat
anew file if it does not exist.
[6 ‘a+’: Opens a file for both appending ®|G To read data from a CSV file, you use the
reader() function provided by the esv
1. reader(): Returns a reader object that will
{cturns a writer object responsible
for converting user's data into delimited
sirings on the given file-like object.
2. writerows() Writes multiple rows of data
into the CSV file,
‘Reading & Writing from
___acsy Fite
crane ‘and Closing a
_CSV File
1 To work with CSV files, we open them using,
the open() function and specify the file mode.
Example:
with open(‘data.csv’, ‘w’, newline=”) as file:
1 Always close the file after operations are
complete:
file.close() # Close the file when done
1 Python's. pickle
and deserialization of P
suitable for storing
binary format,
Example:
import pickle
CHEAT SHEET,
File Handling
Seek and Tell’
In Python, the seek() and tell) methods are used}
for file handling:
1. seek(offset, whence): Moves the file pointer
to a specified position. offset specifies
the number of bytes to move, and whence|
indicates the reference position (0 for start, 1
for current position, 2 for end).
2, tell: Retums the current position ofthe file
pointer.
Example:
file = open(‘example.txt’, r”)
file.seek(10)
print(file.tell0) # Outputs: 10
file.closeQ
‘Opening & Closing
(B To open a binary file in Python, you use
the open() function with modes specifically
tailored for binary data:
‘Example: with open(‘data.bin’,‘tb’) as file:
data = filexreadQ)
# Process binary data
1D Always close a file after processing to free up|
system resources:
7 file.close( # Close the file when doneCHAPTER-5 (ol abn
DATA STRUCTURE : STACK
SCIENCE
Expression Evaluation: Backtracking: Helps Function Cail
Used in parsing expressions in algorithms that ‘Management: Manages
(lke converting infix to require backtracking, function cals in
postfix). such as maze solving. programming languages.
‘Use Cases of Stack
Introduction: A stack is a linear]
data structure that follows the Last In| Push: Adds an dena
[First Out (LIFO) principle, where the to the top ofthe siaxk
last element added to the stack is the
first one to be removed. Stacks are Data structure: Stack
used in various applications such as
expression evaluation, syntax parsing,
and backtracking algorithms.
Pop: Removesand
returns the top element
the stack.
Peek/Top: Retuns te
top element ofthe sh
‘without removingit
(optional.
is Empty Checks ft
In Python, a list can be used to stack is empty (option
implement a stack. Here’s how you
can do it:
Implementation of Stack using List
‘The pop() method of alist is used)
remove and retumn the top ele
[of the stack.
Example:
def pop(stack):
if not isEmpty(stack):
return stack pop()
else:
return “Stack is empty”CHAPTER-6 COMPUTER
COMPUTER NETWORK-| ees
+ Sender Device which is capable of sending |
data over & network. Example ome |
roi phone ete
‘Receiver: Device which is capable of
receiving eta fom he network. For example
Data Communication ae
au computer communication, the sender and
Cnimnicion the CORSTEETE swede me owner sais eanenee
Pecan ofData ‘Message: Data ot information that needs to
two fCaiamaicalet be exchanged betwen the sender and the
receiver IT eanbein the form fet number,
image, ai, video ee.
+ Communication mediamedium: Iti the
path through which the mesage waves
betwen sore and destination For example,
2 television cable, lephone able et.
Computer Network-| Channel, Bandwidth, and
Data Transfer Rate
(ia
‘A-computer network :
is eect of iterconnecic| (The range of frequencies that a) (The amount of data
devices that allows them is channel can carry. transmitted per unit of time.
to’corammufeals ad chase’ 1 KH2=1000 Hz 1 Kbps=2" bps=1024 bps
resources. It facilitates is 1 MHz =1000 KHz 100 0000 H2 | | 1 Mbps=2® bps=1024 Kbps
efficient data transfer, ited, )Masured in Hertz (Hz) Kilohertz | | 1 Gbps=2" bps=1024 Mops
resource sharing, and fi ((KH2); orMegahertz (MHz). | Tops=2" bps=1024 Gbps
collaboration among a sau ‘Measured in bits per second
(bps), Kilobits per second
(Kbps), Megabis per second
(Mbps), Gigabits per second
(Gbps), or Terabits per
second (Teps)
‘Evolution of Networking
in the 1960s, the Advanced
data into packels, which are sent
ly and reassembled at the
‘Used in modern computer
and the internet,1. Twisted Pair Cable:
2, Co-msial Cable:
3. Optical Fibre:
‘Guided (Wired) Media
‘© Use: Offers high bandwidth and
| Communication Media
Radio Waves:
Micro Waves
and satellite
Infrared Waves
+ Very high frequency waves.
* Cannot penetrate solid objects
Unguided (Wireless) Media
+ Waves of frequency range 3 KHz- 1 GHz
+ Omni-directional, these waves can move in all directions
‘+ Radio waves of frequency 300 KHz-30 MHz can travel long distance
‘+ These waves are used in AM and FM radio, television, cordless phones.
++ Provide very large information-carrying capacity.
* Description: Consists of pairs of insulated copper wires twisted together
+ Use: Common in telephone networks and local area networks (LANS).
+ Description: Central conductor surrounded by insulating ayers and a metallic shield.
+ Use: Suitable for cable television and high-speed internet.
+ Description: Transmits data using light signals through glass or plastic fibers.
used in long-distance communication.
‘+ Electromagnetic waves of frequency range IGHz-300GHz.
‘+ Unidirectional, can move in only one direction,
‘+ Used in point-to-point communication or unicast communication such as radar
* Electromagnetic waves of frequency range 300GHz-400THz.
Rofey aye clen (tance |
1G (1982): It was used
to transmit only voice calls
2G (1991): Instead of analog
signals, voice calls were transmited
in digital form, thus improving cal
quality
3G (2001): It provided Intemet access via
the same radio towers that provide voice
service to the mobile phone.
Similarly, 4G and 5G mobile
networks were also developed
for higher demand and faster
data,
MAC and IP Address
‘Unlike MAC addresses, IP addresses can change
when a node is moved between networks,
IPv4 is the initial IP address version, a 32+
numeric address written as four numbers separated
by periods. Due to the limited number of IPv4
addresses, IPv6 was introduced as a 128-it
address.
Each MAC address is a 12-digit hexadeciml
numbers (48 bits in length) out of which
first six digits (24 bits) contains Organisation
Unique Identifier (OUD) and the later six digi}
(24 bits) represents the serial number assigned (0
the card by the manufacturer.CHAPTER-7 ees ¥
COMPUTER NETWORK-II SCIENCE ~ Cheat Sheet
Bus Topology Modem
‘+All devices share a single communication line. ‘Network Topologies + Function: Convers signals between analog and
Data is transmited in both directions, but one Network topology refers to digital forms, enabling internet connectivity
Gevice’s temnsmistion does not interfere with the arrangement of different + Usage: Connects devices to ISP for internet acces,
— elements (links, nodes, etc.)
, + Operates: At Layer or Layer 2 of the OST model
Of computer network, Hero| | <-OPetates:AtLayer | or Layer 2 ofthe OS! model)
Siar Topobgy "
ee
«ach deve some ea xn ub or| | [ee aamesoie male Tan ar io Twa Rew Tae
switch. If one device fails, it doesn’t affect the LL card. Facilitates communication within the same
others, and it’s easy to add or remove devices LAN, Utilizes Ethemet protocol for data transfer.
However, the failure ofthe central hub can disrupt See ea
the entire network.
Repeater
Ring Topology «+ Functlon: Strengthens and resends signals to
+ Esch device is connote to exacly two other extend range and combat attenuation.
devices, forming a closed lop. Canin [++ Usage: Used in wireless networks, fiber optics,
« Data travels in one direction around the ing Newileat en Ty bondoaing
{alle of one deve can dirt the ene
newer rea + Operates: At Layer 1 of the OSI model
‘Mesh Topology. Hub
+ Every device is connected to every other device. + Funetion: Connects multiple devices in a LAN,
Offers high redundancy and reliability, as multiple ‘broadcasting data signals from one porttoall others
Peis ect Re ee mney + Types: Active (boosts signal), Passive (just
+ Complex and expensive to implement due to the forwards), Intelligent (management capabilities)
large number of connections.
= + Usage: For simple LAN connections.
‘Tree Topology
‘©A hierarchical structure where devices are
arranged in atre-lke fashion LJ. Function: Connects multiple devices, directing
‘Combines characteristics of star and_ bus data to its destination using MAC eddkesses.
sonnets ‘Types: Unmanaged, managed, smart, Layer 2,
Layer 3, PoE, fied, stackable, modular
|| Usage: For efficient LAN connectivity.
‘Operates: At Layer 2 (traditional) or Layer 3
“ aefyork layer) of the OSI model
‘Switeh
Work
ene
‘Area Covered | Small Area st . jirects data requests between different
(Upto 10m Trelvorks, determining the best path for data
ius) i packets.
Error Rates Lowest fi acu ‘Types: Edge, core, distribution, wireless routers
‘Transmission High Speed (Giemas zi isge: For interet access and. inter-network
Networking Negligible sonteivi.
Cost ® [eOperates: At Layer 3 ofthe OSI model
R45 Connector ateway
+ Funetion: A standard type of 0 [+ Function: Comes diferent networks or systems with different
networking. 1a packets for compatibility
Ethernet cables.
* Characteristics: Typically hase
with twisted pair cables.Cole) U3
SCIENCE
CHAPTER-8
DATABASE CONCEPT
(X database is a structured eal
lof data organized for effcia” —
Introduction. retrieval and manipulation.
Example: A student managen
system for a school
records of students, teachers, ay,
courses.
(a table that stores data in rows (tuples) and columns
(attributes).
fExample: Consider a “Students” table with’
[columns for student_id, name, and age, where each
row represents data fora single student.
Essential for storing ogmizg |
ees Jand. ‘managing large volung
Cofefiler-]} 3} Jof data in various application
such as banking, ‘healthy
JA. characteristic or property of an entity. For education, and ecommerce,
[They ensure data integrin,
example, in a student database, attributes could,
include student ID, name, and age. [Importance and Need for) and security, and _provik
Databases mechanisms fora |
manipulation and retrieval
(A tuple is a single row in a table that contains a
specific instance of data. [A candidate key is a minimal set ¢
[Example: In an “Orders” table, each tuple, attributes that can uniquely identify
represents a single order placed by a customer, tuple within a relation. It can init
containing details such as order_id, customer_id, Candidate _Jone or more attributes.
and order date. [Example: In a “Students” tle
{student id) is a candidate key 6?
[uniquely identifies each student.
Keys in Database
Analtemate key is
a candidate key that
isnot selected as the
primary key.
Example: In the
“Students” table,
{email} could be
an alternate key if
student_id is chosen
as the primary key.CHAPTER-9
STRUCTURED QUERY
LANGUAGE
(Create Database: Creates a new database
inthe SQL server.
Example: CREATE DATABASE
SchoolDB;
(i) Use Database: Specifies the database to|
be used for subsequent SQL queries
Example: USE SchoolDB;
(il) Show Databases: Displays a list of al
databases in the SQL server.
Example: SHOW DATABASES;
() Drop Database: Deletes an existing]
database and all its associated data
permanently.
Example: DROPDATABASE SchoolDB;
(¥) Show Tables: Lists all tables in the|
currently selected database.
Example : SHOW TABLES;
(Wi Create Table: Creates a new table in
the database with specified columns and|
properties.
Example: CREATE TABLE Students (
student_id INT PRIMARY KEY
name VARCHAR(S0),
age INT,
%
(vil) Alter Table: Adds a new column to an
existing table: ALTER TABLE. table_|
name ADD column_name data_type
tables.
Example: SELECT * FROM Tal
characters (including zero ch
1D The_wildcard matches any si
Example: SELECT *
FROM Products
Ceo) ad
‘SCIENCE
‘SQL Commands
and Operations
Structured Query
(lester
‘Equi Join
[CF Anequi-joinis a type of join that combines rows from
two tables based on a matching column.
[CV It uses the equality operator (=) to match rows where
the specified columns have equal values
IC) Example: SELECT *
FROM Employees ¢
JOIN Departments d ON e.department
= ddepartment
(Natural Join
© A type of join that combines rows from two tables
based on columns withthe same name and datatypes.
IO Automatically matches columns with the same
name in both tables without specifying the columns
explicitly,
Example: SELECT *
FROM Employees
doce HEE INATURALZIOIN Devesinensay_
(@ Distinct Clause: Removes duplicate rows from the
result set
Example: SELECT DISTINCT city
FROM Customers;
(Gi) Where Clause: Filters rows based on specified
conditions.
Example: SELECT *
FROM Employees
WHERE department = ‘IT’;
(iif) In Clause: Checks if a value matches any value in a}
list.
FROM Products
WHERE category IN (‘Electronics’,
“Appliances');
en Clause: Filters rows.
ina range of
: SELECT *
FROM Orders
WHERE order_date BETWEEN ‘2023-
(i) Nall Clauses: NULL: In SQL, NULL represents a
‘unknown value. I signifies thatthe value
‘Checks ifa value is NULL.
‘SELECT * FROM Employees WHERE
manager id 1S NULL:CHAPTER-10 ae
INTERFACE OF PYTHON alts
WITH AN SQL DATABASE
7
& Suerte
In SQL queries executed through
Python, %s is commonly used
Jas a placeholder for parameters|
that will be substituted at
execution time. SQL Methods
Example:
sql_query = “SELECT * FROM
Jemployees WHERE department} Using Ss Format
= %s"
department = “IT”
Jcursor.execute(sql_query,
(department,))
We can also use the .format() aed
‘method or f-strings (in thon
3.64) to Sdn sot peal format Method)
|dynamically.
Example:
sqi_query = “SELECT *
FROM employees WHERE| ‘Using format()
lage > {} AND salary > {}”.
ormat(25,40000)
[cursor.execute(sql_query)
Tenet
Casa)
OUT Tel
Database
Performing
asing cursor
J. fetchall: The fetchall() method fetch ,
. executed): The execute() method is used ip
aan SQL statement, ant
commit(): The commit() method is used
‘changes made by the SQL statements tothe,
fetchone(): The fetchone() method fetches ty
row of a query result, retuming a single sequen
None if'no more rows are available
(remaining) rows of a query result, returning ai
. rowcount: ‘The rowcount attribute retime 4
number of rows that were affected bythe lst ex (
operation,
¢
(3 Insert Query: Used to add new rr
into a table.
Example:
ccursorexecute("”
INSERT INTO students (name, age, at
VALUES (“John Doe", 12, ‘6h’)
“y
13 Update Query: Modifies existing ©
records in a table.
Example: Update a row of data
cursorexecute("” |
UPDATE students
SET age™13,grade='7h’
WHERE name= "John Doe |
IC Detete Query: Removes record a
atable,
Example:
Delete a row of data (
cursorexecute("” ¢
DELETE FROM students
WHERE name = ‘John Doe”
oy
IO Select Query and Fetch Dats:
Retrieves data from a table.
‘xample: Select Query
cursorexecute(“SELECT * FROM
employees")
Fetch one row
row = cursor. fetchone()
print(row)
Fetch all rows
rows = cursor fetchall()
for row in rows
print(row) —