100% found this document useful (1 vote)
31 views62 pages

Class Xii Wrap Up Session

The document outlines the syllabus and exam preparation tips for the CBSE Class 12 Computer Science course, covering key topics such as Python programming, MySQL, computer networks, and database management. It emphasizes the importance of understanding programming concepts, creating personalized notes, and practicing exercises to excel in the exam. Additionally, it provides a detailed overview of various programming functions, data structures, and operators relevant to the curriculum.

Uploaded by

Soham Mukherjee
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
100% found this document useful (1 vote)
31 views62 pages

Class Xii Wrap Up Session

The document outlines the syllabus and exam preparation tips for the CBSE Class 12 Computer Science course, covering key topics such as Python programming, MySQL, computer networks, and database management. It emphasizes the importance of understanding programming concepts, creating personalized notes, and practicing exercises to excel in the exam. Additionally, it provides a detailed overview of various programming functions, data structures, and operators relevant to the curriculum.

Uploaded by

Soham Mukherjee
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/ 62

Computer Science (083)

In today's Global World, Computer Science is as important a language as any other. CBSE
Computer Science from Class 11th to Class 12th provides a solid foundation for any future
endeavors you may wish to take, with Computer Science by your side. However the last
barrier remains the CBSE Class 12th Computer Science exam, here are some tips to help
you clear the exam with flying colors.
Class XII (Theory) – Python and MySQL
Duration: 3 hours Total Marks: 70
UNIT WISE SYLLABUS

Unit 1: Computational Thinking and Programming –


● Revision of Python topics covered in Class XI.
● Functions: types of function (built-in functions, functions defined in module, user
defined functions), creating user defined function, arguments and parameters,
default parameters, positional parameters, function returning value(s), flow of
execution, scope of a variable (global scope, local scope)
● Exception Handling: Introduction, handling exceptions using try-except-finally
blocks
● Introduction to files, types of files (Text file, Binary file, CSV file), relative and
absolute paths
> Text file: opening a text file, text file open modes (r, r+, w, w+, a, a+), closing a
text file, opening a file using with clause, writing/appending data to a text file
using write() and writelines(), reading from a text file using read(), readline()
and readlines(), seek and tell methods, manipulation of data in a text file
> Binary file: basic operations on a binary file: open using file open modes (rb,
rb+, wb, wb+, ab, ab+), close a binary file, import pickle module, dump() and
load() method, read, write/create, search, append and update operations in a
binary file
> CSV file: import csv module, open / close csv file, write into a csv file using
writer(),writerow(),writerows() and read from a csv file using reader()
● Data Structure: Stack, operations on stack (push & pop), implementation of stack
using list.
Unit 2: Computer Networks

● Evolution of networking: introduction to computer networks, evolution of networking


(ARPANET, NSFNET, INTERNET)
● Data communication terminologies: concept of communication, components of
data communication (sender,receiver, message, communication media,protocols),
measuring capacity of communication media (bandwidth, data transfer rate),
IP address, switching techniques (Circuit switching, Packet switching)
● Transmission media: Wired communication media (Twisted pair cable, Co-axial
cable, Fiber-optic cable), Wireless media (Radio waves, Micro waves, Infrared waves)
● Network devices (Modem, Ethernet card, RJ45, Repeater, Hub, Switch, Router,
Gateway, WIFI card)
● Network topologies and Network types: types of networks (PAN, LAN, MAN,WAN),
networking topologies (Bus, Star, Tree)
● Network protocol: HTTP, FTP, PPP, SMTP, TCP/IP, POP3, HTTPS, TELNET, VoIP
● Introduction to web services: WWW, Hyper Text Markup Language (HTML),
Extensible Markup Language (XML), domain names, URL, website, web
browser, web servers, web hosting
Unit 3: Database Management

● Database concepts: introduction to database concepts and its need

● Relational data model: relation, attribute, tuple, domain, degree, cardinality, keys
(candidate key, primary key, alternate key, foreign key)

● Structured Query Language: introduction, Data Definition Language and Data


Manipulation Language, data type (char(n), varchar(n), int, float, date), constraints
(not null, unique, primary key), create database, use database, show databases,
drop database, show tables, create table, describe table, alter table (add and
remove an attribute, add and remove primary key), drop table, insert, delete, select,
operators (mathematical, relational and logical), aliasing, distinct clause, where
clause, in, between, order by, meaning of null, is null, is not null, like, update
command, delete command, aggregate functions (max, min, avg, sum, count),
group by, having clause, joins: cartesian product on two tables, equi-join and natural
join
● Interface of python with an SQL database: connecting SQL with Python, performing
insert, update, delete queries using cursor, display data by using connect(),
cursor(), execute(), commit(), fetchone(), fetchall(), rowcount, creating database
connectivity applications, use of %s format specifier or format() to perform queries
Tips
•The key to a successful Computer Science exam is understanding. As majority of the question
paper is based on programming, the only way to score is by having a thorough understanding of
programming.

•Create your own notes for the important terms and concepts after you understand them. The
given notes in a book would be good for learning but for revision your notes will give you the
exact information you need.

•Clear any doubts you have as soon as you can. Use your Class 11th computer science books or
reference books to clear your doubts, but the best solution would be to ask a teacher.

•Practice all the exercises and questions available in your text book.

•Use flashcards to remember definitions .

• Remember to study definitions and their basic applications thoroughly, questions often arise
asking for explanations of topics.
•Create flowcharts to help you understand and remember programming.

•When you practice writing programs try to maintain the required spacing, even if you are
answering only in rough. Getting into the habit of writing according to the proper spacing will
help you .

•If you have time use different color pens/pencils for different areas to help you visually
remember them.

•Revise by practicing programming on a Computer, you will immediately find out where you
stand in terms of how many programs you can successfully write/run.

•Pay attention to details, a single misplaced punctuation mark can ruin an entire answer.

•Practice sample papers/previous year papers to understand the pattern, test your preparation
and identify your weak areas.
OVERVIEW OF TERMS

A quick recap of the basic types : The basic types are collectively called as TOKENS. A
token is the smallest individual unit in a program.
2.2.1 Keywords Keywords have special meaning to the language interpreter These are
reserved words for special purpose. These words cannot be used as normal identifiers.
2.2.2 Identifiers
Identifiers are also called as variables. Variables are memory boxes that hold values or
constants. A variable name must begin with an alphabet or underscore followed by
alphabets or numbers. For example _test ; test ; sum12 are some valid identifiers. We
shall see more about variables after dealing with data types
2.2.3 Constants
Constants are data items whose values cannot be changed. A constant is of numeric or
non-numeric type. Numeric constants consist of only numbers, either whole numbers or
decimal numbers. Integer, floating-point are numeric constants.
2.2.4 Integer Constant
• Integer Constant must have at least one digit and must not contain any fractional part. •
May be prefixed with a + or – sign •
Floating Point Constant
Floating Point Constant is a signed real number. It includes an integer portion, a decimal
point, a fractional portion and an exponent. While representing a floating point constant the
integer portion or the decimal portion can be omitted but never both.

Character Constant
Character constant is a constant that contains a single character enclosed within single
quotes. It can be any character as defined in the character set of Python language
(alphabet, numeral, mathematical, relational or any other special character as part of the
ASCII set). Certain special characters like tab, backspace, line feed, null, backslash are
called as non-graphic character constants. These characters are represented using
escape sequences. Escape sequences are represented using characters prefixed with a
backslash
Operators :
•Unary operators require one operand
•Binary operator requires two operands
•Ternary operator requires three operands
Membership Operators: in and not in .
in : is used when we are checking if it is present in the data structure or not.

lst=[1,2,3,4,5,6] lst=[1,2,3,4,5,6]
for i in lst: i=int(input("enter a number"))
print(i) if i in lst:
print(i,"is present in the list",lst )
Output: Output:
1 enter a number5
2 5 is present in the list [1, 2, 3, 4, 5, 6]
3 >>>
4
5
6
not in: when the value doesn't belong to the data structure.

lst=[1,2,3,4,5,6]
i=int(input("enter a number"))
if i not in lst:
print(i,"is not present in the list",lst )

enter a number8
8 is not present in the list [1, 2, 3, 4, 5, 6]
>>>
== RESTART:
C:/Users/user/AppData/Local/Programs/Python/Python37-32/ppt1.py ==
enter a number5
>>>
Identity Operator : is and not is
Identity operators are used to compare the objects, not if they are equal,
but if they are actually the same object, with the same memory location:

is:
x is y

x=5
y=x
if x is y:
print("True")

output:
== RESTART:
C:/Users/user/AppData/Local/Programs/Python/Python37-32/ppt1.py
==
True
>>>
is not:

x=5
y=5
if x is not y:
print("True")

Output:
== RESTART:
C:/Users/user/AppData/Local/Programs/Python/Python37-
32/ppt1.py ==
>>>

x=5
y=6
if x is not y:
print("True")

Output:
== RESTART:
C:/Users/user/AppData/Local/Programs/Python/Python37-
32/ppt1.py ==
True
String

Function Description
str.lower() Converts all characters in the string to lowercase.
str.upper() Converts all characters in the string to uppercase.
Capitalizes the first character of the string and converts the rest to
str.capitalize()
lowercase.
Converts the first character of each word to uppercase and the rest to
str.title()
lowercase.
str.swapcase() Swaps the case of all characters in the string.
Removes any leading and trailing whitespace (spaces, tabs, newlines)
str.strip()
from the string.
str.lstrip() Removes any leading (left) whitespace from the string.
str.rstrip() Removes any trailing (right) whitespace from the string.
str.replace(old, new) Replaces all occurrences of a substring old with new in the string.
Returns the lowest index of the first occurrence of substring, or -1 if not
str.find(substring)
found.
str.index(substring) Similar to find() but raises a ValueError if substring is not found.
Splits the string into a list of substrings based on whitespace (or a given
str.split()
separator).
Joins the elements of an iterable (e.g., list, tuple) into a string, using the
str.join(iterable)
string as a separator.
String

Returns True if the string starts with the specified prefix, otherwise
str.startswith(prefix)
False.
str.endswith(suffix) Returns True if the string ends with the specified suffix, otherwise False.
Returns True if all characters in the string are alphabetic (letters), otherwise
str.isalpha()
False.
str.isdigit() Returns True if all characters in the string are digits, otherwise False.
Returns True if all characters in the string are numeric characters (including
str.isnumeric()
digits), otherwise False.
str.isspace() Returns True if all characters in the string are whitespace, otherwise False.
str.islower() Returns True if all characters in the string are lowercase, otherwise False.

str.isupper() Returns True if all characters in the string are uppercase, otherwise False.
Returns True if all characters in the string are alphanumeric (letters and
str.isalnum()
digits), otherwise False.
Returns True if all characters in the string are decimal characters, otherwise
str.isdecimal()
False.
Returns the number of non-overlapping occurrences of substring in the
str.count(substring)
string.
Splits the string into a 3-part tuple: before the separator, separator, and after
str.partition(separator)
the separator.
LIST
Function Description
list.append(x) Adds an element x to the end of the list.
Extends the list by appending all elements from the
list.extend(iterable)
iterable (e.g., another list).
list.insert(i, x) Inserts an element x at a specific position i in the list.
Removes the first occurrence of element x from the
list.remove(x)
list. Raises a ValueError if not found.
Removes and returns the element at the specified
list.pop([i]) index i. If no index is provided, it removes and returns
the last item.
list.clear() Removes all elements from the list, leaving it empty.
Returns the index of the first occurrence of element x
list.index(x[, start[, end]])
in the list within the optional start and end range.
Returns the number of times the element x appears in
list.count(x)
the list.
Sorts the list in place (modifies the original list) in
ascending order by default. Optionally, a custom
list.sort(key=None, reverse=False)
sorting function (key) and reverse order (reverse) can
be specified.
list.reverse() Reverses the order of elements in the list in place.
TUPLES

Function Description

len(tuple) Returns the number of elements in the tuple.

Returns the largest element in the tuple


max(tuple)
(works with comparable elements).

Returns the smallest element in the tuple


min(tuple)
(works with comparable elements).

Returns the sum of all the elements in the


sum(tuple)
tuple (works with numeric elements).

tuple(iterable) Converts an iterable (like a list) into a tuple.

Returns True if all elements in the tuple are


all(tuple)
truthy, otherwise False.
Returns True if any element in the tuple is
any(tuple)
truthy, otherwise False.
Returns a new list that contains all elements
sorted(tuple)
of the tuple in sorted order.
TUPLES

Method Description
Returns the number of occurrences of
count(x)
element x in the tuple.
Returns the index of the first occurrence of
index(x) element x. Raises ValueError if x is not
found.

Operation Description
Concatenation (+) Combine two tuples into a new tuple.
Repeat the tuple a certain number of times
Repetition (*)
to create a new tuple.
Create a sub-tuple by slicing the tuple
Slicing
(e.g., tuple[start:end]).
Dictionary

Category Method/Function Description


Methods clear() Removes all items from the dictionary.
copy() Returns a shallow copy of the dictionary.
fromkeys(seq, value) Returns a new dictionary with keys from seq and values set to value.
get(key, default) Returns the value for key if key exists, otherwise returns default.
items() Returns a view object displaying a list of dictionary's key-value pairs.
keys() Returns a view object displaying all the keys in the dictionary.
Removes the item with key and returns its value. If key is not found, returns
pop(key, default)
default.
popitem() Removes and returns a random (key, value) pair from the dictionary.
setdefault(key, default) Returns the value of key, inserting key with default value if key is absent.
Updates the dictionary with key-value pairs from another dictionary or an
update(other)
iterable.
values() Returns a view object displaying all the values in the dictionary.

Functions dict() Creates a new dictionary.


len(dictionary) Returns the number of key-value pairs in the dictionary.
del Deletes a specific key-value pair from the dictionary.
in Checks if a key exists in the dictionary (key in dict).
not in Checks if a key does not exist in the dictionary (key not in dict).
Type conversions:
Implicit conversions: refers to data type changes brought about in expressions by the
compiler. For example consider the following snippet:
float f = 7.6; int x = f;
The value stored in the variable x is 7, as float is converted to int. The compiler does this
conversion automatically.
Rules for implicit conversion :
Consider a term, having a pair of operands and an operator. The conversions takes place as
follows :
1. If one operand is of type long double , then the other value is also converted to long
double.
2. If one operand is of type double, then the other value is also converted to double.
3. If one of the operands is a float, the other is converted to a float.
4. If one of the operands is an unsigned long int, the other is converted to unsigned long int.
5. If one of the operands is a long int, then the other is converted to long int.
6. If one of the operands is an unsigned int, then the other is converted to an unsigned int.
Loops in Python

for Loop:

The for loop in Python is used to iterate over a sequence (list, tuple, string) or other
iterable objects. Iterating over a sequence is called traversal.
Generally this loop is used when know the number of times to iterate to get the desired
result.
Syntax :
for <var> in sequence:
Body of the for loop
else:
Statement
Here <var> is a variable that is used for iterating over a <sequence>. On every iteration it
takes the next value from <sequence> until the end of sequence is reached.
•.

while Loop in Python

A while loop in Python is used to repeatedly execute a block of code as long as a


specified condition evaluates to True. The loop continues until the condition becomes
False.
Syntax
while condition:
# Code to be executed
# Block of code
condition: An expression that is evaluated to True or False. The loop continues as long
as this condition is True.
•Block of code: The code that runs repeatedly as long as the condition is True.

Points to remember:

•If the condition is True initially, the loop will execute at least once.
•If the condition is False initially, the loop will not execute at all.
•You can exit the loop prematurely using the break statement.
•The else block can be used after a while loop and will execute if the loop terminates without
hitting a break statement
Jump Statement

Jump statements in python are used to alter the flow of a loop by either terminating a loop or skip a part of a loop.
1. break
2. continue
3. pass
Jump Statements
1. break Statement in Python is used to terminate the loop and controls goes to next line after the loop body. If a break
statement is inside a nested loop, it will terminate the innermost loop and continue the outer loop.
Example:
for i in range(1,11):
if (i==5):
break
print(i)
2. continue Statement in Python is used to skip all the remaining statements in the loop and move control back to the top of
the loop.
Example:
for i in range(1,7):
if (i==5):
continue
print(i)
3. pass Statement in Python does nothing. pass statement is used when you create a method that you don't want to
implement later.
Example:
for i in range(0,7):
if (i==5):
pass
else:
print(i)
Functions

A function is a set of statements that take inputs, do some specific computation and
produces output. The idea is to put some commonly or repeatedly done task together and
make a function, so that instead of writing the same code again and again for different
inputs, we can call the function.
define a function using the def keyword, followed by the function name and
parentheses ()

def greet():
print("Hello")

After performing the task functions can return values also. If a function returns a
value then it needs to be called from a variable, so that the value returned is stored
in the variable.
def sumnum(x,y):
c=x+y
num1=int(input("enter a number"))
num2=int(input("enter a number"))

print(result)
Scope of variables
The part of the program where a variable can be used is known as Scope of variable

•Global Scope :With global scope, variable can be used anywhere in the program .

•Local Scope : With local scope, variable can be used only within the function / block that
it is created .

x = 10
def modify_global():
global x # Declaring the variable 'x' as global
x = 20 # Modify the global variable
print("Before modifying:", x) # Output: 10
modify_global()
print("After modifying:", x) # Output: 20
Types of Arguments

Functions with No Parameters: A function that does not take any arguments.
def say_hello():
print("Hello, World!")

say_hello()
Default argument : A default argument is a function parameter that has a default value
provided to it. If the user does not supply a value for this parameter, the default value will
be used. If the user does supply a value for the default parameter, the user-supplied value is
used .

def greet(name="Guest"):
print(f"Hello, {name}!")

greet("Alice") # Output: Hello, Alice!


greet() # Output: Hello, Guest!
Functions with Parameters: A function that takes one or more arguments.
def add_numbers(a, b):
return a + b

result = add_numbers(10, 5)
print(result) # Output: 15

Positional arguments are the arguments passed to a function in the correct


positional order. These arguments are mapped to the parameters in the function based
on their position.
# Define the function
def greet(name, age):
print(f"Hello, {name}! You are {age} years old.")

# Call the function with positional arguments


greet("Alice", 25)
greet("Bob", 30)

# Output:
# Hello, Alice! You are 25 years old.
# Hello, Bob! You are 30 years old.
Functions with Variable Length Arguments: You can define functions that accept a variable
number of arguments using
*args for positional arguments and
**kwargs for keyword arguments- Keyword Argument: keyword arguments (often referred
to as kwargs) are arguments passed to a function by explicitly specifying the name of the
parameter and its corresponding value. This allows you to pass arguments in any order, as long
as you specify the parameter name.
def greet(*names):
for name in names:
print(f"Hello, {name}!")
greet("Alice", "Bob", "Charlie")
# Output:
# Hello, Alice!
# Hello, Bob!
# Hello, Charlie!
def display_info(**info):
for key, value in info.items():
print(f"{key}: {value}")
display_info(name="Alice", age=25)
# Output:
# name: Alice
# age: 25
Modules

Module is a file containing a set of functions which can be included in our application.
Python provide inbuilt standard modules, like math, random etc.

Ways of Importing module in a python code:


1. import statement .By using import statement we can add module(s) in a python file.
import math
math.sqrt(4)

2. from ….import…. By using this statement we can import specific functions from the
module.
from math import sqrt,pow
print(sqrt(4))

Math Module
The math module is a standard module in Python and is always available. To use
mathematical functions under this module, we have to import the module using import
math statement. (pi, e, sqrt(), ceil(), floor(), pow(), fabs(), sin(), cos(), tan())
Using Random Module
 Python has a module namely random that provides random – number generators. Random number
means any number generated within the given range.
 To generate random number in Python we have to import random module
 3 most common method to generate random number in python are :
 random() function
 randint(a,b) function
 randrange(a,b) function

•Use random() when you need a random float between 0.0 and 1.0.
•Use randrange() when you want a random integer from a specified range, with control over the
step size.

•Use randint() when you need a random integer within a specified range, including both endpoints.
Statistics Module
This module provides functions for calculating mathematical statistics of numeric (Real- valued)
data.
statistics.mean(data)
Return the sample arithmetic mean of data which can be a sequence or iterator.

statistics.median(data)
Return the median (middle value) of numeric data, using the common “mean of middle two”
method. If data is empty, StatisticsError is raised.

statistics.mode(data)
Return the most common data point from discrete or nominal data. The mode (when it exists) is
the most typical value, and is a robust measure of central location . If data is empty, or if there is
not exactly one most common value, StatisticsError is raised.
File Handling

•Text Files are simple and suitable for text-based data.


•Binary Files are for raw data and require specific handling.
•CSV Files are a structured text format, ideal for tabular data, commonly used for data
interchange between applications like databases and spreadsheets.
File Pointers
In Python, file pointers are used to keep track of the current position in the file when reading or
writing. The seek() and tell() methods are used to manipulate and retrieve the file pointer's
position.
seek() and tell() Methods in Python
•seek(offset, whence): Moves the file pointer to a specific location in the file.
•tell(): Returns the current position of the file pointer.

# Example of using seek() to move the file pointer


with open('example.txt', 'r') as file:
# Read the first 10 characters
print(file.read(10)) # Reads first 10 characters
# Move the pointer back to the beginning of the file
file.seek(0)
print("Pointer position after seek:", file.tell()) # Get current position (should be 0)
# Read next 5 characters
print(file.read(5)) # Reads next 5 characters
Introduction:
Exception handling is a mechanism that allows a program to respond to runtime errors
(exceptions) in a controlled way, instead of crashing or producing incorrect results. When
an error occurs, an exception is raised, and the program can handle it using specific code
blocks to recover gracefully.
The primary goal of exception handling is to improve the program's robustness and
reliability by allowing the program to continue executing even when an error occurs.
Key Concepts:
1. Exception: An event that disrupts the normal flow of a program. For example,
division by zero, file not found, or accessing an invalid array index.
2. Try Block: Code that might raise an exception is placed inside a try block. The
program attempts to execute the code in the try block.
3. Except Block: If an exception occurs in the try block, the program jumps to the
except block to handle the error.
4. Finally Block: Code inside the finally block will always execute, regardless of
whether an exception occurred or not. It is used to clean up resources or perform tasks
that must happen after the try-except process (like closing files or releasing locks).
Example:
try:
# Code that may raise an exception
num1 = int(input("Enter a number: "))
num2 = int(input("Enter another number: "))
result = num1 / num2
print(f"Result: {result}")
except ZeroDivisionError:
# Handle division by zero error
print("Error: Cannot divide by zero.")
except ValueError:
# Handle invalid input (non-integer input)
print("Error: Please enter valid integers.")
finally:
# This block will always execute
print("Execution completed.")
Explanation of the Example:
1. try block: The program asks for two inputs from the user and attempts to perform division.
2. except blocks: The first except block catches a ZeroDivisionError (if the user tries to divide by zero).
o The second except block handles ValueError (if the user inputs non-numeric data).
Text File
•Opening Files: Use open() to open a file in different modes (r, w, a, etc.).
•Reading Files: Use read(), readline(), or readlines() to read the file contents.
When we use read() ,data is read as string, readline –string, readlines- list of strings
•Writing to Files: Use write() or writelines() to write data to a file.
•Appending to Files: Use 'a' mode to add content to an existing file.
•Closing Files: Use close() or the with statement to automatically handle file closing.

Binary File
•Binary files store data as bytes, unlike text files that store human-readable strings.
•Use the 'rb' and 'wb' modes for reading and writing binary files, respectively.
•Use seek() and tell() for random access in binary files.
•Always close files after use to release system resources, preferably using the with statement.
•We need to import pickle module.
•Pickling (Serialization): Converting a Python object into a byte stream.
•Unpickling (Deserialization): Converting a byte stream back into a Python object.
CSV File

•Reading CSV Files: Use csv.reader() for reading data as rows (lists) and csv.DictReader() for
reading data as dictionaries.
•Writing CSV Files: Use csv.writer() to write data as rows (lists) and csv.DictWriter() to write
data as dictionaries.
•Custom Delimiters: Specify a delimiter such as ; if needed using the delimiter parameter.
•Handling Newlines: Always use newline='' when opening files for writing to avoid extra
newlines being added.
•import csv module.

Note: When data is read from a csv file ,it is read as a string. So, while checking for int
values you should use int() as data is a string value.
Feature Text Files Binary Files CSV Files
Contains tabular data with
Contains raw data in a
File Type Contains readable text data. values separated by
specific binary format.
commas.
.bin, .dat, or no specific
File Extension .txt (common) .csv
extension
Data is represented as
Data is stored as plain text Data is stored as bytes strings in a tabular
Data Representation
(strings). (binary format). structure, typically with
commas separating values.
Open with Open with Open with open('file.csv',
Reading and Writing
open('filename.txt', 'r') or 'w' open('filename.bin', 'rb') or 'r') or 'w' (text mode) or
Mode
(text mode). 'wb' (binary mode). using csv module.
Read using methods like Read using read() to fetch Read using csv.reader()
Reading Data
read(), readlines(). raw bytes. from the csv module.
Write using methods like Write using write() for raw Write using csv.writer()
Writing Data
write(), writelines(). bytes. from the csv module.
Typically stored in plain
Data is typically encoded Data is not encoded (raw
Encoding text, can be encoded as
(e.g., UTF-8). byte data).
UTF-8 or ASCII.
Name,Age,Location\n
Hello World! (text- Alice,30,New
\x48\x65\x6c\x6c\x6f
File Content Example based, human- York\nBob,25,LA
(byte data).
readable). (comma-separated
values).
For handling complex For storing structured
For storing and handling data that needs to be tabular data, such as
Use Case
text-based data. read/written as bytes spreadsheets or
(e.g., images, audio). databases.
Easy to edit and read
Easy to read and edit Not human-readable, with standard
Ease of Use
(human-readable). requires specific tools. spreadsheet software or
Python libraries.
csv module
Standard Python Standard Python
(csv.reader(),
Python Libraries functions (open(), functions (open(),
csv.writer()) or pandas
read(), write()) read(), write())
for more advanced use.
import csv; with
Example f = open('file.txt', 'r') f = open('file.bin', 'rb') open('file.csv', 'r') as f:
reader = csv.reader(f)
Stack

A stack is a data structure in which all the insertion and deletion of data / values are
done at one end using list . The elements of the list can be either list, tuple, dictionary or
a single element.

It follows LIFO(Last In First Out) property.


Insertion / Deletion in stack can only be done from top.
Insertion in stack is also known as a PUSH operation.
Deletion from stack is also known as POP operation in stack.

Note:
One should check whether the stack is empty or not
MySQL is a widely used relational database management system (RDBMS), and it
supports a wide range of commands for interacting with databases. These
commands are typically divided into several categories based on their function, such
as Data Definition Language (DDL), Data Manipulation Language (DML), Data
Control Language (DCL), and Transaction Control Language (TCL).
Command Description Example
CREATE DATABASE Creates a new database. CREATE DATABASE mydatabase;

Deletes a database (including all its


DROP DATABASE DROP DATABASE mydatabase;
tables).
CREATE TABLE users (id INT, name
CREATE TABLE Creates a new table in a database. VARCHAR(50));

DROP TABLE Deletes an existing table. DROP TABLE users;

ALTER TABLE users ADD age INT;


Modifies an existing table, such as adding ALTER TABLE USERS MODIFY CLASS
ALTER TABLE
or dropping columns. VARCHAR(3);
ALTER TABLE USERS DROP AGE;

Displays the structure of a table


DESCRIBE / EXPLAIN DESCRIBE users;
(columns, data types, constraints).
SHOW TABLES Lists all tables in the current database. SHOW TABLES;

SHOW DATABASES Lists all databases SHOW DATABASES;


Data Manipulation Language (DML) Commands
DML commands are used to manipulate data stored in the tables.
Command Description Example
Retrieves data from one or more
SELECT SELECT * FROM users;
tables.
INSERT INTO users (name, age)
INSERT INTO Inserts new data into a table.
VALUES ('Alice', 25);
Updates existing records in a UPDATE users SET age = 26
UPDATE
table. WHERE name = 'Alice';
DELETE FROM users WHERE
DELETE Deletes records from a table.
age < 20;

In MySQL, the Cartesian product is produced using the CROSS JOIN operation, which returns the
Cartesian product of two or more tables. This operation combines each row from the first table with
every row from the second table, resulting in a set of all possible pairs (or tuples, if more tables are
involved).
Cartesian Product in MySQL is where the number of rows in the result is the product of the number
of rows in the two tables involved. For example, if Table1 has 3 rows and 2 columns and Table2 has 4
rows and 3 columns, the result will have 3x4=12 rows and 4+3=5 columns.
Key Type Description Purpose

Ensures each record in a table is unique and


A field or a set of fields that uniquely
Primary Key cannot have NULL values. Only one primary
identifies each record in a table.
key is allowed per table.

A field or set of fields in one table that refers Establishes and enforces a link between two
Foreign Key
to the Primary Key in another table. tables, maintaining referential integrity.

A constraint that ensures all values in a


Ensures uniqueness for specified columns
column or a set of columns are unique
Unique Key (can accept NULL, but only one NULL value
across all rows in a table, except for NULL
per row).
values.

A key that consists of more than one Used when a single column is not enough to
Composite Key
column. uniquely identify a record.

A set of one or more columns that can Any column(s) that can serve as a primary
Candidate Key uniquely identify a record in a table, but is key (a table can have multiple candidate
not necessarily the primary key. keys).

A candidate key that is not chosen to be the Refers to any candidate key not selected as
Alternate Key
primary key. the primary key.
Constraint Type Description Purpose Example
Ensures that the column(s)
Guarantees that each row is
uniquely identify each row in a
PRIMARY KEY unique and non-null in the PRIMARY KEY (id)
table and cannot contain NULL
specified column(s).
values.
Maintains referential integrity
A column (or combination of
between two tables. Ensures that
columns) in one table that refers FOREIGN KEY (department_id)
FOREIGN KEY the values in the foreign key
to the PRIMARY KEY of another REFERENCES departments(id)
column exist in the referenced
table.
table.
Prevents duplicate values in the
Ensures that all values in a
specified column(s). A column
UNIQUE column or set of columns are UNIQUE (email)
with a UNIQUE constraint can
unique across all rows.
accept NULL values.
Forces a column to always CREATE TABLE employees (id INT
Ensures that a column cannot
NOT NULL contain a value, disallowing NOT NULL, name VARCHAR(100)
contain NULL values. NOT NULL)
NULL.
Specifies a default value for a
Assigns a default value to a
column when no value is
DEFAULT column if no value is specified age INT DEFAULT 18
provided during an insert
during insertion.
operation.
SELECT TABLE_NAME FROM USER_TABLES;
select [distinct] {*, column [alias], …} from table;

select [distinct] {*, column [alias],…}


from table
[where condition(s)];

•and returns true if both conditions are true.


•or returns true if one condition is true.
•not returns true if condition is false.
•The =, <>, <, <=, >, >= operators have higher precedence over logical
operators.
•not operator has a higher precedence over and operator which has a higher
precedence over or.
•The rules of precedence can be over-ridden by using parentheses.
Using Between, In, Like and Is Null Operators:
The BETWEEN, IN and LIKE operators are also comparison
operators.
between : Between two values (both inclusive)
in (list) : Match any of a list of values.
like : Match a character pattern.
is null : Is a null value.

Using Like with wild cards


•The like operator is used to perform wild card searches ( e.g. *.exe)
•The search condition can contain literal characters or numbers.
•You can use % or _ wild card characters
•% denotes zero or many characters
•_ denotes one character
•You can combine pattern matching characters ( _ % )
•You can use the ESCAPE identifier to search for ‘%’ or ‘_’
•The escape character can be anything (it only has to be specified)
Distinct clause
The keyword Distinct is used to suppress duplicate values.

Arranging table in Ascending / Descending order using Order By


clause
•The rows can be sorted using ORDER BY clause.
asc : Ascending order (default)
desc : Descending order
•Null values are displayed last for ascending order.
•Null values are displayed first for descending order.
•The order by clause is always the last line of the select clause.
•You can sort a column that is not on the column list.
The syntax of the select statement with order by clause is as follows:
select [distinct] {*, column [alias],…}
from table
[where condition(s)]
[order by {column, expr, alias} asc / desc];
Multi-Row Functions
Multiple row functions operate on a group of rows and return a single
row per group. Multiple row functions are also known as Group
functions or Aggregate functions.
The commonly used multi-row / group functions are:
count()
sum()
avg()
max()
min()
Note:
•min( ), max( ), count( ) can work on Character, Date, or Number type
values.
•sum( ), avg( ) only work on numeric values.
•Use distinct to suppress duplicate values.
•Use all for all values (default).
•All group functions except count( ) ignore null values.
MULTI-ROW FUNCTIONS / GROUP FUNCTIONS / AGGREGATE FUNCTIONS.
SYNTAX USE
COUNT(COLUMN) RETURNS THE COUNT OF VALUES
SUM(COLUMN) RETURNS THE SUM OF ALL VALUES
AVG(COLUMN) RETURNS THE AVERAGE OF ALL VALUES
MAX(COLUMN) RETURNS THE MAXIMUM VALUE
MIN(COLUMN) RETURNS THE MINIMUM VALUE
GROUP BY CLAUSE
The Group By clause is used to group data together. You can use the group by clause to divide
a table into smaller groups.
The syntax of the select statement with group by clause is as follows:
select column group_function(column)
from table
[where condition(s)]
[group by group_by_expr]
[having group condition]
[order by column asc / desc];
The following are the guidelines for group by clause:
•Column aliases cannot be used.
•By default, columns are sorted in ascending order. You can use the order by clause to change
the order.
•Individual columns cannot be used in the select statement unless that column appears in group
by clause
Joins
An Equi Join is a type of INNER JOIN where the condition used to combine the tables is
based on equality. In other words, an Equi Join retrieves records that have matching values in
the columns being compared between the two tables.

Example
select name,age,marks
from student,result
where student.regno=result.regno

A Natural Join is a type of JOIN operation in SQL where the tables are automatically joined
based on all columns that have the same name and data type in both tables. Unlike an INNER
JOIN, where you explicitly define the join condition, a Natural Join implicitly uses all the
columns with the same name for matching rows between the tables.
select * from r1 natural join r2;
+---------+----------+----------+
| regno | sname | marks |
+---------+----------+----------+
| 1 | abc | 45 |
| 2 | xyz | 55 |
+---------+-- -----+-- -----+
2 rows in set (0.01 sec)
Networking

In networking, protocols are standardized rules and procedures that determine how
data is transmitted over a network. These protocols ensure that devices on a network can
communicate with each other reliably and securely. Protocols govern aspects such as
data formatting, error handling, flow control, and routing.
Protocol Description
Hypertext Transfer Protocol is used for transferring web pages over the internet. It operates at the application
HTTP
layer and is the foundation of web browsing.
Secure version of HTTP using SSL/TLS encryption to secure data during transfer. It ensures that communication
HTTPS
between browsers and servers is secure.
File Transfer Protocol is used for transferring files between a client and a server. FTP supports both active and
FTP
passive modes for file transfer.
Domain Name System resolves human-readable domain names (like www.example.com) to IP addresses used for
DNS
routing traffic.
SMTP Simple Mail Transfer Protocol is used for sending emails from a client to a server or between mail servers.

Post Office Protocol version 3 is used to retrieve emails from a mail server to a client. It downloads emails and
POP3
deletes them from the server.
Internet Message Access Protocol allows users to retrieve and manage emails on the server without downloading
IMAP
them, keeping them stored on the server.
Transmission Control Protocol ensures reliable, ordered, and error-checked delivery of data between devices. It is
TCP
commonly used with IP for Internet communication (TCP/IP).
Internet Protocol is responsible for addressing and routing data packets across networks. IPv4 and IPv6 are the
IP
most common versions.
SSH Secure Shell is a cryptographic protocol used for securely accessing remote devices over a network.
A protocol used for remote communication over a network. It is less secure than SSH and is not recommended for
Telnet
use in modern networks.
Type of Unguided
Description Frequency Range Applications
Media
Electromagnetic waves AM/FM radio, television
used for long-range broadcasting, mobile
Radio Waves 3 kHz to 300 GHz
communication, including networks, Wi-Fi, wireless
broadcasting. LANs.
Satellite communication,
High-frequency radio
point-to-point
Microwaves waves that require line-of- 1 GHz to 300 GHz
communication, radar
sight communication.
systems, telecom.
Electromagnetic waves Remote controls, short-
used for short-range range data transfer (e.g.,
Infrared (IR) 300 GHz to 400 THz
communication, often in between devices), IR
line-of-sight. peripherals.
Li-Fi (Light Fidelity),
Visible Light Uses light waves in the
high-speed wireless
Communication visible spectrum for 430 THz to 770 THz
communication over short
(VLC) communication.
distances.
High-security
Higher frequency than
communication,
Ultraviolet (UV) visible light; specialized 30 PHz to 1.0 eV
specialized medical or
wireless communication.
industrial systems.
Uses microwaves and
Global communication,
Satellite radio waves for Varies (L-band, S-band,
GPS systems, satellite TV,
Communication communication with Ku-band, Ka-band, etc.)
weather forecasting.
satellites in space.
Common
Network Topology Description Advantages Disadvantages
Applications
Limited cable
All devices are length, difficult to Small networks,
connected to a Easy to implement troubleshoot, temporary
Bus Topology
single central cable and cost-effective. performance networks, and
(the bus). degrades with legacy systems.
heavy traffic.
Home networks,
All devices are Easy to install and
Failure of the
office networks,
connected to a manage, easy to central hub/device
Star Topology and most modern
central device (hub, troubleshoot, causes network
enterprise
switch, or router). scalable. disruption.
networks.
Devices are Failure in one
Legacy networks,
connected in a Good performance device or
token ring
Ring Topology closed loop; data with predictable connection can
networks, and
travels in one data flow. disrupt the whole
small office setups.
direction. network.
Every device is Highly redundant, Expensive to Large enterprise
connected to every fault-tolerant, and implement and networks, data
Mesh Topology
other device in the provides high maintain, complex centers, and critical
network. security. cabling. systems.
Hybrid topology
Scalable and Dependent on the Large networks,
that combines
hierarchical root node; failure campus networks,
Tree Topology characteristics of
structure, easy to can affect the entire and enterprise-wide
star and bus
manage. network. systems.
topologies.
Network Device Description Function Common Applications
A device that converts digital Modulates and demodulates Internet access (e.g., DSL,
Modem data into analog signals and signals for internet access overcable modem), broadband
vice versa. telephone lines or cable. connections.
A hardware component that Provides a physical interface Computers, servers,
Ethernet Card (NIC) allows a device to connect to a for communication over workstations, and any devices
wired network. Ethernet networks. requiring wired connectivity.
A type of connector used for Wired networking (e.g.,
Connects devices to wired
RJ45 Ethernet cables (Cat5, Cat6) in connecting computers to
networks via Ethernet cables.
networking. switches or routers).
A device that amplifies or Extends the range of signals in Long-distance connections,
Repeater regenerates signals to extend a network, compensating for wireless network extension,
the range. attenuation. and signal boosters.
A basic networking device that Sends data packets to all Small networks, legacy
Hub broadcasts data to all connected devices connected to it systems, or when cost is a
devices. (unintelligent device). major concern.
A device that connects devices Forwards data only to the Local Area Networks (LANs),
Switch within a network and forwards specific device it is intended offices, data centers, and
data based on MAC addresses. for. enterprise networks.
A device that forwards data Routes data between different Internet connection sharing,
Router packets between different networks (e.g., from LAN to connecting multiple networks
networks. WAN). (home and business networks).
A device that connects two Translates and forwards data Connecting networks with
Gateway different networks using between networks with different protocols (e.g., IPv4
different protocols. different protocols. to IPv6).
Enables wireless Laptops, smartphones, tablets,
A device that allows a device to
Wi-Fi Card (Wireless NIC) communication with access and any device requiring
connect to wireless networks.
points (Wi-Fi networks). wireless connectivity.
Aspect Circuit Switching Packet Switching
Breaks data into smaller packets and
Establishes a dedicated communication path between two
Description sends them independently over the
devices for the entire duration of the communication session.
network.
Connection Connectionless (packets travel
Dedicated connection (constant path is reserved).
Type independently).
Less efficient, as the path is reserved even when no data is More efficient, as network resources
Efficiency
transmitted. are used dynamically.
Data Data is divided into packets, which may
Continuous stream of data once the connection is established.
Transmission take different routes.
Requires time to establish a circuit before communication Minimal setup time, as data packets are
Setup Time
begins. sent immediately.
Can experience delays, packet loss, or
Reliability High reliability due to the dedicated connection.
out-of-order delivery.
Bandwidth Poor, as the dedicated path remains unused if there is no data High, as the network bandwidth is
Utilization being transmitted. shared among multiple users.
Suitable for data transmission like
Suitability Best for real-time communication such as voice calls. emails, web browsing, and file
transfers.
Traditional telephone networks, PSTN (Public Switched
Example Internet, LANs, VoIP, email systems.
Telephone Network).
Lower, as resources are used on
Higher, due to the need to reserve dedicated resources for the
Cost demand, and no dedicated channels are
entire duration.
required.
Less scalable, as establishing dedicated connections for many Highly scalable, as packets can be
Scalability
users can be resource-intensive. routed over shared paths.
Network Protocol Full Name Description Port Number Common Applications
Protocol used for Web browsing, accessing
HyperText Transfer
HTTP transmitting web pages and Port 80 websites, retrieving web
Protocol
content over the internet. pages.
Used for transferring files File uploads/downloads, file
Port 21 (Control), Port 20
FTP File Transfer Protocol between client and server sharing, website
(Data)
over a network. management.
A protocol used for direct
Dial-up internet
communication between
PPP Point-to-Point Protocol No specific port connections, VPNs, and
two devices, often over
serial communications.
serial connections.
Simple Mail Transfer Protocol for sending email Sending emails, email
SMTP Port 25
Protocol between servers. server communication.
The fundamental suite of
General networking,
Transmission Control protocols that defines how Various (Port 80, 443 for
TCP/IP Internet communication,
Protocol/Internet Protocol data is transmitted across HTTP/HTTPS)
web browsing.
networks.
Used for retrieving email
from a server to a client, Email retrieval from servers
POP3 Post Office Protocol 3 allowing email to be Port 110 (used by email clients like
downloaded and stored Outlook).
locally.
A secure version of HTTP,
Secure web browsing,
HyperText Transfer encrypts data using
HTTPS Port 443 online banking, e-
Protocol Secure SSL/TLS to protect privacy
commerce sites.
and security.
A protocol used for
Telecommunication accessing remote computers Remote management of
TELNET Port 23
Network over a network, typically in servers, network devices.
command-line mode.
A protocol for transmitting
Internet telephony, voice
voice communications over Various (SIP typically uses
VoIP Voice over Internet Protocol calls, video calls (e.g.,
IP networks, often used for Port 5060)
Skype, Zoom).
phone calls.
Term Description Purpose/Use

A system of interlinked hypertext Provides access to information through


WWW (World Wide Web)
documents accessed via the internet. websites, services, and resources.

A standard markup language used to create Structures content on the web (headings,
HTML (HyperText Markup Language)
and design web pages. paragraphs, links, images).

A flexible text format for representing Used for data exchange between systems,
XML (Extensible Markup Language)
structured data. especially in web services.
Allows users to access websites using
A human-readable address that
Domain Names easy-to-remember names (e.g.,
corresponds to an IP address.
www.example.com).

A reference or address used to access Specifies the location of a resource (e.g.,


URL (Uniform Resource Locator)
resources on the web. https://www.example.com).

A collection of web pages and related Provides content, services, and resources
Website
content under a single domain. for users via the internet.

Software used to access and view websites Displays content (HTML, images, etc.)
Web Browser
on the internet. from websites (e.g., Chrome, Firefox).

A software or hardware that serves web Hosts websites, processes requests, and
Web Server
pages to users over the internet. delivers content to web browsers.
A service that provides the infrastructure Stores website files and makes them
Web Hosting
for hosting websites. accessible to users over the internet.
Points to remember while attempting case study based question:

1. Server is placed in the building where there are maximum number of computers
2. Cable layout to be drawn keeping in mind the cost of cable.
Minimum distance connection to be considered.
3. For connection with hilly regions we always use radiowaves.
4. To secure network firewall should be installed.
5. Remote login is Telnet ,Anydesk etc.
CBSE SAMPLE
PAPER WITH
MARKING SCHEME
ComputerScience-SQP.pdf
ComputerScience-MS.pdf

You might also like