100% found this document useful (1 vote)
502 views32 pages

701oswaal CBSE 12th Revision Notes - Computer Science

The document provides revision notes on Python basics including its history, qualities, identifiers, data types, operators, expressions, conditional statements, and iteration constructs. Python was created in late 1980s and is based on ABC and Module 3 languages. It uses indentation for code blocks and supports dynamic typing, multiple assignment, comments with # and triple quotes. Key data types include numbers, sequences, sets and maps. Common operators include arithmetic, relational, logical, assignment, bitwise and identity operators. Conditional statements include if, if-else and if-elif statements. Iteration constructs allow repetitive execution using for, while and nested loops.
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)
502 views32 pages

701oswaal CBSE 12th Revision Notes - Computer Science

The document provides revision notes on Python basics including its history, qualities, identifiers, data types, operators, expressions, conditional statements, and iteration constructs. Python was created in late 1980s and is based on ABC and Module 3 languages. It uses indentation for code blocks and supports dynamic typing, multiple assignment, comments with # and triple quotes. Key data types include numbers, sequences, sets and maps. Common operators include arithmetic, relational, logical, assignment, bitwise and identity operators. Conditional statements include if, if-else and if-elif statements. Iteration constructs allow repetitive execution using for, while and nested loops.
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/ 32

UNIT-I : Computational Thinking and Programming - 2

CHAPTER-1
REVISION OF THE BASICS OF PYTHON
Topic-1
Python Basics
Revision Notes
• Python was created by Guido van Rossum in late ‘1980s’ (Released in 1991) at National Research Institute in
the Netherland. Python got its name from a BBC comedy series – “Monty Python’s Flying Circus”. Python is
based on two programming languages:
(i) ABC language
(ii) Module 3
Some qualities of Python based on the programming fundamentals are given below:
Ø Interactive Mode: Interactive mode, as the name suggests, allows us to interact with OS. It executes the code
by typing in Python shell.
Ø Script Mode: In script mode, we type Python program in a file and then use interpreter to execute the content
of the file.
Ø Indentation: Blocks of code are denoted by line indentation, which is rigidly enforced.
Ø Comments: A hash sign (#) that is not inside a string literal begins a single line comment. We can use triple
quoted string for giving multiple-line comments.
Ø Variables: A variable in Python is defined through assignment. There is no concept of declaring a variable
outside of that assignment. Value of variable can be manipulated during program run.
Ø Dynamic Typing: In Python, while the value that a variable points to has a type, the variable itself has no strict
type in its definition.
Ø Static Typing : In static typing, a data type is attached with a variable when it is defined first and it is fixed.
Ø Multiple Assignment: Python allows you to assign a single value to several variables simultaneously.
For example: a = b = c = 1
a, b, c = 1, 2, “john”
Ø Token : The smallest individual unit in a program is known as a Token or a lexical unit.
Ø Identifiers : An identifier is a name used to identify a variable, function, class, module, or other object. An iden-
tifier starts with a letter A to Z or a to z or an underscore ( _ ) followed by zero or more letters, underscores, and
digits (0 to 9).
Ø Python does not allow punctuation characters such as @, $, and % within identifiers. Python is a case sensi-
tive programming language. Thus, Value and value are two different identifiers in Python.
Here are following identifiers naming convention for Python:
Ø Class names start with an uppercase letter and all other identifiers with a lowercase letter.
Ø Starting an identifier with a single leading underscore indicates by convention that the identifier is meant to be
private.
Ø Starting an identifier with two leading underscores indicates a strongly private identifier.
Ø If the identifier also ends with two trailing underscores, the identifier is a language-defined special name.
• Reserved Words(Keywords) : The following list shows the reserved words in Python v3.0 or later
2 ] Oswaal CBSE Chapterwise & Topicwise Revision Notes, COMPUTER SCIENCE, Class – XII

Python Keyword List

False None True and as assert async (v3.5 or


later)
await (v3.5 or later) break class continue def del elif
else except finally for from global if
import in is lambda nonlocal not or
pass raise return try while with yield

These reserved words may not be used as constant or variable or any other identifier names. All the Py-
thon keywords contain lowercase letters only except False, None and True which have first letter capital.

• Literal/ Values : Literals (Often referred to as constant value) are data items that have a fixed value.
Python allows several kind of literals as String literals, Numeric literals, Boolean literals, special literal
None, literal Collections

 ata Types : Data type is a set of values and the allowable operations on those values. Python has a great
•D
set of useful data types. Python’s data types are built in the core of the language. They are easy to use and
straight forward.

DATA TYPES

NUMBERS SEQUENCES SETS MAPS

int long float complex string list tuple dictionary

• Numbers can be either integers or floating point numbers.

• A sequence is an ordered collection of items, indexed by integers starting from 0. Sequences can be
grouped into strings, tuples and lists.

Ø Strings are lines of text that can contain any character. They can be declared with double quotes.

Ø Lists are used to group other data. They are similar to arrays.
Ø A tuple consists of a number of values separated by commas.
• A set is an unordered collection with no duplicate items.
• A dictionary is an unordered set of key value pairs where the keys are unique.
• Operator : Operators are special symbols which perform some computation. Operators and operands form an
expression. Python operators can be classified as given below :
Python operator types

Operators

Arithmetic Relational Logical Assignment Bitwise Identity Membership


operators operators operators operators operators operators Operator

+ < or = & is in
– > and += | is not not in
* <= not –= ^
/ >= *= -
% != /= <<
** == %= >>
// //=
**=
&=
|=
∧=
>>=
<<=

• Expressions : An expression in Python is any valid combination of operators, literals and variables.
Oswaal CBSE Chapterwise & Topicwise Revision notes, COMPUTER SCIENCE, Class – XII [ 3

Topic-2
Conditional Statements

Revision Notes
• A conditional is a statement which is executed, on the basis of result of a condition.
• If conditional in Python have the following forms.
(a) Plain if
(b) The if-else conditional
Syntax:
if <conditional expression>:
test False
expression Body of else [statements]
?
else:

True
[statements]

Body of if

(c) The if-elif conditional statement


if <conditional expression>:

. Statement

[statements]
elif <conditional expression>:

. statement
.
.
else:

. statement
.
.
[statements]

(d) Nested if
•• A nested if is an if which is inside another if ’s body or elif ’s body or else’s body.
•• Storing conditions – Complex and repetitive conditions can be named and then used in if statements.

Topic-3
Iteration Constructs

Revision Notes
•The iteration statements or repetition statements allow a set of instructions to be performed repeatedly.
•Python provides three types of loops
(a) Counting loops repeat a certain number of times e.g. for

(b) Conditional loops repeat until a certain thing happens e.g. while.

(c) Nested loops.

4 ] Oswaal CBSE Chapterwise & Topicwise Revision Notes, COMPUTER SCIENCE, Class – XII

•Loop Constructs in Python


We will learn about different types of Python looping statements. In Python, we have different types of loops like
For Loop, While Loop, and Nested For Loop with their subtypes, syntax, and examples.

while for
loops loops

Phython

Loops Nested
loops

•Types of loop constructs in Python


• Python for loop
• Python while loop
• Python loop control statements
• Nested for loop in Python
1.Python WHILE Loop
A while loop in Python iterates till its condition becomes False. In other words, it executes the statements under itself
while the condition it takes is true.
while loop
Syntax

while <logical Expression>:

Condition
False loop body

True

Block of Code

When the program control reaches the while loop, the condition is checked. If the condition is true, the block of code
under it is executed.
Remember to indent all statements under the loop equally. After that, the condition is checked again. This continues
until the condition becomes false. Then the first statement, if any after the loop is executed.
e.g.
>>> a=3
>>> while(a>0):
  print(a)
  a-=1
Output
3
2
1
a.An Infinite Loop
Be careful while using a while loop. Because if you forget to increment the counter variable in Python, or write flawed
logic, the condition may never become false. In such a case, the loop will run infinitely, and the conditions after
the loop will starve. To stop execution, press Ctrl+C. However, an infinite loop may actually be useful.
b.The else statement for while loop
A while loop may have an else statement after it. When the condition becomes false, the block under the else statement
is executed. However, it doesn’t execute if you break out of the loop or if an exception is raised.
e.g.
>>> a=3
>>> while(a>0):
  print(a)
  a-=1
  else:
  print(“Reached 0”)
Output
3
2
1
Reached 0
In the following code, we put a break statement in the body of the while loop for a==1. So, when that happens, the
statement in the else block is not executed.
Oswaal CBSE Chapterwise & Topicwise Revision notes, COMPUTER SCIENCE, Class – XII [ 5
e.g.
>>> a=3
>>> while(a>0):
  print(a)
  a-=1
  if(a==1):
   break;
  else:
  print(“Reached 0”)
Output
3
2
c. Single Statement while
Like an if statement, if we have only one statement in while loop’s body, we can write it all in one line.
e.g.
>>> a=3
>>> while a>0: print(a); a-=1;
Output
3
2
1
You can see that there were two statements in while loop’s body, but we used semicolons to separate them. Without the
second statement, it would form an infinite loop.
2.Python FOR Loop
Python for loop can iterate over a sequence of items. The structure of a for loop in Python is different than that in C++
or Java. That is, for(int i=0;i<n;i++) won’t work here. In Python, we use the ‘in’ keyword.
for loop

Item for False


sequence

True

Block of Code

>>> a = 1
>>> for a in range(3):
  print(a)
Output
1
2
If we wanted to print 1 to 3, we could write the following code.
>>> for a in range(3):
  print(a+1)
Output
1
2
3
a.The range() function
This function yields a sequence of numbers. When called with one argument, say n, it creates a sequence of numbers
from 0 to n-1.
>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
We use the list function to convert the range object into a list object. Calling it with two arguments creates a sequence
of numbers from the first to the second.
>>> list(range(2,7))
[2, 3, 4, 5, 6]
6 ] Oswaal CBSE Chapterwise & Topicwise Revision Notes, COMPUTER SCIENCE, Class – XII

You can also pass three arguments. The third argument is the interval.
>>> list(range(2,12,2))
[2, 4, 6, 8, 10]
Remember, the interval can also be negative.
>>> list(range(12,2,-2))
[12, 10, 8, 6, 4]
•Jump Statements Python offers two jump statements-break and continue to be used within loops to jump out of loop
iterations.
• break statement It terminates the loop it lies within. It skips the rest of the loop and jumps over to the statement
following the loop.
• continue statement Unlike break statement, the continue statement forces the next iteration of the loop to take
place, skipping any code in between.
• Nested Loops A loop may contain another loop in its body, this inner loop is called nested loop. But in a nested
loop, the inner loop must terminate before the outer loop.
e.g.
for i in range(1,6):
for j in range (1,i):
print(“*”,)

Topic-4
Idea of Debugging
Revision Notes
• An error or a bug is anything in the code that prevents a program from compiling and running correctly.
• There are three types of errors
Compile Time errors occur at compile time.
These are of two types :
(i) Syntax errors occur when rules of programming language are misused.
(ii) Semantics errors occur when statements are not meaningful.
Run Time errors occur during the execution of a program.
Logical Errors occur due to programmer’s mistaken analysis of the error.
To remove logical errors is called debugging.

Topic-5
List, Tuples and Dictionary
Revision Notes
List
• A list is a standard data type of Python that can store a sequence of values belonging to any type.

• The lists are depicted through square brackets.

• These are mutable (i.e. modifiable), you can change elements of a list in place.
• Lists store a reference at each index.
• We can index, slice and access individual list elements.
• len (L) returns the number of items in the list L.Membership operators in and not in can be used with list.
• To join two lists use `+’ (concatenation) operator.
• L [start: stop] creates a list slice with starting index as start till stop as stopping index but excluding stop.
Oswaal CBSE Chapterwise & Topicwise Revision notes, COMPUTER SCIENCE, Class – XII [ 7
• List manipulation functions are
append(), insert(), extend(),sort(), remove(), reverse() and pop().
Tuples
•• Tuples are immutable Python sequences, i.e. you cannot change elements of a tuple in place.
•• Tuples’ items are indexed.
•• Tuples store a reference at each index.
•• Tuples can be indexed sliced and its individual items can be indexed.
•• len (T) returns count of tuple elements.
•• Tuple manipulation functions are: len(), max(), min(), and tuple().
Dictionaries
•• Dictionaries in Python are a collection of some key-value pairs.
•• These are mutable and unordered collection with elements in the form of a key : value
pairs that associate keys to values.
•• The keys of dictionaries are immutable type and unique.
•• To manipulate dictionaries functions are : len(), clear(), has_key(),items(), keys(), values(),
update().
•• The membership operators in and not in work with dictionary keys only.

Topic-6
Sorting Algorithm

Revision Notes
• Sorting means arranging the elements in a specified order i.e. either ascending or descend-
ing order.
• Two sorting techniques are
(i) 
Bubble Sort – It compares two adjoining values and exchange them if they are not in
proper order.
(ii) Insertion Sort – Suppose an array A with n elements A[1], A[2],…..A[N] is in memory.
The insertion sort algorithm scans A from A[1] to A[N] inserting each element A[x] into
its proper position in the previously sorted subarray A[1], A[2]…….A[x-1]

Topic-7
Strings in Python
Revision Notes
• Strings in Python are stored as individual character in contiguous location, with two way index for each
location.

• Strings are immutable and hence item assignment is not supported.

• Following operations can be used on strings.


(1) Concatenation `+’
(2) Replication `*’
(3) Membership in and not in
(4) Comparison Operators ==, ! =, <, >, < =, > =
8 ] Oswaal CBSE Chapterwise & Topicwise Revision Notes, COMPUTER SCIENCE, Class – XII

• Built in functions
ord() – returns ASCII value of passed character.
chr() – returns character corresponding to passed ASCII code
• String slice refers to a part of the string, where strings are sliced using a range of indices
Syntax : string [n:m] slice the string.

Topic-8
Python modules
Revision Notes
• Any Python file can be referenced as a module. Modules can define functions, classes and variables that you
can reference in other Python by files via the Python command line interpreter.
• Modules are accessed by using the import statement. A module is loaded only once, regardless the number
of times it is imported.
Syntax Import module_name
Mathematical functions
• Mathematical operations can be performed by imported the math module. Different types of mathematical
functions:
(i) Sqrt() : find the square root of a specified expression
(ii) pow() : compute the power of a number
(iii) fabs() : Returns the absolute value of x.
Random Functions
• Python offers random module that can generate random numbers. Different Random functions are as fol-
lows
(i) random() : Used to generate a float random number less than 1 and greater than or equal to 0.
(ii) Choice() : Used to generate 1 random number from a container.
Statistics Module
• To access Python’s statistics functions, we need to import the functions from the statistics module.
Some statistics functions are as follows:
(i) Mean() : Returns the simple arithmetic mean of data which can be a sequence or iterator.
(ii) Median() : Calculates middle value of the arithmetic data in iterative order.
(iii) Mode() : Returns the number with maximum number of occurrences.

CHAPTER-2
FUNCTIONS
Revision Notes
Ø The act of partitioning a program into individual components is called `Modularity’.
Ø A module is a separately saved unit whose functionality can be reused. A Python module has the .py exten-
sion.
Ø A Python module can contain objects like docstrings, variables, constants, classes, objects, statements, func-
tions etc.
Ø The Python modules that come preloaded with Python are called “standard library modules”.
Oswaal CBSE Chapterwise & Topicwise Revision notes, COMPUTER SCIENCE, Class – XII [ 9
Ø A function is a named block of statements that can be invoked by its name.
Ø Python can have three types of functions i.e., built-in functions, functions in modules and user-defined
functions.
Ø The docstrings are useful for documentation purpose.
Ø Python module can be imported in a program using import statement.
Ø There are two forms of import statements :
(i) import < module name >
(ii) from < module name> import < object >
Ø The built-in functions of Python are always available, one needs not import any module for them.
Ø The math module of Python provides mathematical functionality.
Ø sys.stdin is the most widely used method to read input from the command line or terminal.
Ø The command line sys.argv arguments is another way that we can grab input, and environment variables
can also be used from within our programs.
Ø The basic I/O (Input/Output) functions are input() and print() respectively.
Ø One of the most useful tools available in Python is the print() function. This simply allows the program to
display or print data for the user to read. For example :
red=’Hi, how are you?’
print (red)
Output Hi, how are you?
Ø Python has an input function which lets you ask a user for some text input. In Python 2, you have a built-in
function raw_input(), whereas in Python 3, you have input() for inputting by user. The syntax is :
mydata = input(‘Prompt :’)
print(mydata)
Output: Prompt :
Ø In Python, a number of mathematical operations can be performed with ease by importing a module named
“math” which defines various functions which makes our task easier.
• ceil(x): Returns the ceiling of x as a float, the smallest integer value greater than or equal to x.
• floor(x) : Returns floor of x as a float, the largest integer value less than or equal to x.
• fabs(x): Returns the floating point absolute value of x.
Ø exp(x): Return e**x
Ø log(x,(base)): With one argument, returns the natural logarithm of x (to base e).
With two arguments, returns the logarithm of x to the given base calculate as log(x)log(base)
Ø log10(x): Returns the base-10 logarithm of x. This is usually more accurate than log(x,10).
Ø pow(x, y) : Returns x raised to the power y. In particular, pow(l.0, x) and pow(x, 0.0) always return 1.0, even
when x is a zero or a NaN. If both x and y are finite, x is negative, and y is not an integer then pow(x, y) is
undefined, and raises ValueError.
Ø sqrt(x): Returns the square root of x.
Ø cos(x): Returns the cosine of x radians.
Ø sin(x): Returns the sine of x radians.
Ø tan(x): Returns the tangent of x radians.
Ø degrees(x): Converts angle x from radians to degrees.
Ø radians(x): Converts angle x from degrees to radians.
Ø A function is a block of organized and reusable code that is used to perform a single, related action. Func-
tions provide better modularity for your application and a high degree of code reusability.
10 ] Oswaal CBSE Chapterwise & Topicwise Revision Notes, COMPUTER SCIENCE, Class – XII

Ø Function blocks begin with the keyword def followed by the function name and parentheses ( ).
Ø Any input parameters or arguments should be placed within these parentheses. You can also define param-
eters inside these parentheses.
Ø The first statement of a function can be an optional statement - the documentation string of the function or
docstring
Ø The code block within every function starts with a colon (:) and is indented.
Ø The statement return [expression] exit a function, optionally passing back an expression to the caller. A
return statement with no arguments is the same as return None.
Ø Defining a function only gives a name, specifies the parameters that are to be included in the function, a
structure the blocks of code.
Ø The scope of a variable determines the portion of the program where you can access a particular identifier.
There are two basic scopes of variables in Python :
1. Global variables
2. Local variables
Ø Variables that are defined inside a function body have a local scope, and those defined outside have a global
scope.

Functions

Built-in Modules User-defined

Ø Built-in functions: These are the functions that are always available in Python and can be accessed by a
programmer without importing any module.
Ø Examples of Some Built-in Functions
(i) print() : It prints objects to the text stream file.
(ii) input() : It reads the input, converts it to a string and returns that.
(iii) sorted() : Returns a new sorted list from the items in iterable.
(iv) bool() : Returns a boolean value i.e., True or False.
(v) min() : Returns the smallest of two or more arguments.
(vi) any() : Returns True if any element of the iterable is True.
Ø String Functions
(i) partition() : It splits the string at the first occurrence of the given argument and returns a tuple contain-
ing three parts.
(ii) join() : It takes a list of string and joins them as a regular string.
(iii) split() : It splits the whole string into the items with separator as a delimeter.

Ø Modules: It is a file containing Python definitions and statements. We need to import modules to use any
containing part before separator, separator parameter and part after the separator if the separator parame-
ter is found in the string of its function or variable in our code.
Ø Examples of Some Module Functions
(i) fabs() : It returns the absolute value of a number.
(ii) factorial() : This method finds the factorial of a positive integer.
(iii) random() : It produces an integer between the limit arguments.
Oswaal CBSE Chapterwise & Topicwise Revision notes, COMPUTER SCIENCE, Class – XII [ 11

(iv) today() : This method returns the current date and time.
(v) search() : This function searches the pattern inside the string.
(vi) capitalize() : It returns the copy of string in capital letters.
Ø User-Defined Functions: User defined functions are those that we define ourselves in our program and
then call them wherever we want.
Ø Parameters : These are the values provided in the parenthe­ses in the function header when we define the
function

Ø Arguments : These are the values provided in function call/invoke statement.


Ø Function Arguments: You can call a function by using the following types of formal argments:
• Required arguments / Positional arguments
• Keyword arguments
• Default arguments
• Variable-length arguments

Ø Required arguments are the arguments passed to a function in correct positional order.
Ø Keyword arguments are related to the function calls. When you use keyword arguments in a function call,
the caller identifies the arguments by the parameter name.
Ø A default argument is an argument that assumes a default value, if a value is not provided in the function
call for that argument.
Ø All variables in a program may not be accessible at all locations in that program. This depends on where you
have declared a variable or the scope of variable
Passing different objects as an arguments
You can send any data types of argument to a function as string, number, list, dictionary etc., and it will be
treated as the same data type inside a function.
e.g. List as an argument
def fun(Fruit);
for i in Fruit;
print(i)
Food = [“Mango”, “Cherry”, “Grapes”, “Banana”]
fun(Food)
Output
Mango
Cherry
Grapes
Banana

CHAPTER-3
FILE HANDLING
Revision Notes
Ø Files are used to store huge collection of data and records permanently.
Ø Many applications require large amounts of data. In such situation, we need to use some devices such as
hard disk, compact disk etc, to store the data.
Ø Need for a Data File
12 ] Oswaal CBSE Chapterwise & Topicwise Revision Notes, COMPUTER SCIENCE, Class – XII

• It is a convenient way to deal with large quantities of data.


• To avoid input of data multiple times during program execution.
• To share data between various programs.
Ø Types of files
• Text files store information in ASCII or Unicode characters. In text file, each line of text is terminated, (de-
limited) with a special character known as EOL (End of Line) character.
• Binary files are just a file that contains information in the same format in which the information is held in
memory, i.e., the file contains that is returned to you is raw. In binary file, there is no delimiter for a line.
• CSV (Comma Separated value) files are a common file format for transferring and storing data. The ability
to read, manipulate and write data to and from CSV files using Python is a key skill to master for any data
scientist or business analysis.
Ø Access modes specify the type of operations to be performed on the opened file.
Ø read(), readline() and readlines() methods are available for reading data from the file.
Ø write() and writelines() are used for writing data in the file.
Ø pickle module is used in serialization of data. This allows us to store data in binary form in the file.
Ø dump and load functions are used to write and read data from file.
Ø The open() function creates a file object which would be utilized to call other methods associated with it.

Syntax :
file_object=open(filename[ access_mode],[ buffering])
Here is the parameter details:
Ø filename: The file name argument is a string value that contains the name of the file that you want to access.
Ø access_mode: The access_mode determines the mode in which the file has to be opened i.e., read, write,
append, etc. A complete list of possible values is given below in the table. This is optional parameter and the
default file access mode is read (r).
File Opening Modes

Modes Description
r Opens a file for reading only in text format. The file pointer is placed at the beginning of the file. This is
the default mode.
rb Opens a file for reading only in binary format. The file pointer is placed at the beginning of the file. This
is the default mode.
r+ Opens a file for both reading and writing. The file pointer will be at the beginning of the file.
rb+ Opens a file for both reading and writing in binary format. The file pointer will be at the beginning of
the file.
w Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a new
file for writing.
wb Opens a file for writing only in binary format. Overwrites the file if the file exists. If the file does not
exist, creates a new file for writing.
w+ Opens a file for both writing and reading. Overwrites the file if the file exists. If the file does not exist,
creates a new file for reading and writing.
wb+ Opens a file for both writing and reading in binary format. Overwrites the file if the file exists. If the file
does not exist, creates a new file for reading and writing.
a Opens a file for appending. The file pointer is at the end of the file if the file exists. That is, the file is in
the append mode. If the file does not exist, it creates a new file for writing.
ab Opens a file for appending in binary format. The file pointer is at the end of the file if the file exists. That
is, the file is in the append mode. If the file does not exist, it creates a new file for writing.
a+ Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The
file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.
Oswaal CBSE Chapterwise & Topicwise Revision notes, COMPUTER SCIENCE, Class – XII [ 13

ab+ Opens a file for both appending and reading in binary format. The file pointer is at the end of the file
if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for read-
ing and writing.
Ø Buffering: If the buffering value is set to 0, no buffering will take place. If the buffering value is 1, line buff-
ering will be performed while accessing a file. If you specify the buffering value as an integer greater than 1,
then buffering action will be performed with the indicated buffer size. If negative, the buffer size is the system
default (default behaviour).

Ø The file object attributes: Once a file is opened and you have one file object, you can get various information
related to that file. Here is a list of all attributes related to file object:

AttributeS Description
file.closed Returns true if file is closed, false otherwise.
file.mode Returns access mode with which file was opened.
file.name Returns name of the file.
file.softspace Returns false if space explicitly required with print, true otherwise.
Ø file () : This is same as open ().
Ø Random Access : There are two functions that allow us to access a file in a non-sequential or random mode.
• tell() : It tells us the position of the file pointer.
• seek() : It moves the file pointer to the position specified.
Ø Functions
(a) read () : syntax: <file handle>.read([n])
It reads at most n bytes and returns the read bytes as string. If `n’ is not specified it reads the entire file.
(b) readline () : syntax: <file handle>.readline ([n])
It reads a line of input, and returns it in the form of a string.
(c) readlines () : syntax: <file handle>.readlines ()
It reads all lines and returns them in a list.
(d) write () : syntax: <filehandle>.write (str1)
It writes string str1 to file referenced by <file handle>
(e) writelines () : syntax: <file handle>.writelines (L).
It writes all strings in list L as lines to file referenced by <file handle>
(f) flush () : syntax: <file object>.flush()
It forces the writing of data on disc that is still pending in output buffer.
(g) Importing sys module lets you read/write from the standard input/output device using sys.stdin.read ()
and sys.stdout.write().
(h) split () function splits a line in columns. It returns columns as items of a list.
(i) rename () function is used to rename a file existing on the disk.
syntax: os.remane(<current_file_name>,<new_file_name>)
(j) remove () function is used to delete a file existing on the disk.
syntax: os.remove(<file_name>)
(k) os.path.join () is used to assemble directory names into a path.
(l) os.path.split () is used to split off the last path component.
(m) os.path.splittext() is used to split file name into primary name and extension.
(n) os.path.exists () function check if a path actually exists.
14 ] Oswaal CBSE Chapterwise & Topicwise Revision Notes, COMPUTER SCIENCE, Class – XII

Ø Absolute File Path : It describes how to access a given file or directory staring from the root of the file system.
Ø Relative File Path : It is interpreted from the perspective your current working directory.
Reading CSV files with CSV
Reading from a CSV file is done using the reader object. The CSV file is opened as a text file with Python’s built
in open() function, which returns a file object. This is then passed to the reader,

which does the heavy lifting.


Import CSV
With open(“Employee.txt”) as CSV_file:
CSV_reader = CSV.reader (CSV_file, delimiter = ‘,’)
line _count = 0
for row in CSV_reader:
if line_count = = 0:
print (f ’ column names are {“,”.join(row}’)
line_count + = 1
else :
print (f ‘\t{row [0]} works in the {row[1]}
department, and was born in {row[2]}.’)
line_count + = 1
Print (f ’Processed {line_count} lines.’)
Optional Python CSV reader Parameters
The reader object can handle different styles of CSV files by specifying additional parameters, some of
which are shown below:

Ø Delimiter specifies the character used to separate each field. The default is the comma (‘,’).
Ø quatechar specifies the character used to surround fields that contain the delimiter character. The default is
a double quote (‘ “ ‘).
Ø Escapechar specifies the character used to escape the delimiter character, in case quotes are not used. The
default is no escape character.
Writing CSV Files with CSV
You can also write to a CSV file using a writer object and the write_row() methods:
Import CSV
With open (‘Employee_file.CSV’, mode = ‘w’) as Employee_file:
Employee_writer = CVS.writer (Employee_file, delimiter
= ‘,’ quotechar = ‘ “ ‘ quoting = CSV. Quote_Minimal)
Employee_writer.writerow([‘Rahul’ , Manger ’ , ‘April’])
Employee_writer.writerow([‘Neha’ , ‘IT’ , ‘June’])

CHAPTER-4
USING PYTHON LIBRARIES
Revision Notes
Ø Python has packages for directories and modules for files.
Oswaal CBSE Chapterwise & Topicwise Revision notes, COMPUTER SCIENCE, Class – XII [ 15
Ø As our application program grows larger in size, we place similar modules in one package and different
modules in different packages.
Ø A python package can have subpackages and modules.
Ø A directory must contain a file named __init__.py in order for and Python to consider it as a package.

Ø Modules can be imported using dot (.) operator.


Ø dir( ) is used to find out names that are defined inside a module.
Ø The names that begin with an __(underscore) are default Python attributes associated with the module.
Ø __name__ attribute contains the name of the module.
Ø Interpreter looks for a package or module in a list of directories defined in sys.path.
Ø While using the import syntax for packages, the last attribute must be a subpackage as a module, it should
not be any function or class name.
Ø import <package_name> statement doesn’t put any of the modules in the package into the local namespace.
Ø __all__ is a list of all modules that should be imported when the statement is executed.
Ø Packages can contain nested subpackages to arbitrary depth.
Ø A module in one subpackage can reference objects in a sibling subpackage.

Ø ... refers to a package one level up.


Ø A Python library’s top-level directories or modules are those .py files that are in one of the direc-
tories in Python path, rather than one of those directories or subdirectories.
Ø .pyc is a file with the name same as other Python files and contains a form of the program that can
be loaded and sum faster than the plain text source code.
Ø .pyc file is recreated every time .py file is edited.

CHAPTER-5
DATA STRUCTURES
Topic-1
List

Revision Notes
 A data structure is an organized group of data of different data types which can be processed as a single unit.
Data Structure

Static Dynamic

Array Union Structure Linear Non-linear

Tree Graph

Stock Queue Linked


list

 Lists are the container which store the heterogeneous elements of any type. Lists are mutable which means
they can be modified after creation. You can easily add and remove elements from a list.
 In Python, you can create different types of list. Some of them are described below:
(i) Empty list: This type of list does not contain any element. This list is equivalent to 0 or ”.

(ii) Mixed data types list: This type of list contains different data types. Elements in mixed data types list are

type1 of integer, string etc.
16 ] Oswaal CBSE Chapterwise & Topicwise Revision Notes, COMPUTER SCIENCE, Class – XII

e.g. l = [ 12, ‘are’, ‘xyz’, –67]


(iii) Long lists: In Python, you can create long list which contain many elements that may be different or same.
e.g. l1 = [25, 42, 43, 73, –44, ‘Neha’, ‘abc’, 2.5, 4.4, ‘xyz’, 35]
 Creating list from existing sequence
List can be created from an existing sequence such as tuples, string etc. Elements of list will be represented
individually separated by comma.
Syntax:
listName = list (Sequence)
e.g. >>> l = list (‘PROGRAM’)
>>> l
Output
[‘P’, ‘R’, ‘O’, ‘G’, ‘A’, ‘M’]
 Accessing lists
• Like strings, lists are accessed by index number
• With the help of index number, you can access the individual elements from the list. Two types of indexing are
used to access the elements: positive indexing and negative indexing.
• Index number 0 represents the first element of the list, 1 represents the second element and so on. It is called
positive indexing.
• Index number –1 represents the last element of the list, –2 represents the second last element and so on. It is
called negative indexing.
 Traversing a list
Traversing a list is a process to iterate the particular elements of a list. With the help of traversing, you
can iterate all or particular elements of list.
There are two ways to traverse a list as follows:
• Using FOR loop: FOR loop allows to iterate or traverse all the elements of the list.

• Using FOR loop with RANGE function : If you want to traverse specified elements of list, you must

use FOR loop with RANGE function.
 List Operations
In Python, some basic operations can be formed on lists as follows:
• Concatenate lists: Lists can be concatenated in Python with the help of concatenate operator (+).

• Replicating lists: Lists can be replicated in Python with the help of replicate operator (*).

• Slicing: It is the process to extract the sub part of the list. In Python, indexing is used for slicing the

list.
Syntax: listname [start: stop]
 Working with lists
Various operations can be performed on lists as appending, updating, deleting etc.
• Appending elements to a list: In Python, you can add individual elements to an existing list. For this,

append() method is used.
Syntax: listName. append (element)
• Updating elements to a list: Lists are mutable which can be modified you can update or change an

element in list using index number.
Syntax: ListName (index) = value
• Deleting elements from a list: Elements can be deleted from a list. For this, del keyword is used in
Python.
Syntax: del listName [IndexNumber]
 List Method
There are many methods to manipulate a list in Python. Some of them are as follows:
Oswaal CBSE Chapterwise & Topicwise Revision notes, COMPUTER SCIENCE, Class – XII [ 17

(i) extend() This method is used to add multiple elements to a list.


Syntax: list1. extend (list2)
This method is used to add element to a list but at spec-
ified
(ii) insert() index number.
Syntax: listName.insert(indexNumber, element)

(iii) remove() This method is used to remove the element which is


passed as an argument.
Syntax listName.remove(value)
(iv) reverse() This method is used to reverse the elements of a list
Syntax: listName.reverse()
This method is used to arrange the elements in ascend-
ing order in a list.
(v) sort() Syntax: listName.sort()

Topic-2
Stacks

Revision Notes
 A stack is a linear data structure implemented in LIFO (Last In First Out) manner.
 Insertions and deletions both occur only at one end known as TOP.
 Removing data from stack is called POP.
 Adding data into stack is called PUSH.
 It is a dynamic data structure i.e. stack can grow and shrink.
 Peek refers to inspecting the value at stack’s top without removing it.
 Overflow refers to condition when one tries to PUSH an item in stack that is full.
 Underflow refers to condition when one tries to POP an item from an empty stack.
 Prefix notation refers when operator is placed before its operands.
 Postfix notation refers when operator is placed after its operands e.g. ab+.

UNIT-II : Computer Networks

CHAPTER-6
COMPUTER NETWORKS

Topic-1
Communication Technologies
Revision Notes
Ø Evolution of Networking
(a) ARPANET : In 1969, US govt. formed an agency named ARPANET (Advanced Research Projects Agen
cy Network) to connect computers at varions universities and defense agencies. The main objective of
ARPANET was to develop a network that could continue to function efficiently even in the event of a
nuclear attack.
18 ] Oswaal CBSE Chapterwise & Topicwise Revision Notes, COMPUTER SCIENCE, Class – XII

(b) Internet (INTER-connection NETwork) : The Internet is a worldwide network of computer networks.

Switching Techniques
Ø
(a) Circuit switching : In the circuit switching technique, first the complete end to end transmission path

between the source and the destination computers is established and then the message is transmitted
through the path. The main advantage of this technique is guaranteed delivery of the message which
is mainly used for voice communication.
(b) Message Switching : In the message switching technique, no physical path is established between

sender and receiver in advance. This technique follows the store and forward Mechanism.
(c)  Packet Switching : In this switching technique, fixed size of packet can be transmitted across the

network
Ø Comparison between the various switching techniques:

Criteria Circuit switching Message Switching Packet Switching

Path established in ad- Yes No No


vance
Store and forward tech- No Yes
nique Yes
Message follows multiple No Yes
routes Yes

Ø Data communication Terminologies


(a) Concept of Channel : A data channel is the medium used to carry information or data from one point

to another.
(b) Band: It is the unit to measure the data transmission speed. It is equivalent to bps (bits per second).

(c) Band width: The maximum volume of data that can be transferred over any communication channel

at a given point of time is known as the bandwidth. In analog systems, it is measured in hertz (Hz) and
in digital systems, it is measured in bits per second (bps).
(d) Data Transfer Rate: The amount of data transferred per second by the communication channel from

one point to another is known as the data transfer rate. It is measured in bits per second (bps), bytes per
second (Bps).
1 Kbps = 1024 bps (bit per second) 1 Kbps =125 Bps (Byte per second)
1 Mbps = 1024 Kbps 1 Mbps = 125 Kbps
1 gbps = 1024 mbps 1 Gbps = 125 Mbps
1 Tbps = 1024 gbps 1 Tbps = 125 Gbps

Ø Transmission Media
(a) Twisted Pair Cable : It consists of two identical 1mm thick copper wires insulated and twisted togeth-

er. The twisted pair cables are twisted in order to reduce crosstalk and electromagnetic induction.
Advantages:
• It is easy to install and maintain.
• It is inexpensive.
Disadvantages:
•It is incapable to carry a singal over long distances without the use of repeaters
•Due to low band width, these are unsuitable for broadband applications.
(b) Coaxial Cables: It consists of a solid wire core surrounded by one or more fail or braided wire

shields, each separated from the other by some kind of plastic insulator. It is mostly used in the cable
wires.
Advantages:

• Data transmission rate is better than twisted pair cables.

Oswaal CBSE Chapterwise & Topicwise Revision notes, COMPUTER SCIENCE, Class – XII [ 19
• It provides a cheap means of transporting multi-channel television signals around metropolitanar-

eas.
Disadvantages:
•Expensive than twisted pair cables.

•Difficult to mange and reconfigure.

(c) Optical fiber : It consists of thin glass fibres that can carry information in the form of visible light.

Advantages:

• Transmit data over long distance with high security.

• Data transmission speed is high.
• Provide better noise immunity.
• Bandwidth is up to 10 Gbps.
Disadvantages:
•  Expensive as compared to other guided media.

• Need special care while installation.

(d)Infrared: The infrared light transmits data through the air and can propagate throughout a room, but

will not penetrate walls. It is a secure medium of signal transmission. The infrared transmission has
become common in TV remote, automotive lift doors, wireless speakers etc.
Advantages:
• Power consumption is used.

• Circuitry cost is less

• Secure mode of transmission

Disadvantages
• Limited in a short range.

•  Can be blocked by common materials like walls, people, plants etc.

(e) Radio wave : It is an electromagnetic wave with a wavelength between (0.5) cm and 30,000m. The trans-

mission making use of radio frequencies is termed as radio-wave transmission.
Advantages:
• Radio wave transmission offers mobility.

• It is cheaper than laying cables and fibers.

•  It offers ease of communication over difficult terrain.

Disadvantages:
• Radio wave communication is insecure communication.

•  Radio wave propagation is susceptible to weather effects like rains, Thunder storms etc.

(f) Microwave : The microwave transmission is a line of sight transmission. Microwave signals travel at a

higher frequency than radio waves and are popularly used for transmitting data over long distances.
Advantages:

• It is cheaper than laying cable or fiber.

• It has the ability to communicate over oceans.

Disadvantages:

• Microwave communication is an insecure communication.
• Signals from antenna may split up and transmitted in different way to different antenna which leads
to reduce in signal strength.
• Microwave propagation is susceptible to weather effects like rains, thunder storms etc.
• Bandwidth allocation is extremely limited in case of microwaves.
20 ] Oswaal CBSE Chapterwise & Topicwise Revision Notes, COMPUTER SCIENCE, Class – XII

(g) Satellite link: The satellite transmission is also a kind of line of sight transmission that is used to

transmit signals throughout the world.
Advantages:
• Area covered is quite large.
• No line of sight restrictions such as natural mountains, tall buildings, towers etc.
• Earth station which receives the signals can be fixed position or relatively mobile.
Disadvantages:
• Very expensive as compared to other transmission mediums.
• Installation is extremely complex.
• Signals sent to the stations can be tampered by external interference.
Ø Network Devices
These are units that mediate data in a computer network and also called network equipments.
• Modem: A MODEM (Modulator Demodulator) is an electronic device that enables a computer to trans-
mit data over telephone lines. There are two types of modems namely, internal modem and external
modem.
• RJ45 Connector: The RJ-45 (Registered Jack) connectors are the plug in devices used in the networking
and telecommunication applications. They are used primarily for connecting LANs, particularly Ether-
net.
•Ethernet card: It is a hardware device that helps in connection of nodes within a network.
• Hub: It is a hardware device used to connect several computers together. Hubs can be either active or
passive. Hubs usually can support 8,12 or 24 RJ45 parts.
• Switch : A switch (switching hub) is a network device which is used to interconnect computers or de-
vices in a network. It filters and forwards data packets across a network. The main difference between a
hub and a switch is that hub replicates what is received on one port onto all the other ports while switch
keeps a record of the MAC addresses of the devices attached to it.
• Gateway: It is a device that connects dissimilar networks.
•Repeater : It is a network device that amplifies and restores signals for long distance transmission.
Ø Network Topologies
Topology refers to the way in which the workstations attached to the network are interconnected.

Some common network topologies are as follows:
Bus Topology: It uses a common single cable to connect all the workstations . Each computer performs

its task of sending messages without the help of the central server. However, only one workstations can
transmit a message at a particular time in the bus topology.
Advantages:

•Easy to connect and install.

•Involves a low cast of installation time.

•can be easily extended.

Disadvantages:

• The entire network shuts down if there is a failure in the central cable.

• Only a single message can travel at a particular time.

•Difficult to troubleshoot an error.

Star Topology: It is based on a central which acts as a hub. A star topology is common in home networks

where all the computers connect to the single central computer. using a hub.
Advantages:

•Easy to troubleshoot.

• A single node failure does not affect the entire network.

Oswaal CBSE Chapterwise & Topicwise Revision notes, COMPUTER SCIENCE, Class – XII [ 21
• Fault detection and removal of faulty parts is easier.

• In case a workstation fails, the network is not affected.

Disadvantages:

•Difficult to expand.

•Longer cable is required.

• The cost of the hub and the longer cables makes it expensive over others.

•In case hub fails, the entire network fails.

Tree Topology : It combines the characteristics of the linear bus and star topologies. It consists of groups of

star configured workstation connected to a bus backbone cable.
Advantages:

•Eliminates network congestion.

•The network can be easily extended.

•Faulty nodes can be easily isolated from the rest of the network.

Disadvantages:

•Uses large cable length.

• Requires a large amount of hardware components and hence is expensive.

• Installation and reconfiguration is very difficult.

Ø Network Types
• LAN(Local Area Network) : It is a network that is confined to a relatively small area. It is generally lim-
ited to a geographic area such as writing lab, school or building. It is generally privately owned network
over a distance not more than 5 km.
• MAN (Metropolitan Area Network): It is a network that covers a group of nearby corporate offices in a
city and might be either private or public.
• WAN (Wide Area Network): These are the networks spread over large distances, say across countries or
even continents through cabling or satellite uplinks.
• PAN(Personal Area Network): It is a computer network organized around an individual person. It gen-
erally covers a range of less than 10 meters. PAN can be constructed with cables or wirelessly.
Ø Network Protocol
A Protocol means the rules that are applicable for a network. It defines the standardized format for data
packets, techniques for detecting and correcting errors and so on. A protocol is a formal description of
message formats and the rules that two or more machines must follows to exchange those messages.
e.g. Using library books
Types of protocols are:

• 
Hypertext Transfer Protocol (HTTP) : It is a communication protocol for the transfer of information on
the Internet and world wide web. HTTP is a request/response standard between a client and a server. A
client is the end-user while, the server is the website.
• 
FTP (File Transfer Protocol): It is the simplest and most secure way to exchange files over the Internet.
The objective of FTP are:
1. To promote sharing of Files (computer programs and/or data).
2. To encourage indirect or implicit use of remote computers.
3. To shield a user from variations in fire storage systems among different hosts.
4. To transfer data reliably and efficiently.
• 
TCP/IP (Transmission control Protocol/ Internet Protocol): TCP is responsible for verifying the correct
delivery of data from client to server. Data can’t be lost in the intermediate network. TCP adds support
to detect errors or last data and to trigger retransmission until the data is correctly and completely re-
ceived.
22 ] Oswaal CBSE Chapterwise & Topicwise Revision Notes, COMPUTER SCIENCE, Class – XII

IP is responsible for moving packet of data from node to node. IP forwards each packet based on a four byte
destination address (the IP number). The Internet authorities assign ranges of numbers to different organi-
sations. The organisations assign groups of their numbers to departments. IP operates on gateway machines
that moves data from department to organization, then to region and then around the world.
• 
SMTP(Simple Mail Transfer Protocol): It is a standard protocol for email services on TCP/IP network
that provides ability to send and receive email.
• 
POP3 (Post Office Protocol Version3): It is a message access protocol which allows client to fetch an
E-mail from remote mail server.
Ø Wireless Technologies
• 
GSM (Global System for Mobile Communication): It is leading digital cellular system. In covered areas,
cell phone users can buy one phone that will work anywhere, where the standard is supported. It uses
narrow band TDMA, Which allows eight simultaneous calls on same radio Frequency.
• 
CDMA (Code Division Multiple Access): It is a digital cellular technology that uses spread spectrum tech-
niques. CDMA does not assign a specific frequency to each user. Instead, every channel uses the full available
spectrum.
• WLL(Wireless in Local Loop): WLL is a system that connects subscribers to the public switched telephone

network using radio signals as a substitute for other connecting media.
•  Email(Electronic Mail): Email is sending and receiving messages by computer.

•  Chat: Online Textual talk in real time is called chatting.

• Video Conferencing: A two way videophone conversation amoung multiple participants is called video

conferencing.
•  SMS (Short Message Service): SMS is the transmission of short text messages to and from a mobile phone,
fax machine and/or IP address:
•  3G and EDGE: 3G is a specification for the third generation of mobile communication technology. 3G

promises increased bandwidth upto 384 Kbps, when a device is stationary.
EDGE is Enhanced Data rates for GSM Evolution of Enhanced Data for Global Evolution which is a third
generation, high speed, mobile data and internet access technology. It is faster enough to support wide
range of advanced data services such as video, music clips, full picture and video messages, high speed
color internet access and email on move.

Topic-2
Network Security and Web service

Revision Notes
Ø Network security concepts
(i) Threats are the logical attacks on a system to fail its functioning.

Viruses : These are programs which replicate and attach to other programs in order to corrupt the execut-
able codes. Virus enters the computer system through an external source and become destructive.
Worms: These are also self replicating programs that do not create multiple copies of itself on the computer
but propagate through the computer network. Worms log on to computer system using the username and
passwords and exploit the system.
Trojan Horse: Though it is a useful program, however, a cracker can use it to intrude the computer system

in order to exploit the resources. Such a program can also enter into the computer through an e-mail of
free program downloaded through the Internet.
Spams: Unwanted e-mail (usually of a commercial nature sent out in bulk).
(ii)Prevention Techniques

Cookies: These are the text message sent by a web server to the web browser primarily for identifying the
user.
Oswaal CBSE Chapterwise & Topicwise Revision notes, COMPUTER SCIENCE, Class – XII [ 23
Firewall: it is used to control the traffic between computer networks. It intercepts the packets between the
computer networks and allows only authorized packets to pass.
(iii)IT Acts

Cyber Law: It refers to all the legal and regulatory aspects of internet and the world wide web.
Cyber crimes: It involves the usage of the computer system and the computer network for criminal activ-
ity.
Hacking: It is an unauthorized access to computer in order to exploit the resources.
Ø Web Services
 WWW: The world wide web or W3 or simply the web is a collection of linked documents or pages, stored
on millions of computers and distributed across the Internet.
 HTML (HyperText Markup Language):It is a computer language that describes the structure and behav-
ior of a web page. This language is used to create web pages.
 XML (Extensible Markup Language): It is a meta language that helps to describe the markup language.
 Domain Name: It is a unique name that identifies a particular website and represents the name of the
server where the web pages reside.
 URL(Uniform Resource Locator) : It is a means to locate resources such as web pages on the Internet. URL
is also a method to address the web pages on the Internet. There are two types of URL namely, absolute
URL and relative URL.
 Website : A collection of related web pages stored on a web server is known as a website.
 Web browser: A software application that enables to browse, search and collect information from the web
is known as web browser.
 Web servers : The web pages on the Internet are stored on the computers that are connected to the Internet.
These computers are known as web servers.
 Web hosting: Web hosting or website hosting is the service to host, store and maintain websites on the
world wide web.
 Web scripting : The process of creating and embedding scripts in a web page is known as web scripting.
Types to Scripts are:
(i) Client Side Scripts: These support interaction within a webpage. e.g. VB script, Java Script, PHP (PHP’s

Hypertext preprocessor).
(ii) Server Side Scripts : These support execution at server end. e.g. ASP, JSP, PHP etc.

Ø Open Source Technologies
 Free Software: The software’s is freely accessible and can be freely used, changed, improved, copied and
distributed by all and payments are needed to make it free software.
 Open Source Software : Software whose source code is available to the customer and it can be modified
and redistributed without any limitation. OSS may come free of cost but nominal charges has to be paid.
 FLOSS (Free Libre and Open Source Software): Software which is free as well as open source software.
GNU (GNU’s Not Unix) : GNU project emphasize on the freedom and its objective is to create a system

compatible to UNIX but not identical with it.
 FSF (Free Software Foundation): It is a non-profit organization created for the purpose of the free software
movement. Organization funded software developers to write free software.
 OSI (Open Source Initiative): Open Source software organization dedicated to promote open source
software. It specified the criteria of OSS and its source code is not freely available.
 W3C (World Wide Web Consortium): W3C is responsible for producing the software standards for world
wide web.
 Proprietary software: It is the software that is neither open nor freely available, normally the source code
of the proprietary software is not available but further distribution and modification is possible by special
permission by the supplier.
24 ] Oswaal CBSE Chapterwise & Topicwise Revision Notes, COMPUTER SCIENCE, Class – XII

 Freeware : It is the software freely available which permits the redistribution but not modification (and
their source code is not available). Free ware is distributed in binary form (ready to run) without any
licensing fees.
 Shareware : Software for which license fee is payable after sometime limits its source code is not available
and modification to the software are not allowed.
 Localization: It refers to the adaptation of language, content and design to reflect local cultural sensitivities
e.g. software localization, where message that a program presents to the user need to be translated into
various languages.
 Internationalization : Opposite of localization.
Mozilla : It is a free internet software that
• a web browser

• an email client

• an HTML editor

• IRC client

 Apache server: Apache web server is an open source web server available for many platforms such as
BSD, Linux and Microsoft Windows etc.
 MYSQL : It is one of the most popular open source database system. Features of MYSQL:
• Multithreading

• Multi-user

• SQL Relational Database server

• Works in many different platform

 Postgres SQL : It is a free software object relational database server which can be downloaded from
postgressql.org
 Pango: Pango project is to provide an open source framework for the layout and rendering of internation-
alized text into GTK + GNOME environment. Pango Uses Unicode for all of its encoding and will eventu-
ally support output in all the worlds major languages.
 OpenOffice: It is an office application suite. It is intended to compatible and directly complete with Mic-
rosoft office OO version 1.1 inclludes:
• Write (word processor)

• Calc (Spreadsheet)

• Draw (Graphics program)

 Tomcat : Tomcat functions as a servlet container. Tomcat implement the servlet and the JavaServer Pages
Tomcat comes with the jasper computer that complies JSPs into servlets.

Know the Terms


• 
1G(First Generation) : 1G networks (NMT, C-Nets, AMPS, TACS) are considered to be first analog cel-
lular systems, which started early 1980s. There were radio telephone systems even before that. 1G net-
works were conceived and designed purely for voice calls with almost no consideration of data services
(with the possible exception of built in modems in some headsets). The G in wireless networks refer to
the generation of the underlying wireless network technology.
• 
2G(Second Generation): 2G networks (GSM, CDMA one, D-AMPS) are the first digital cellular systems
launched early 1990s, offering Improved sound quality, better security and higher total capacity. GSM
supports circuit switched data (CSD), allowing users to place dial-up data calls digitally, so that the net-
works switching station receives actual ones and zeroes rather than the screen of an analog modem.
• 
3G (Third Generation): 3G networks (UMTS FDD and TDD, CDMA 2000 3x, TD-SCDMA, Arib WCDMS,
EDGE, IMT-2000 DECT) are newer cellular networks that have data rates of 334 Kbits and more. The
UN’s International Telecommunications Union IMT-2000 standard requires stationary speeds of 2Mbps
and mobile speeds of 334 Kbps for a true 3G.
Oswaal CBSE Chapterwise & Topicwise Revision notes, COMPUTER SCIENCE, Class – XII [ 25
• 
4G (Fourth Generation): 4G technology refers to the fourth generation of mobile phone communication
standards. LTE and WiMAX are marketed as parts of this generation, even though they fall short of the
actual standard.
• 
Backbone: Referring to the Internet, a central network that provides a pathway for other networks to
communicate.
• 
Bridge: A data link layer device that limits traffic between two network segments by filtering the data
between them based an hardware addresses.
• 
Broadband: A transmission system capable of carrying many channels of communication simultaneous-
ly by modulating them on one of several carrier frequencies.
• 
Congestion : Traffic in excess of network capacity.
• 
Data Link : The physical connection between two devices such as Ethernet, LocalTalk or Token Ring that
is capable of carrying information in the service or networking protocols such as AppleTalk, TCP/IP or
XNS.
• 
Destination Address: Address of network device that is receiving data.
• Gbps : Gigabits per second

• GHz : GigaHertz

• 
KBPS : A unit of measure used to describe the rate of data transmission equal to 1000 bits per second.
• MBPS: A unit of measure used to describe the rate of data transmission equal to one millions bits per

second.
• 
Packet: A discrete chunk of communication in a per defined format.
• 
Session : An on-going relationship between two computing devices involving the allocation of resources
and sustained data flow.
• Token Ring: A ring topology network that uses token passing for MAC.

• Transport Protocol: The protocol layer of the OSI-7 layer model that is concerned with management of

data flow between source and destination.
• Adware : A general term used for software that invades your computer in the form of persistent pop-up

ads.
• Anti-virus : A security program that can run on a computer or mobile device and protects you by identifying

and stopping the spread of malware on your system.
• ASP(Active Server Pages): It is a technology developed by Microsoft for the purpose of creating dynamic

pages that have a .asp extension. such pages utilize VBScript of Jscript code.
• E-mail (Electronic mail) : It refers to electronic messages that are sent over communications networks on

the Internet. E-mail is sent and retrieved with various protocols including SMTP, POP3 and IMAP.
• Encryption: The process by which data is converted into a secret code from its original form via some

algorithm. The data in its original form can then only be read by those who can reverse the encryption.
Encryption prevents unauthorized reading of data.
• Hacker: A general term used for anyone who spends time poking into computers and operating systems,

trying to discover their vulnerabilities.
• Host : A computer that is accessed by a user from a remote location, also any computer on a network.

• IP Address : It is a unique identifier for every computer or device on a network.

• JavaScript : An object oriented high level language used for web development. JavaScript was originally

created by Netscape. It can be used to interact with the user as well as create dynamic content such as
moving images and clocks.
• Phishing : It is a social engineering technique where cyber attackers attempt to fool you into taking an action

in response to an Email. Phishing was a term originally used to describe a specific attack scenario.
• Scripting Language : It is a language used to write scripts that are usually executed in a web browser or a

web server. Scripting languages are often used to add functionality to web pages such as interaction with
the user, animations an different menus. Code written in scripting language is not compiled, rather inter
preted. Some scripting languages include JavaScript, VBScript, PHP and Python.
26 ] Oswaal CBSE Chapterwise & Topicwise Revision Notes, COMPUTER SCIENCE, Class – XII

• Spyware: A type of malware that is designed to spy on the victim’s activities, capturing sensitive data such

as the person’s passwords, online shopping and screen, contents.

UNIT-Iii : Data Base Management

CHAPTER-7
DATA BASE MANAGEMENT
Revision Notes
Ø Database Concepts and Needs:
• A Database consists of a number of tables. Each table comprises of rows (records) and columns (attri-

butes). Each record contains values for the corresponding attributes. The values of the attributes for a
record are interrelated. For example, different cases have different values for the same specifications
(length, color, engine capacity, etc).
•  The database oriented approach supports multiple views of the same data. For example, a clerk may

only be able to see his details, whereas the manager can view the details of all the clerks working under
him.
•  In database oriented approach, we store the common data in one table and access it from the required

tables. Thus, the redundancy of data decreases.
•  Multiple views of the same database may exist for different users. This is defined in the view level of

abstraction.
•  The logical level of abstraction defines the type of data that is stored in the database and the relation-

ship between them.
•  The design of the database is know as the database scheme.

• The
 instance of the database is the data contained by it at that particular moment.
• The database administrator has the total control of the database and is responsible for setting up and

maintaining the database.
•  A data mode is the methodology used by a particular DBMS to organize and access the data.

• Hierarchical, Network and Relational model are the three popular data models. However, the relational

model is more widely used.
Ø Hierarchical Model
• The hierarchical model was developed by IBM in 1968.

• The data is organized in a tree structure where the nodes represent the records and the branches of the

tree represent the fields.
•  Since the data is organized in a tree structure, the parent node has the links to its child nodes.

• If we want to search a record, we have to traverse the tree from the root through all its parent nodes to

reach the specific record. Thus, searching for a record is very time consuming.
• The hashing function is used to locate the root.

• SYSTEM2000 is an example of hierarchical database.

Ø Network Model
•  Recording of relationship in the network model is implemented by using pointers.

• Recording of relationship implementation is very complex since pointers are used. It supports ma-

ny-to-many relationship and simplified searching of record, since a record has many access paths.
•  DBTG Codasyl was the first network database.

Oswaal CBSE Chapterwise & Topicwise Revision notes, COMPUTER SCIENCE, Class – XII [ 27
Ø Relational Model
• The Relational model, organizes data in the form of independent tables (consisting of rows and columns)

that are related to each other.
•  A table consists of a number of rows (records/tuples) and columns (attributes). Each record contains values

for the attributes.
•  The degree of the table denotes the number of columns.

•  A domain in the relational model is said to be atomic, if it consists of indivisible units. For example, name

is not atomic since it can be divided into first name and last name.
•  E.F. Codd laid down 12 rules (known as Codd’s 12 rules), that outline the minimum functionality of a

RDBMS. A RDBMS must comply with at least 6 rules.
•  A super key is a type of attribute that collectively identifies an entity in an entire set. For example, the bank

account number is a super key in the bank accounts table.
•  A candidate key (also known as primary key) is the smallest subset of the super key for which there does

not exist a proper subset that is a super key.
•  Out of the multiple candidate keys, only one is selected to be the primary key and the remaining are alter-

nate keys.
•  A foreign key is the primary key of a table that is placed into a related table to represent one-to-many

relationship among these tables.
•  A primary key is a set of one or more attributes that can uniquely identify the relation.

Know the Terms


Ø DBMS: It stands for Database Management System that enables users to define, create and maintain the database
and provides controlled access to this database.
Ø DBA: DBA is Database Administrator that having the central control over the system.
Ø RDBMS: RDBMS stands for Relational Database Management System.
Ø Meta Data: It means data about data i.e., a logical description of the structure of a data.
Ø File Processing System: It is a collection of row data files stored in the hard drive of a system.

CHAPTER-8
structured query language (sql)
Revision Notes
1. Structured Query Language (SQL)
l When a user wants to get some information from a database file, he can issue a query.
l A query is a user-request to retrieve data or information with a certain condition.
l SQL is a query language that allows user to specify the conditions, (instead of algorithms).
2. Types of SQL commands
l Data Definition Language commands (DDL Commands): All the commands used to create,
modify or delete physical structure of an object like table. e.g., Create, Alter, drop.
l Data Manipulation Language Commands (DML Commands): All the commands used to modify
contents of a table comes under this category. e.g., Insert, Delete, Update

l Transaction Control Language Commands(TCL Commands): These commands are used to control
transaction of DML commands. e.g., Commit, Rollback.
3. Basic structure of an SQL query
l General structure SELECT, ALL/DISTINCT, *, AS, FROM, WHERE
l Comparison IN, BETWEEN, LIKE “% _”
28 ] Oswaal CBSE Chapterwise & Topicwise Revision Notes, COMPUTER SCIENCE, Class – XII

l Grouping GROUP BY, HAVING, COUNT(), SUM(), AVG(), MAX(), MIN()


l Display order ORDER BY, ASC/DESC
l Logical operators AND, OR, NOT
4. Constraint
l Constraint is a condition applicable on a field or group of fields.
l Two types of constraint:
l Column constraint: apply only to individual column.
l Table constraint: Apply to group of columns.
l Different constraints:
Unique Constraint-Primary Key constraint.
Default Constraint-Check constraint.
Applying Constraint
Example: Create a student table with student id, student name, father ’s name, age, class, address.
CREATE TABLE student ()
sid char (4) PRIMARY KEY,
sname char (20) NOT NULL,
fname char (20),
age number (2) CHECK (age<20),
class char (5) NOT NULL,
address char (50));
5. SELECT Command
The SELECT command is a query that is given to produce certain specified information from the database table.
Syntax:
SELECT <column-name>,[,<column-name>,......]
FROM <table-name>;
Example: Write a query to display the name and salary of the employee in emp table.
SELECT ename, sal
FROM emp;
Variations of SELECT command:
(i) Selecting specific Rows........WHERE clause
Syntax:
SELECT <column-name> [,<column-name>.......]
FROM <table-name>
WHERE <condition>;
Example: Display the codes, names and salary of employees who belong to ‘Manager’ category.
SELECT empno, ename, sal
FROM emp
WHERE job=“MANAGER”;
(ii) Searching for NULL (IS NULL command)
The Null value in a column can be searched for in a table using IS NULL in the Where Clause
Syntax:
SELECT......<column-name>[,<column-name>......]
FROM <table-name>
WHERE <column-name> IS NULL;
Example: Display the codes, names and jobs of employees whose DeptNo is Null.
SELECT empno,ename, job
FROM emp
WHERE DeptNo IS NULL;
(iii) IS NOT NULL Command
Example: Display the names and jobs of those employees whose DeptNo is not Null.
SELECT ename, job FROM emp
WHERE DeptNo IS NOT NULL;
(iv) Sorting Result-ORDER BY Clause
The resulting column can be sorted in ascending and descending order using the ORDER BY clause.
Oswaal CBSE Chapterwise & Topicwise Revision notes, COMPUTER SCIENCE, Class – XII [ 29
Syntax:
SELECT <column-name>[,<column-name>.......]
FROM <table-name>
WHERE <condition>
ORDER BY <column-name>ASC/DESC;
Example:
Display the list of employees in descending order of employee code, who is manager.
SELECT * FROM emp
WHERE job=“MANAGER”
ORDER BY ecode DESC;
(v) Conditions based on a range
SQL provides a BETWEEN operator that defines a range of values that the column value must fall for the
condition to become true.
Example:
SELECT Roll_no, name From
student Where Roll_no Between 100 and 103;
The given command displays Roll_no and name of those students whose Roll_no lies in the range 100 to 103
(both 100 and 103 are included in the range):
(vi) Conditions based on a list
To specify a list of values, In operator is used. This operator selects values that match any value in the given
list.
Example:
Select * From student Where city in (‘Delhi’, ‘Agra’, ‘Gwalior’);
The above command displays all those records whose city is either Delhi or Agra or Gwalior.
(vii) Conditions based on Pattern
SQL provides two wild card characters that are used while comparing the strings with LIKE operator.
(a) percent (%) matches any string.
(b) Underscore(_) matches any one character.
Example:
Select Roll_no, name, city From student Where Roll_no Like “%3”;
This query displays those records where last digit of Roll_no is 3 and may have any number of characters in
front.
Example:
SELECT Roll_no, name, city From student Where Roll_no Like “1_3”;
This query displays those records whose Roll_no starts with 1 and second letter may be any letter but ends
with digit 3.
6. The INSERT command
The tuples are added to relation using INSERT command of SQL.
Syntax:
INSERT INTO <table-name>[<column list>]
VALUES (<value1>,<value2>,<value3>,.....);
Example: Enter a new record in student table.
INSERT INTO student (sid,sname,fname,age, class,address)
VALUES(“101”,“Mohan”,“Pawan”,15,“8”,“Jaipur”);
Output:
sid sname fname age class address
101 Mohan Pawan 15 8 Jaipur
7. The DELETE command
The delete command removes the tuples from the tables. This command removes the entire row from the
table and not the individual field. So, no field argument is needed.
Syntax:
DELETE FROM <table-name>
WHERE <condition>;
Example: Delete all the records of employee whose salary is less than 3000.
DELETE FROM emp
WHERE sal<3000;
30 ] Oswaal CBSE Chapterwise & Topicwise Revision Notes, COMPUTER SCIENCE, Class – XII

To delete all the record from the table.


Syntax:
DELETE FROM<table-name>;
8. The UPDATE command
The UPDATE command is used to change some values in existing rows. The UPDATE command specifies the
rows to be changed using the WHERE clause, and new data using the SET keyword.
Example: Update the salary of employee to 5000 whose employee code is 1011.
UPDATE emp
SET sal=5000
WHERE empno=1011;
9. The ALTER TABLE command
The ALTER command is used to change the definition of existing table.
(a) To add columns to a table
Syntax
ALTER TABLE<table-name> ADD <column name> <data type> <size>;
(b) To modify existing columns of a table
Syntax:
ALTER TABLE <table-name>
MODIFY (Column-name newdatatype (newsize));
Example: To modify column job of table emp to have new width of 30 characters.
ALTER TABLE emp
MODIFY (job char (30));
10. The DROP Command:
The DROP command is used to drop the table from the database. For dropping a table, all the tuples should be
deleted first i.e., the table should be empty.
Syntax:
DROP TABLE <table-name>;
Example: Drop the student table from the database.
DROP TABLE student;
Some Example:
Ex 1. Write a query on the customers table whose output will exclude all customers with a rating <=100, unless
they are located in Shimla.
SELECT * FROM customers WHERE rating >100 OR city =“Shimla”;
Ex 2. Write a query that selects all orders except those zeros or NULLs in the amount field.
SELECT * FROM Orders WHERE amt <>0 AND (amt IS NOT NULL);
Ex 3. Write a query that lists customers in descending order of rating. Output the rating field first, followed by the
customers name and number.
SELECT rating, cust_name, cust_num FROM customers ORDER BY rating DESC;
Ex 4. Write a command that puts the following values in their given order, into the salesman table:
cust_name-Manisha, city-Manali, comm.-NULL, cust_num-1901.
INSERT INTO salesman (city, cust_name, comm., cust_num) VALUES (“Manali”, “Manisha”, NULL, 1901);
Operators in SQL:
The following are the commonly used operators in SQL:
(i) Arithmetic Operators   +, -, *, /, %
(ii) Relational Operators =, <, >, <=, >=, <>
(iii) Logical Operators   Or, And, Not
l Arithmetic operators are used to perform simple arithmetic operations.

l Relational operators are used when two values are to be compared and logical operators are used to
connect search conditions in the Where clause in SQL.
Other Operators:
(iv) Range check – between low and high
(v) List check – in
(vi) Pattern check – like, not like (%and _ (under score) are used).
Oswaal CBSE Chapterwise & Topicwise Revision notes, COMPUTER SCIENCE, Class – XII [ 31
11. SQL Functions:
SQL supports functions which can be used to compute and select numeric, character and date columns of a
relations. These functions can be applied on a group of rows. The rows are grouped on a common value of a
column in the table. These functions return only one value for a group and therefore, they are called aggregate or
group functions.
(i). SUM (): It returns the sum of values of a column of numeric type.
E.g., Select sum (salary) from employee;
(ii). AVG (): It returns the average of values of a column of numeric type.
E.g., Select avg (salary) from employee;
(iii). MIN (): It returns the minimum value of the values of a column or a given relation.
E.g., Select min (salary) from employee;
(iv). MAX (): It returns the maximum value of the values of a column or a given relation.
E.g., Select max (salary) from employee;
(v). COUNT ( ): It returns the number of rows in a relation.
E.g., Select count (*) from employee;
Join
A join is a query that combines rows from two or more tables. In a join query, more than one tables are listed
in FROM clause.
The function of combining data from multiple tables is called joining.
Joins are used when we have to select data from multiple tables is called joining.
Joins are used when we have to select data from two or more tables. Joins are used to extract data from two
tables, when we need a relationship between certain columns in these tables.
There are different kind of SQL joins:
1. Equi-Join
Equi join is a simple SQL join condition that uses equal sign as a comparison operator.
Syntax
SELECT column1, column2, column3
FROM Table1, Table2
WHERE Table1. column1 = Table2. column1;
2. Self Join
A self join is a join where we join a particular table to itself. Here in this case, it is necessary to ensure that the
join statement defines an ALIAS name for both the copies of the tables to avoid column ambiguity.
3. Non-Equi Join
Non- equi join is used to return the result from two or more tables, where exact join is not possible. The SQL
non-equi join uses comparision operators instead of, the equal sign like >, <, >=, <= alongwith conditions.
Syntax
SELECT * FROM Table1, Table2
WHERE Table1. column > Table2. column;:
4. Natural Join
The natural join is a type of equi join and it structured in such a way that, columns with same name of
associated tables will appear once only.
Syntax
SELECT* FROM Table1
NATURAL JOIN Table2;

CHAPTER-9
INTERFACE OF PYTHON WITH AN SQL DATABASE
Revision Notes
 Python’s standard for database interfaces is the Python DB-API
 Python Database API supports a wide range of database servers such as GadFly, mSQL, MySQL, Oracle, Sybase etc.
 You need to download separate DB-API module for each database you need to access.
Oswaal CBSE Chapterwise & Topicwise Revision notes, COMPUTER SCIENCE, Class – XII [ 32
 DB-API provides a minimal standard for working with databases.
 MySQLdb is an interface for connecting to a MySQL database servers from Python.
 Connect method of MySQLdb interface is used to create a connection object using MySQLdb module.
 A cursor is a Python object that enables you to work with the database. In database terms, the cursor is positioned
at a particular location within a table or tables in a database.
 To get a cursor you need to call the cursor method on the database object.
 To save your changes to the database, you must commit the transaction using commit()
 When you are done with the script, close the cursor and then the connection to free up the resources
 The DB-API’s include a defined set of exceptions.
Database object Methods

Method Description
close() Closes the connection to the database
commit() Commits any pending transaction to the database.
cursor() Returns a database cursor object through which queries can
be executed
rollback() Rolls back any pending transaction to the state that existed
before the transaction began.

 Cursor object Attributes and Methods


Note: c is the cursor object.

Syntax Description
c.arraysize() The readable/writable numbers of ours that fetchmany() will
return if no size is specified.
c.close() Close the cursor, c.
c.execute(sql,params) Executes the SQL query on string sql, replacing each place-
holder with the corresponding parameter from the param
sequence or mapping
c.executemany(sql, seq-of-params) Executes the SQL query once for each item in the seq-of-
params sequence of sequences or mappings. This method
should not be used for operations that create results set (such
as SELECT statement)
c.fetchall() Returns a sequence of all the rows that have not yet been
fetched.
c.fetchmany(size) Returns a sequence of rows(each row itself being a se-
quence); size defaults to c.arraysize
c.fetchone() Returns the next row of the query result set as a sequence or
None when the results are exhausted. Raises an exception if
there is no result set.
c.rowcount() The read only row count for the last operation (e.g. select,
insert, update delete) or –1 if not available or applicable

Know the Terms


 DB-API: It is a specification for a common interfaceto relational databases.
 Cursor: It is a Python object that enables you to do the work with the database.
 Result Set: It is an object that is returned when a cursor object is used to query a table.
 Database: It is a collection of organised information that can easily be used, managed, updated and they are
classified according to their organizational approach.
 MySQLdb: It is an for connecting to a MySQL database server from Python.

You might also like