Download as pdf or txt
Download as pdf or txt
You are on page 1of 107

SESSION: 2023-24

केन्द्रीय विद्यालय संगठन,


पटना संभाग
KENDRIYA VIDYALAYA SANGATHAN,
PATNA REGION

COMPUTER SCIENCE (083)

CLASS - XII
STUDENT SUPPORT MATERIAL
CBSE CURRICULUM
PATRON

SH. ANURAG BHATNAGAR


DEPUTY COMMISSIONER, KVS RO PATNA

OUR MOTIVATORS

SMT. SOMA GHOSH SH. MANISH K PRABHAT SH. PURNENDU MANDAL


AC, KVS RO PATNA AC, KVS RO PATNA AC, KVS RO PATNA
COURSE DIRECTOR
SH, RISHI RAMAN
PRINCIPAL, KV AFS DARBHANGA

CONTENTS PREPARED BY

SN TEACHER NAME DESIG. NAME OF KV

1 SH PURUSHOTTAM KUMAR PGT -CS KV AFS BIHTA

2 SH ANUGRAH CHAUBEY PGT -CS KV JAWAHARNAGAR

3 SH RISHIKESH KU SINGH PGT -CS KV DANAPUR FS

4 SH MANIK KUMAR PGT -CS KV JAMALPUR


INDEX
SN CONTENTS Page No.
1 SYLLABUS

UNIT-1: Computational Thinking and Programming – 2


2 TOPICS: (Revision of Python topics covered in Class XI, 01-36
Functions, Exception Handling)

UNIT-1: Computational Thinking and Programming – 2


3 TOPICS: (Introduction to files, Text file, Binary file, 37-52
CSV file, Data Structure)

4 UNIT-2: Computer Networks 53-74

5 UNIT-3: Database Management 75-99


Computer Science
CLASS-XII
Code No. 083
2023-24
1. Prerequisites
Computer Science- Class XI
2. Learning Outcomes
Student should be able to
a) apply the concept of function.
b) explain and use the concept of file handling.
c) use basic data structure: Stacks
d) explain basics of computer networks.
e) use Database concepts, SQL along with connectivity between Python and SQL.

3. Distribution of Marks:

Unit No. Unit Name Marks Periods

Theory Practical

I Computational Thinking and 40 70 50


Programming – 2

II Computer Networks 10 15 …

III Database Management 20 25 20

Total 70 110 70

4. Unit wise Syllabus


Unit I: Computational Thinking and Programming – 2
● 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 II: 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 III: 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
5. Practical

S.No Unit Name Marks


(Total=30)

1 Lab Test: 8
1. Python program (60% logic + 20%
documentation + 20% code quality)

2. SQL queries (4 queries based on one or 4


two tables)

2 Report file: 7
● Minimum 15 Python programs.
● SQL Queries – Minimum 5 sets using
one table / two tables.
● Minimum 4 programs based on Python -
SQL connectivity

3 Project (using concepts learnt in Classes 11 8


and 12)

4 Viva voce 3

6. Suggested Practical List:


Python Programming
● Read a text file line by line and display each word separated by a #.
● Read a text file and display the number of vowels/consonants/uppercase/lowercase
characters in the file.
● Remove all the lines that contain the character 'a' in a file and write it to another file.
● Create a binary file with name and roll number. Search for a given roll number and
display the name, if not found display appropriate message.
● Create a binary file with roll number, name and marks. Input a roll number and update
the marks.
● Write a random number generator that generates random numbers between 1 and 6
(simulates a dice).
● Write a Python program to implement a stack using list.
● Create a CSV file by entering user-id and password, read and search the password for
given userid.
Database Management
● Create a student table and insert data. Implement the following SQL commands on the
student table:
o ALTER table to add new attributes / modify data type / drop attribute
o UPDATE table to modify data
o ORDER By to display data in ascending / descending order
o DELETE to remove tuple(s)
o GROUP BY and find the min, max, sum, count and average
● Similar exercise may be framed for other cases.
● Integrate SQL with Python by importing suitable module.
7. Suggested Reading Material
● NCERT Textbook for COMPUTER SCIENCE (Class XII)
● Support Materials on the CBSE website.
8. Project
The aim of the class project is to create something that is tangible and useful using Python
file handling/ Python-SQL connectivity. This should be done in groups of two to three
students and should be started by students at least 6 months before the submission
deadline. The aim here is to find a real world problem that is worthwhile to solve.
Students are encouraged to visit local businesses and ask them about the problems that
they are facing. For example, if a business is finding it hard to create invoices for filing GST
claims, then students can do a project that takes the raw data (list of transactions), groups
the transactions by category, accounts for the GST tax rates, and creates invoices in the
appropriate format. Students can be extremely creative here. They can use a wide variety of
Python libraries to create user friendly applications such as games, software for their school,
software for their disabled fellow students, and mobile applications, of course to do some of
these projects, some additional learning is required; this should be encouraged. Students
should know how to teach themselves.
The students should be sensitized to avoid plagiarism and violations of copyright issues while
working on projects. Teachers should take necessary measures for this.
Study Materials (CS/083)
Session :2023-24
Name of Unit
Computer Thinking and Programming – 02
Sub Topic
Revision of Python Topics covered in class 11th

Name of Topic: Tokens


Introductions: The smallest units of programs are known as tokens. It has a specific
meaning to the compiler or interpreter. It has normally five categories.
i. Identifiers
ii. Keywords
iii. Literals
iv. Operators
v. Delimiters

MCQ (01 Marks)


i. The Smallest unit of the program is known as………………………
ii. Token have …………………meaning.
iii. Odd man out from given choices
a. Literals
b. Delimiters
c. Operators
d. Compiler
iv. Without token , can we write program… Yes / No

Very Short Questions Answers (02 Marks)


i. Write down the name of different types of Tokens.
Answers :-
i. Identifiers
ii. Keywords
iii. Literals
iv. Operators
v. Delimiters

ii. What do you mean by Tokens ?


Answers : :- Smallest units of programs are known as token. It have a specific
meaning to the compiler or interpreter. It is five type. Examples : Name_std, int
etc.

1
Short questions Answers (03 Marks)
i. Write down the name of different types of Tokens.
Answers :-
i. Identifiers :- Roll_Number
ii. Keywords :- int, for, while
iii. Literals :- “Hello”, 123, -12.30
iv. Operators :- >, &, +,*
v. Delimiters :- , ( } [

Name of Topic : Variables and Data Types


Introductions :- Variable is symbol which use as like a container to store values. Values of
variable be change in a program. Format for variable declaration is given below :-

Data type <name of variable>


Or
Data type <name of variable> = <value of variable>

We can initialize value of variable through following method


i. Static Initialization: Assign variable values at the time of variable declaration.
ii. Dynamic Initialization: Assign variable through keyboard at the time of
program execution.
Data types are specific word they have special meaning for the program. It is normally use
with variables. Basically five types of data types are present.
i. Numeric Data Types ( Store only numeric Values)
i. Integers ( Integers Values )
ii. Float (Decimal values)
iii. Complex (Real and Imaginary Values)
iv. Boolean (True and false )
ii. None (Undefined values)
iii. Sequence (Ordered collection of items)
i. String (Enclosed in double quotes)
ii. List (Enclosed in Big bracket)
iii. Tuple ( Enclosed in parenthesis / small brackets )
iv. Sets (Unordered collections of items / values and enclosed in curly brackets )
v. Mapping ( present in key and values pair)
i. Dictionary (Present in kay –values pairs and enclosed in curly brackets)

2
MCQ (01 Marks)
i. Value of variable will be ………………………
ii. We can assign more than one value to variable . yes /not
iii. How many format to declaration of variable is ……………
iv. Data type is ……………… and ……………….
v. Choose correct name of variable
i. Name iii. _123a
ii. int iv. for
vi. Without variable we can write a program. Yes /not
vii. Choose correct statement
i. Name = “Purujee” iii. Str = \n
ii. int =100 iv. char = ‘Puruji’
viii. If z = 10 + 21i then real part = ……….
ix. Example of mapping data type is …………………
x. Boolean variable have ……………… values.

Very Short Questions Answers (02 Marks)


i. What do you mean by Variable ? With Examples
Answer:- Variable is a symbol. They store some value which is supply by user.
Example : int a, char ch, name etc.
ii. How Many data types .
Answer:- It is two type of static and dynamic variables
Example : name = “Purujee” Static variable
Name = input(“Enter your Name”)
Here Name is Dynamic Variable.
iii. Write down the name of numeric data type.
Answer:- int (Integer) : 1 , 2, 3
float (Float) : 1.02 , 20.3, 124.0124
long
double
long double

iv. Write down the name of sequence data type .


Answer:- Sequences allow you to store multiple values in an organized and
efficient fashion. There are seven sequence types: strings, bytes, lists, tuples,
bytearrays, buffers, and range objects. Dictionaries and sets are containers for
sequential data.

v. Write down the name of 10 valid variables.


Answer : name, roll, subject, martks, sum, avg, cs_083, ip_065, per, course etc.

3
Short questions Answers (03 Marks)
i. How many method to initialize values of variables.
Answer:- Two method
1. Static Initialization
2. Dynamic Initialization
ii. What is the difference between static and dynamic initialization of variables?
Answer:-
Static Dynamic
Variable values are assigned at the Variable assigns through key board at
time of variable assign the time of program execution.
Examples if write name=”KV” Example : name=input(“Enter Name
Where Name is Static Variable of School”)
Where Name is Dynamic Variable
Its values will be fixed Its values will be changeable

iii. How many types of data type? Explain


Answer : In Python we are using different types of data types
i. Integers
ii. Float
iii. String
iv. List
v. Tuple
vi. Dictionary

Name of Topic : Keywords


Introductions :- Keywords are reserve word they special meaning in program or for the
compiler or interpreter or assembler. In Python all keyword write in small letters.
Examples : int, char, for, break etc.
MCQ (01 Marks)
i. Choose the correct keyword from the given list
a. For c. Else
b. While d. if
ii. “ int “ is use to indicate ………………..data type.
iii. “ char “ is use to indicate………………...data type.
Very Short Questions Answers (02 Marks)
i. Write name of four data type which is use for numeric data representation.
Answer : Four numeric data type are
i. int iii. long double
ii. float iv. double

4
ii. Without keyword , can we write a Python program ? Explain
Answers : No.

Short questions Answers (03 Marks)


i. What is difference between keywords and Variables ?
Answer :
Keyword Variable
It is reserve word . It is not reserve word.
It is pre define word. User write name as per requirement.
Its has specific meaning for compiler. No
It has a pre define format. It has also pre define format.
Examples : ‘for’ , ‘int’ etc Examples : name, roll etc.

Name of Topic : Mutable and immutable data types

Introductions :- All those Data type those values will be change they are known as Mutable
and all those data type which value is not change they are known as immutable data type.
Examples :-
Mutable Data type : List and Dictionary
Immutable Data type : Tuple and String

MCQ (01 Marks)


i. List is ………………. data type .
ii. String is …………….. data type.
iii. Variable is …………….
iv. Constant is ……………
v. How many time mutable data type values will be change . one/two/many

Very Short Questions Answers (02 Marks)


i. Write about the data type.
Answer:-
Data type is identify the nature of variable in program. It is two type
i. Mutable data type : List and Dictionary
ii. Immutable data type : Tuple and String
ii. Mutable data type can be change or modify into immutable data types ?
Answer : No.

Short questions Answers (03 Marks)


i. What is difference between mutable and immutable data type

5
Answer :-
Mutable Immutable
Values can be change Values cannot be change
It is data type It is also data type
Example: List, Dictionary etc. Examples : String, Tuple etc.

Name of Topic : Operators


Introductions :- Operator is a special type of symbol they have specific meaning for the
compilers. Operators perform operation on the basis of operand.
Example :
A+B
Where A and B are operand but + is operators.
Classification of operators according to operand :-
i. Unary operators : Operator required Single operand to perform operation.
Example : a + = 10
ii. Binary operators : Operator required Minimum Two operand to perform
operation.
Example : a + b
iii. Tertiary operators : Operator required minimum three operand to perform
operation.
Example : expr1 > ( statement) ? expr2 : expr 3
Classification of operators according to symbol :-
i. Arithmetical operators : + - * / // % etc.
ii. Relational Operators : > , >= , < , <= , ! =, <>
iii. Logical operators : And (&), OR ( || ) , Not ( ! =)
iv. Assignment operators : = =
v. Bitwise operators : >> , <<
Note :-
Short Hand Assignment operators
S.No Short hand Assignment Operators Examples (if p =10)
1 += >>> p += 2 then output will be 12
2 -= >>> p -= 2 then output will be 8
3 *= >>> p *= 2 then output will be 20
4 /= >>> p /= 2 then output will be 5
(quotient with fraction )
5 %= >>> p %= 2 then output will be 0 (Remainder )
6 **= >>> p **= 2 then output will be 100
7 //= >>> p += 2 then output will be 5 (only quotient)
Note

6
P =15 >>> p /= 2 then output will be 7. 5 >>> p //= 2 then output will be 7

MCQ (01 Marks)


i. Write out of given expression
If a = 10 , b =20 , c = 30
a. a ** b + c – 11
b. c /a + b // a
c. a + b * 3 *c
d. a * 2 + b **2 + c//3
ii. Write True or false
a. a > b < c
b. b < a > c
c. (a + 10) > (b + c)
iii. Write output
a. (a + b) < c

Very Short Questions Answers (02 Marks)


1. What do you mean by Operators ? explain
Answer: Operator is a special type of symbol they have specific meaning for the
compilers.
2. How many Type of operators ?Explain
Answer :
i. Arithmetical operators : + - * / // % etc.
ii. Relational Operators : > , >= , < , <= , ! =, <>
iii. Logical operators : And (&), OR ( || ) , Not ( ! =)
iv. Assignment operators : = =
v. Bitwise operators : >> , <<

3. What do you mean by Precedence of Operators ?


Answer:- Precedence of Operators is describe which operator will use first in given
expression or equation. On the basis of this principle we solve out the different types
of python expression or equations.

Name of Topic : Input and output functions


Introductions :- For inserting data through keyboard, using a function that function is
known as “input()” function. Its format is given below :-
<name of variable> = <data type> (input (“ Name of entry prompt”))
Where : data type is optional.
Examples :-

7
Num = int(input(“Enter value of Num =”))
Name = input( “Enter Name :”)

For displaying data or outcome on screen we are using a function that function is “print( )
“ . It is also known as output function. Its format is given below :-
print(“ Write Statement ”)
print( name of variable )

Examples
print(“ My Name is Purujee”) than display on screen : My Name is Purujee
print(a) than if a =10 then display on screen : 10

Note : With print( ) function following symbol use , they have special meaning in print( )
function.
For new line : “\n”
For blank line : “\b”
For space : “\t”
MCQ (01 Marks)
i. Which function is use to enter data from keyboard …………………
ii. Which function is use to display data on screen …………………….
iii. Choose the correct statement
i. print “Puruji”
ii. print [“ Purujee”]
iii. print(“Purujee”)
iv. print< “Purujee”>

Very Short Questions Answers (02 Marks)


i. Write down the output of given statement
a. print( “ Purujee \n is \n Guruji \n of \n Python”)
b. print(“Purujee ,”\n”, “belong” ,”\n”, “from”,”\n”,”Patna”)
ii. Write input statement for
i. Enter your friend name from keyboard
ii. Enter two numeric values from keyboard

Short questions Answers (03 Marks)


i. What is difference between input and output function ?
Answers :
Input function Output function
It is use for enter data from It is use to display data on screen
Keyboard
It has two format It has more than two format

8
Example : Example :
num = int( input( “Enter value of num)) print(“ Enter value of num is :”, num)

Name of Topic : Comments


Introductions :- Comments are special statement inside the program. They will never
executed with program. It is use to enhance the readability and clarity of programming
statements. It is two type :-
1. Single line comment : it is start from “#” symbol.
Examples :
Print( a) # this statement is use to print numeric value of variable “a”
2. Multiline comment : It is start from “/* …………………………..
…………………………. */ symbol.
Examples :
Number = float ( input “ Enter Value of Number = “ ) \* This statement is use to
Enter floating value */

MCQ (01 Marks)


i. Comments are use to enhance ……….. and …………….. of program.
ii. Single line comments starts from ………………..
iii. Comments are executed with program : yes /no
iv. Without comments , can we write a program ? yes / no

Very Short Questions Answers (02 Marks)


i. How many type of comments. Explain
Answers : Comments are two type
a. Single line comments
b. Multiline comments
ii. Write use and importance of comments in program.
Answers : Basically comments are very useful for the unskilled programmer
because through the comments we can clearly understand the complete program
and as per requirement of user we can made some modification. But it is also tru
comment is not mandatory part of programming.

9
Short questions Answers (03 Marks)
i. Write a program with comments.
Answer :

Num1 = int ( input (“Enter Value of Num1 =”)) # Enter integer value of Num1
Num2 = int ( input (“Enter Value of Num2 =”)) # Enter integer value of Num2
Sum = Num1 + Num2 # adding Num1 and Num2
print (“Sum of Numbers are = “ , Sum) # Displaying sum of two numbers.

Name of Topic : Flow of controls


Introductions :- The way in which the statements are executed defines the flow of execution
or flow of control. It is basically three types
i. Sequential Statements : In this statements executed in a proper sequence
otherwise program will generate an error.
Examples :
a. Write a program to calculate the area of circle.
Answer:-
r = int( input (“Enter the value of radius =”))
area = (3.14) * r * r
print( “Area of Circle is =” , area)

ii. Selection or conditional statements : It is used to perform actions or calculation


based on whether a condition is evaluated as true or false. It is totally based on
the concepts of decision making or selection.
We are using following statement :-
i. Normal “if”
ii. if – else
iii. if – elif – else
iii. Iteration or Looping Statements : In this execute statement or set of statement
repetitively until given condition is true. We are using two types of loop
i. “for” loop
ii. “while” loop
Some basic terms and terminology :-

Before developing a program we are using different types of tools and technique for
analysis and analyze the problem . Then after on the basis of use tool we try find out the
solution of problems.
1. Algorithm : An algorithm is a step by step procedure to solve a given problem . It is
also known as well defined structured.

10
2. Flow charts : A flow chart s a graphical representation of step by step an algorithm
to solve a given problem.
3. Pseudo code : it is an informal way of describing the steps of a program solution
without using any strict programming language syntax or underlying technology
consideration.
4. Decision tree : It is way of presenting rules in hierarchical and sequential structure
where based on the hierarchy of rules.

It is simplest form of “if” statement . When given condition is true then output will be
display or generated otherwise no output or display.

Format of “ if “ :-

if (conditions)
Statement ;

Format of “if --- else “ :-

In this, when condition is true then output will generated and when condition is false then
output will also generated.

if (condition)
Statement 1;
else
Statement 2 ;

Format of “ if—elif—else “:-

if condtion1
Statement 1 ;
elif condition 2
Statement 2 ;
elif condition 2
Statement 3 ;
--------------------------
--------------------------
else :
Statement 17

11
Range function :-

The range( ) function of Python generate a list. Which is special sequence type . A
sequence in Python is a succession of values bound together by a single name. Examples of
Python sequence types are : Lists, Tuple, String etc.
Format of range function is
range(<lower limit>, <upper limit> )
# both limit should be integers
If range(0,5) then produce [0,1,2,3,4]
If range (5,0) then no list produce
Format
Range(< lower limit>, <upper limit>,<step value>
# both limit and step value should be integers
If range(0,10,2) then (0,2,4,6,8)
If range(5,0,-1) then (5,4,3,2,1 )
Format
range(number)
# number should be interger
If range(5) then (0,1,2,3,4)

For Loop :-

The “for “ loop of Python is designed to process the items of any sequence .
Format for ‘for loop is given below
for <variable name> in [sequence] :
Statements
Where :
Variable Name : it is name of the variable
Sequence : it is use for how many time loop will be executed.
Examples
for a in [1,4,7] :
print (a)
print (a *a)
Output : 1 1 4 16 7 49

While loop :-
A While loop is a conditional loop that will repeat the instructions within itself as long as a
condition remain same.
Format I given below
While <logical expression> :
Loop body

12
Examples
a=5
While a > 0 :
Print (“Hello”, a)
A=a-3
Print(“Loop is over, dear”)
Output
Hello 5
Hello 2
Loop is over, dear
Break jump statement :-
The ‘Break’ statement enables a program o skip over a part of the code . A break
statement terminates the loop in lies within. Execution resumes at the statement
immediately.
Examples :
a=b=c=0
For in in range(1,21):
A = int(input(“Enter Number 1”))
B = int(input(“Enter Number 2”))
If b == 0 :
Print(“ Division by Zero Error ! Aborting )
break
else
C=a/b
Print (“Quotient = “,c)
Print (“Program is over”)

Continue jump statement:-

In the continue statement before the “continue “ keyword code will be repeating until given
condition will be satisfy but in continue statement force the next iteration of the loop to
take place.
Examples :
a=b=c=0
For in in range(1,21):
A = int(input(“Enter Number 1”))
B = int(input(“Enter Number 2”))
If b == 0 :
print(“ \n the denominator can not be zero, Enter again” )
continue
else
C=a/b
print (“Quotient = “,c)

13
MCQ (01 Marks)
i. How many type of flow of control ? Two
ii. How many types of statement ? Three
iii. Without range we can use “for” loop ? yes
iv. Is “if” use for looping ? No
v. How many part of range function ? three
vi. “ While” is similar to “for” ? yes
vii. “continue” and “break” are jump statement ? yes
viii. “exit( )” is keyword ? No.

Very Short Questions Answers (02 Marks)


i. Write format of “if – else “
Answer :
if <condition> :
statement
else :
statement
ii. Write a program to enter your name and print it.
Answer :
Name = input(“Enter your name”)
print(“ Enter Name is : “, Name)
iii. Write a program to print series of Natural Numbers upto 100.
Answer:

for i in range (1 , 100, 1)


print( i)
print(“\n”)
Short questions Answers (03 Marks)
i. Write a Program to print sum of two numbers.
Answer :
Num1 = int(input(“Enter values of Num1 “))
Num2 = int(input(“Enter values of Num2 “))
Sum= Num1 + Num2
print( “Sum of the Numbers =”, Sum)

ii. Write a program to print the sum of series up to entered number.


Answer :
N = int(input(“Enter values of N:”))
sum=0
for i in range( 1, N, 1)
sum = sum + i

Print( “Sum of the Number is :”, sum)

14
Long Questions Answers (04 Marks )
i. Write a program to perform basic operation of calculator. (Write itself)

Name of Topic : String


Introductions :- When we enclosed any things in double quotes is known as string. It is
immutable data type.
Examples : “Purujee” , “Hello Dear”, “Hi Pythonian”

Note :
Some time we enclosed some things in single quotes they also known as String.
Examples : ‘ Hi Dear Students ‘ , ‘ Are to ready to read Pyhton’

When we enclosed any things in triple quotes that is known as doc string.
Examples : ‘ ‘ ‘ Hi Purujee ‘ ‘ ‘ , ‘ ‘ ‘ Are you from Where ‘ ‘ ‘

Traversal of String : All operation on string perform on the basis of Indexing. When we
travel all string character one by one that is known as traversal of string.
Example :-

0 1 2 3 4 5 6 Forward Indexing
P U R U J E E Name of String
-7 -6 -5 -4 -3 -2 -1 Backward Indexing

Note
Forward Indexing start from Zero (0) but backward indexing start from (-1)

Operation on string:
We can perform following operation on string :-
Suppose String name is : str =”Purujee” str1 = “ from Patna”
Name of operation Format Examples
Slicing Name of String[start : stop: step ] Str [ 0,5,2] then output : “Prj”
Concatenation Str3 = str1 + str2 Str + str 1 then output “
Purujeefrom Patna
Repletion Name of string * < + ve integer values> Str * 2 then output :
PurujeePurujee
Memberships <substring> in / not in <string> Pu in Purujee then Output : True
Reverse String [ :-1 ] Str[:-1] then output : eejuruP

We are using different type of function to perform the different type of operation on String.
Some important string functions are given below :-

15
Suppose String name is : str =”Purujee” str1 = “ Patna # Bihar ”
S.No Name of Function Operation Examples
1 len( ) Find length N = len(str) then N = 7
2 capitalize( ) Return upper str3 = str. capitalize( ) then PURUJEE
case
3 split ( ) Return str1.split( “#” ) then [“Patna” , “Bihar”]
substring
4 replace( ) Replace string str1.replace(“Patna”, “Patliputra”) then
“Patliputr # Bihar”
5 lower( ) Return Lower Str. Lower( ) then “purujee”
case
6 lstrip( ) Remove space Str1.lstrip( ) then “Patna # Bihar ”
from left side
7 rstrip( ) Remove space Str1.rstrip( ) then “ Patna # Bihar”
from right side
8 isspace( ) Return True if Str.isspace( ) then true
whitespace is
present
otherwise false
9 ord( ) Return ASCII ch = ‘b’ then ord(ch) output 98
code of
character
10 chr( ) Return ch = 98 then chr(ch) output b
character
values
11 isalpha( ) Return true if str.isalpha( ) then True
all characters
are alphabets
otherwise false

MCQ (01 Marks)


i. String are enclosed in………………… quotes.
ii. String character can be modified. Yes / Not
iii. String operation based on……………
iv. Indexing is ………….. and ………….
v. isdigit ( ) is a ………………………….
vi. String slicing is similar to the range function. Yes or not
vii. Traversal of string accessing …………. Elements of string.
viii. Choose correct one
i. “PuruJee” iii. ‘ ‘ ‘ PuruJee ‘ ‘ ‘
ii. _PuruJee’ iv. All correct
ix. String is ……………… data type.
x. Without function, can we perform operation on string. Yes /Not

16
Very Short Questions Answers (02 Marks).
i. What do you mean by String ?
ii. What do you mean by Indexing of String ?
iii. What do you mean by Traversal of string ?
iv. Write about the split ( ) function of string .
v. String can be modify. Explain
vi. Write a program to enter a string and display on screen.
vii. Write a program to add two different string.
viii. Write a program to print index of entered string.

Short questions Answers (03 Marks)


i. Write output of given string statement , if given string : str = “Purujee”
P u r u j e e
0 1 2 3 4 5 6
-7 -6 -5 -4 -3 -2 -1

Answer :
a. str[1:3] then “ur”
b. str [ :3 ] then “Pur”
c. str[ 3: ] then “ujee”
d. str[ : ] then “Purujee”
e. str[ - 2: ] then “ee”
f. str[: - 2 ] then “Puruj”
g. str[ : : 2] then “Prje”

ii. Write a program to show traversal of string.


iii. Write a program to entered a string and display its reverse order.
iv. Write a program to accept a string and return a string having first letter of each
word in capital letter.
Answer :-
str = input(“Enter a string”)
print(“Enter string is “, str)
str1 = “ “
x = str.split( )
for i in x :
str1 + = a.capitalize( )
print( str1)

17
Name of Topic : List
Introductions :-
The lists are containers that are used to store a list of values of any type. Basically list is
mutable. We Known as which value will be change they are known as mutable in Python .
List is mutable but string and tuples are immutable.
When we enclosed any number, character, symbol in big square bracket. That type of
collection is known as list .We are using three types of list
1. The Empty list Example:: L = list ( )
2. Long List Example :: sqrs = [0,1,4,9,16,25,36,49,64,81,100]
3. Nested List Example :: L1 = [1,3, [4,5],7,8]
Creating list from existing Sequences .
Format :-
L = list ( <sequence>)
Where <sequence > can be any kind of sequence object including string, tuple ad list
>>> L1 = list(“hello”)
>>> L1
[‘h’, ’e’ ,’l’ ,’l’ ,’o’]

Format for creation of list


<name of list> = list/eval(input(“please enter list element :”))
Example
L1 = = list(input(“please enter list element :”))
When above code will be execute then following prompt will be appear on screen then after
we enter require list values through keyboard
please enter list element : 234567
>>> L1
[‘2’, ’3’, ’4’, ’5’, ’6’, ’7’]
Note : eval(‘4’ +’8’) will display 12

Accessing List :-
For Accessing of list we are using following methods
1. Length : use function len(L) for items count in list
2. Indexing and slicing
3. Membership function (in, not in)
4. Concatenation and replication operators
Accessing Individual elements of list
Example
>>> vowels = [‘a’, ’e’ ,’I’ ,’o’ ,’u’]
Then
>>> vowels[0] then ‘a’ wil display
>>> vowels [-1] then ‘u’ will be display

For Comparing of list use relational operators

18
Example
>>> L1, L2 = [1,2,3] ,[1,2,3]
>>> L3 = [1, [2,3]]
Now
>>> L1= = L2
True
But When
>>> L1 = = L3
False

Different other Operations on List :-


We can perform different types of operation on list with support of operators
1. Joining Operation on list
If >>> L1 = [1,2,3]
>>>L2 =[1,2,3]
Than
>>> L1 + L2
Then
[1,2,3,1,2,3]
Similarly we can add more than two list
2. Repeating of list
If >>> L1 = [1,2,3]
>>> L1 * 2
Than
[1,2,3, 1,2,3 ]
Slicing of list
Format
seq = <name of list> [Start : stop]
Or
seq = <name of list> [Start : stop : step]
Example
>>> L1 = [1,2,3,4,5,6,7,8]
>>> seq = L1 [3 :-3]
>>> seq
Than
[4,5,6]
Now We want to modify list than
>>> seqc[1] = 55
Than
>>> seq
[4,55,6]

19
Working With List :-

1. Appending Items of List


Format
<list name>. append(item values)
Example
>>> L1 = [1,2,3]
>>> L1.append(6)
>>> L1
Than
[1,2,3,6]
2. Updating elements of list
Format
<list name> [index no.]= <new value>
Example
>>> L1 = [1,2,3]
>>> L1[2]=10
>>> L1
Than
[1,10,3]

Deleting Element from List :-

Format
del <name of list> [<index>]
Or
del <name of list> [start : stop ]
Example
>>> L1 = [1,2,3,4,5,6,7,8,9,10]
>>> del L1= [5]
>>> L1
[1,2,3,4,5,7,8,9,10]
>>> del L1 =[3,7]
>>> L1
[1,2,3,9,10]

Function and Method of List :-

We are using different types of function and method for performing different types of
operation on list.
1. Index Method : list .index(<item>)
2. The append method : list.append(<item>)
3. The Extend method : list .extend(<item>)

20
4. The Insert Method : list. Insert (<pos>,<item>
5. The Pop method : list .pop(<index>)
6. The remove method : list .remove(<value>)
7. The Clear Method : list.clear( )
8. The count method : list. Count(<item>)

Join Two different List :-

list1 = ["a", "b" , "c"]


list2 = [1, 2, 3]

list3 = list1 + list2


print(list3)
Output of above Program
[‘a’,’b’,’c’,1,2,3]

Use of extend( ) function :-

list1 = ["a", "b" , "c"]


list2 = [1, 2, 3]

list1.extend(list2)
print(list1)
Output of above Program
[‘a’,’b’,’c’,1,2,3]

Use of “for” loop in List :-

L1= ["apple", "banana", "cherry"]


for x in L1:
print(x)
Output of above program
apple
banana
cherry

Sum of element of List items :-


list2 = [1, 2, 3]
sum =0
for i in list2:
sum=sum+i
print(sum)
Output of above program 6

21
Some Useful program of List :-

L1 =[1,2,3,4,5,6,7,8,9,11,22,33,44,55,66]
L2=['a','b','c']

# Find length of List


n=len(L1)
print("lenght of List L1 is = ",n)

# Print Sum of elements of List L1


sum=0
for i in L1:
sum=sum+i
print("Sum of the given List is = ",sum)

#Values of subscripts of List


for j in range(0,n,1):
print("List L1 index [",j,"] is =",L1[j])
print("\n")

# Add two different List


L3=L1 +L2
print(L3)

# Use extend fuction in List


L4=["Puru","Is","Guru"]
L2.extend(L4)
print(L2)

MCQ (01 Marks)


1. Which of the following commands will create a list?
a) list1 = list()
b) list1 = []
c) list1 = list([1, 2, 3])
d) all of the mentioned Answer :d
2. What is the output when we execute list(“hello”)?
a) [‘h’, ‘e’, ‘l’, ‘l’, ‘o’]
b) [‘hello’]
c) [‘llo’]
d) [‘olleh’] Answer :a

22
3. Suppose list1 is [2445,133,12454,123], what is max(list1)?
a) 2445
b) 133
c) 12454
d) 123 Answer : c
4. Suppose list1 is [1, 5, 9], what is sum(list1)?
a) 1
b) 9
c) 15
d) Error Answer : c
5. Suppose list1 is [2, 33, 222, 14, 25], What is list1[:-1]?
a) [2, 33, 222, 14]
b) Error
c) 25
d) [25, 14, 222, 33, 2] Answer : a

Very Short Questions Answers (02 Marks)


1. What do you mean by List Slicing ?
Answer : When specific portion or part subtract from given List that process is
known as slicing.
Example :
If L1 = [1,2,3,4,5]
Then L1 [1:3:1] = [ 2,3]
2. How many type of List.
Answer : List is normally three types
a. Normal list
b. Long List
c. Nested List
3. What do you mean by traversal of List ?
Answer : When we try to accessing all element of given list one by one that process
is known as traversal of list. This process is totally depend upon indexing of list.

Short questions Answers (03 Marks)


1. Write down the use of following functions ?
1. len( )
2. index( )
3. append( )
4. clear( )
5. insert( )
6. append( )
Answer : See above Table

23
2. What is difference between string and list ?
Answer :
List String
It is mutable It is immutable
It is three type It has not type
Example : L1 = [1,2,3,4] Example: str =”Purujee”

3. Write a program to traversal of string.


Answer :
L1 =list(input(“Enter Element of L1 list :”)
L = len( L1)
for i in range(0, L, 1):
print(“ Element of L1 at index [“ , i , “]”, L1[ i ] )
print(“\n”)

Name of Topic : Tuples


Introductions :-
Tuples is immutable data type . It is a type sequence like string and list but it differ from
them in the way that list are mutable but string and tuples are immutable.

Creation of tuple is similar to the list but at the place of big bracket we put the small
bracket ( )
Format
<name of tuple> (values of tuple) #separated by comma
Example
>>> TP=(1,2,3)
Types of Tuple
1. The Empty Tuple :: >>> TP =( )
2. Single Element Tuple :: >>> TP =(1)
3. Long Tuple :: >>> TP =(1,2,3,4,5,6,7,7,8,9,12)
4. Nested Tuple :: >>> TP = (1,2 ,(3,5))

Creating Tuple from existing Sequence


Format
>>> name of Tuple =tuple(<sequence>)
Example
>>> T1 = tuple(“puruji”)
>>> T1 than (‘p’, ’u’, ’r’, ’u’, ’j’, ’I’)
Format 1
Name of tuple =tuple(input(“Enter desire tuple”))
Examples
>>> T2 =tuple(input(“Enter Tuples”))

24
Enter Tuples 1135
>>> T2 than
(‘1’, ’1’, ’3’, ’5’)

For Accessing of tuples we are using following methods


1. Length or len(T) : it return no of items in given tuple
2. Indexing and slicing
3. Membership operators (in , not in )
4. Concatenation and replications operators ( +, *)
Example
>>> T1 =(‘p’, ’u’, ’r’, ’u’, ’j’, ’i’)
Than
>>> T1[0] then ‘p’
>>> T1 [-1] then ‘i’

Different types of operation on Tuple :-

We can perform different types of operation


1. Joining of Tuples
Example
>>> T1 = (1,2,5)
>>> T2 =(2,3,4)
>>> T1 + T2 then (1,2,5,2,3,4)
Slicing the Tuples
Format
seq= <name of tuple> [ start : stop]
Example
>>> T1 =(10,20,30,40,50,60,70,80)
>>> seq =T1 [3,-3]
(40,50,60)

For comparing of tuples using different types of relational operators


Example
>>> T1 =(1,2,3)
>>> T2 =(1,2,3)
Then
>>> T1 = = T2 then true
>>> T1 =(1,5,3)
>>> T2 =(1,2,3)
Then
>>> T1 = = T2 then false
Deleting Tuples

25
>>> del <name of tuple>
Or
>>> del <name of tuple> [subscript of tuple]
Examples
>>> T1 =(1,2,3)
>>> del T1 then >>> T1 no exist
>>> del T1 [0] then >>> T1 (2,3) will be display

Different type of Functions:-

We are using different types of method and function for performing different types of
operation on given tuples. Some important function /methods are given below :
1. The len( ) method : it is use for find out the length of tuples Example : >>> T1
=(1,2,3) than >>>len(T1) than result will be 3.
2. The max( ) method : it is use for find out the maximum values of the tuple Example
: >>> T1 =(1,2,3) than >>>max(T1) than result will be 3.
3. the min( ) method : it is use for find out the maximum values of the tuple Example :
>>> T1 =(1,2,3) than >>>min(T1) than result will be 2.
4. The index( ) method : it is use for fid out the index of tuple element in tuple Example
: >>> T1 =(1,2,3) than >>>index.T1(1) than result will be 0.
5. The count ( ) function : it is use for count the how many specific elements in tuple.
Example : >>> T1 =(2,1,2,3,2,3,2,4,2) than >>>T1.count(2) than result will be 5.
6. The tuple( ) method : It is use for create tuples from existing tuple.
Format tuple (<Sequence>)
Examples :-

# Creating empty tuple


Example
>>> tuple( )

# creating tuple from string


Example
>>> T1 = tuple (“abc”)
>>> T1 then (‘a’ ,’b’, ‘c’)

# Creating a tuple from a list


Example
>>> T1 = tuple([1,2,3])
>>> T1 then (1,2,3)

26
# Creating a tuple from keys of dictionary
Example
>>> T1 = tuple({ 1 : “3”, 2: “4”})
>>> T1 then (3,4)

MCQ (01 Marks)


1. Which of the following is a Python tuple?
a) [1, 2, 3]
b) (1, 2, 3)
c) {1, 2, 3}
d) {}
2. Suppose t = (1, 2, 4, 3), which of the following is incorrect?
a) print(t[3])
b) t[3] = 45
c) print(max(t))
d) print(len(t))
3. What will be the output of the following Python code?

1. >>>t1 = (1, 2, 4, 3)
2. >>>t2 = (1, 2, 3, 4)
3. >>>t1 < t2
a) True
b) False
c) Error
d) None

Very Short Questions Answers (02 Marks)


1. What do m you mean by Tuple?
Answer : Tuple is immutable data type. Its elements enclosed in small bracket. One
element sperate from other through comma.
Example :
T1 = (“a”,”b”,”c”)
T2 =(1 , 2 , 3 , 4 )
2. What do you mean by traversal of Tuple ?
Answer : When each and every elements of given tuple accessing one by one that
process is known as traversal of Tuple. This process is totally depend upon indexing
of tuple.

27
Short questions Answers (03 Marks)
1. Write a program to traversal of given tuple ?
Answer
T1 = (“a”,”b”,”c”)
L = len(T1)
for i in range (0 , L , 1) :
print( “ Element of Tuple at index [“ , i , “] =” , T1[i] )
print( “\n”)

Name of Topic : Dictionary


Introductions :-

Dictionary is way which is use for organize the data in proper form. We can perform
different types of operation on dictionary with support of function and methods. It is
mutable unordered collection with elements in the form of a” key:value “ pair that
associate keys to values.

Creating a Dictionary :-

Format
<name of dictionary > = {<key : value> , <key : value > …………………………………..}
Example
School = { “teacher “: “Ram” , “salary “ : 10000 , “Hobbies” : “ Chess”}
Note : key of dictionary must be of immutable type.

Format
>>> <dictionary name> [<key>]
Examples
>>> School = { “teacher “: “Ram” , “salary “ : 10000 , “Hobbies” : “ Chess”}
>>> school [“Teacher”]
Then
Ram
>>> school [“salary”]
Then
10000
>>> print (school[“Teacher”])
Then
Ram

Main characteristics of dictionary are given below :

28
1. Unordered set
2. Not a sequence
3. Indexed by Key , no number
4. Keys must be unique
5. Mutable
6. Internally stored as mapping
Note : the key of dictionary must be of immutable types such as number or string. A tuple
can also be a key provided a contains immutable elements.

Working on dictionary through different way. Some are given below


1. Multiple ways of creating Dictionaries
1.1 Initializing a dictionary
1.2 Creating a Dictionary from name and value pairs
1.3 adding key : value pairs to an empty dictionary
2. Adding element in Dictionary
3. Updating existing element in dictionary
4. Deleting element from dictionary
5. Checking for existence of a key element
6. Pretty Printing a dictionary
7. Counting frequency of element in a list using dictionary

Different Functions :-

We Are using different types of function and method in dictionary for performing
different types of operations. Some are given below
1. The len( ) method : it is use for find out the length of dictionary.
Format >>> len(<name of dictionary>)
2. The clear( ) method : It is use for make dictionary empty
format : >>> <name of dictionary> . <clear>
3. The get( ) method : it is use for find out the similar things in given dictionary
format : <name of dictionary> .get (key. [default])
4. The items( ) method :it is use for return all the items of dictionary.
Format : >>> <name of dictionary> . Items( )
5. The keys( ) method : it is use for return the all keys of the dictionary.
Format : >>> <name of dictionary> . Keys ( )
6. The values( ) method : it is use for return the value of the dictionary
format : >>> <name of dictionary> . Values( )
7. The update ( ) method : It is use merger key :value pair from the new dictionary
into the original dictionary , adding or replacing as needed. Format : >>>
<dictionary> .update (other dictionary

29
MCQ (01 Marks)
1. Dictionary is ……………….
2. Keys and Values are associated ………….
3. Keys values can be change …………..
4. Values of dictionary can not change…………
5. Dictionary totally depend upon …………….

Very Short Questions Answers (02 Marks)


1. How to traversal in Dictionary?
Answer : When we accessing each and every elements of given dictionary in
sequential mode on the basis of dictionary index that process is known as traversal
of Dictionary.
2. Write about the dictionary?
Answer : Dictionary is mutable data type. Their elements are enclosed in curly
bracket. Its elements are present in the form of key : values pair. But keys values
are immutable and values are mutable.

Name of Topic : Searching Techniques


Introductions :-

Sorting in computer means arranging these elements in a specific order. It may be


ascending or descending order.
Examples
S1 = [8,4,6,7,1,5]
Then
If we write
[1,4,5,6,7,8] is ascending order
But if we write
[8,7,6,5,4,1] is descending order.
Both are example of the sorting

Bubble sorting :-
The basic idea of bubble sort is to compare two adjoining values and exchange them if they
are not proper order. Until all given elements are not come to the proper order.

Insertion Sorting :-
It is a sorting algorithm that builds a sorted list one element at a time from the unsorted
list by inserting the element at its correct position in sorted list

30
MCQ (01 Marks)
1. The process of placing or rearranging a collection of elements into a particular
order is known as
a. Searching
b. Sorting
c. Rearranging
d. Merging
2. Sort is the simplest sorting algorithm that works by repeatedly swapping the
adjacent elements in case they are unordered in n-1 passes.
a. Bubble
b. Insertion
c. Complexity
d. Selection

Name of Topic : Functions


Introductions :-
A function is sub program that acts on data and often returns a value.
Example:-
def calcSomething ( x ):
r = 2 * x ** 2
return r
Where :
def. means a function definition is strating.
Calsomthing : Name of the function.
( ) : call operator of function
x : parameter of function
: it is end of the function definition line.
r : it is body of the function.
return : it is use return the function value.

Calling of function :
first way
def calcSomething ( x ):
r = 2 * x ** 2
return r

Second Way
x = int(input(“Enter a number”)
def calcSomething ( x ):
r = 2 * x ** 2

31
return r
print (calcSomething ( x ))

Types of function :-
1. Built in Function : It is pre define function
2. Function define in Module : these function are pre-define for particular module.
3. User define function : it is define by the user or programmer.

Define Functions in Python :-


General format of Function in Python
def <name of function> ( [ Parameters]) :
[“ “ “ < description of function] “ “ “]
<statement >
……………..
Examples
def Sum ( ) :
A=B+C
return C
def Display ( ):
print( “ Hello Students”)

Program to add numbers using Functions :-


Using Concepts of Function)
def calsum( x, y ) :
s=x+y
return (s )
num1 = float(input(“Enter First Number”))
num2= float (input(“Enter Second Number”))
sum =clasum(num1,num2)
print(“Sum of the given numbers is “,sum)
Where :
s,x ,y num1, num2 and sum are variable in above program.

Passing Arguments or parameters :-


Three Way to passing arguments in function :
1. Positional argument :: def sum(x,y,z)
2. Default argument : def interest (principal, rate = 1.02, time)
3. Keyword argument : it is use for calling function .
Example
interest (principal = 1000, rate = 1.02, time = 4)

32
Scope Variables in Functions :-

Scope Variable means accessing capability of variable, inside the program.


It is two type :
1. Global Variables
2. Local Variables.
Note :
Normally All variables which will declared under the “_main_” they are consider Global.
But
All variables which is declared under the function body they are consider local.

MCQ (01 Marks)


1. Which keyword is used for function?
a) Fun
b) Define
c) def
d) Function
2. What are the two main types of functions?
a) Custom function
b) Built-in function & User defined function
c) User function
d) System function
3. Which of the following is the use of id() function in python?
a) Id returns the identity of the object
b) Every object doesn’t have a unique id
c) All of the mentioned
d) None of the mentioned
4. Which of the following refers to mathematical function?
a) sqrt
b) rhombus
c) add
d) rhombus
5. What will be the output of the following Python code?

1. def cube(x):
2. return x * x * x
3. x = cube(3)
4. print x
a) 9
b) 3
c) 27
d) 30

33
Very Short Questions Answers (02 Marks)
1. How many types of functions .
Answer : Basically function is two type
a. Pre define functions ; Its output is fixed.
b. User define function : Its output is not fixed. This function start from “ def ”
keyword.
2. What do you mean by default arguments ?
Answer : Default argument is parameter of parametrized function. When we do not
passing the parameters in this situation function accept define parameter values
itself that is known as default parameters.

Short questions Answers (03 Marks)


1. Write a program to display sum of two number using function. (write itself)

Long Questions Answers (04 Marks )

1. Write program to calculate area of triangle, circle , square and rectangle using
function. (write itself)

Name of Topic : Exception handling


Introductions :-
Exception handling allows you to separate error-handling code from normal code. An
exception is a Python object which represents an error. As with code comments, exceptions
helps you to remind yourself of what the program expects. It clarifies the code and
enhances readability.

Python Exceptions are :-


Exception Cause of Error

AssertionError Raised when an assert statement fails.

AttributeError Raised when attribute assignment or reference fails.

EOFError Raised when the input() function hits end-of-file condition.

FloatingPointError Raised when a floating point operation fails.

34
MCQ (01 Marks)
1. How many except statements can a try-except block have?
a) zero
b) one
c) more than one
d) more than zero
2. Is the following Python code valid?
try:
# Do something
except:
# Do something
finally:
# Do something
a) no, there is no such thing as finally
b) no, finally cannot be used with except
c) no, finally must come before except
d) yes

3. When is the finally block executed?


a) when there is no exception
b) when there is an exception
c) only if some condition that has been specified is satisfied
d) always
4. Can one block of except statements handle multiple exception?
a) yes, like except TypeError, SyntaxError [,…]
b) yes, like except [TypeError, SyntaxError]
c) no
d) none of the mentioned
5. When will the else part of try-except-else be executed?
a) always
b) when an exception occurs
c) when no exception occurs
d) when an exception occurs in to except block

35
Scoring tips for Students

• Try to write neat and clean in proper manner


• Try to use double colour pens.
• Try to include examples during the explanation of questions.
• Firstly solve all easy questions.
• Give proper space and margin between two questions answers.

Any others.
All contents are based on the CBSE examination pattern for the CBSE Board examination
2023-24.

36
Files – Text Files

A text file stores information in the form of a stream of ASCII or Unicode characters.In text files, each line of
text is terminated, (delimited) with a special character knownas EOL (End of Line) character. In Python, by
default, this EOL character is the newline character ('\n') or carriage-return, newline combination ('\r\n').
The text files can be of following types:

Regular Text files: These are the text files which store the text in the same form as typed. Here the newline
character ends a line and the text translationstake place. These files have a file extension as .txt.
Delimited Text files: In these text files, a specific character is stored to separate the values, i.e., after each
value, e.g., a tab or a comma after everyvalue.
a. When the comma is used to separate the values stored, these are calledCSV files (Comma Separated Values
files). These files take the extensionas .csv.
Files – Binary Files
A binary file stores the information in the form of a stream of bytes. A binary file contains information in the
same format in which the information is held in memory,i.e., the file content that is returned to you is raw (with
no translation or no specificencoding). As a result, binary files are faster and easier for a program to read and
write than are text files. As long as the file doesn't need to be read by people or needto be ported to a different
type of system, binary files are the best way to store program information.

File Object: A file object is a reference to a file on disk. It opens the file and makesit available for a number of
different tasks.
Absolute Vs Relative path:
An absolute path is defined as specifying the location of a file or directory from theroot directory. In other
words, we can say that an absolute path is a complete pathfrom start of actual file system from / directory.
Relative path is defined as the path related to the present working directly.

File Modes: A file mode govern the type of operations (read/write/append)possible in the opened file.
Sr.No. Modes & Description

r: Opens a file for reading only. The file pointer is placed at the beginningof the file. This is
1 the default mode.
r+: Opens a file for both reading and writing. The file pointer placed atthe beginning of
2 the file.
w: Opens a file for writing only. Overwrites the file if the file exists. If thefile does not exist,
3 creates a new file for writing.
w+: Opens a file for both writing and reading. Overwrites the existing fileif the file exists. If
4 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
5 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 theend of the file if the
6 file exists. The file opens in the append mode. If thefile does not exist, it creates a new file
for reading and writing.

37
File Read Methods:
Sr.N
Methods & Description
o.
Filehandle.read([n]): reads and return n byres, if n is not specified itreads entire file.
1
Filehandle.readline([n]): reads a line of input. If n is specified reads atmost n bytes. Read
bytes in the form of string ending with end of line character of blank string if no more
2
bytes are left for reading.
Filehandle.readlines(): reads all the lines and return them in a list.
3

File Write Methods:


Sr.No. Methods & Description

Filehandle.write(str): Write string str to file referenced by filehandle.


1
Filehandle.writelines(L): Write all strings in list L as lines to filereferenced by
2 filehandle.

Opening text file:


open() function: The open() function is used to open a file in the following manner:
<file-objectname> = open(<filename>)
<file-objectname> = open(<filename>,<mode>)
By default the file open mode is read mode.

with statement: with statement will automatically close the file after the nested blockof code. It is guaranteed to
close the file no matter how the nested block exits. Evenif an exception occurs with statement will handle it and
close the file. It is used in thefollowing manner:
with open(<filename>,<filemode>) as <filehandle>:
<file manipulation statements>

Closing a text file: A close() function breaks the link of file-object and the file on the disk. No tasks cab be
performed after the file is closed.
It is used in the following way:
<file-handle>.close()

The tell() Function: The tell() function returns the current position of the file pointerin a file. It is used as per the
following syntax:
<file-object>.tell()

The seek() Function: the seek() function changes the position of the file pointer byplacing the file pointer at the
specified position in the opened file. It is used as per the following syntax:
<file-object>.seek(offset[, mode])
offset: is a number specifying number of bytes.
mode: 0 – for beginning of the file – by default 0
1 – for current position of file pointer
2 – for end of the file

38
The seek() Function: the seek() function changes the position of the file pointer byplacing the file pointer at the
specified position in the opened file. Its is used as per the following syntax:
<file-object>.seek(offset[, mode])
offset: is a number specifying number of bytes.
mode: 0 – for beginning of the file – by default 0
1 – for current position of file pointer
2 – for end of the file
Questions – 1 Mark - MCQ

Q1. To open a file c:\ss.txt for appending data we use


a. file = open(‘c:\\ss.txt’,’a’)
b. file = open(r‘c:\ss.txt’,’a’)
c. file = open(‘c:\\ss.txt’,’w’)
d. both a and b

Q2. To read the next line of the file from the file object infi, we use
a. infi.read(all)
b. infi.read()
c. infi.readline()
d. infi.readlines()
Q3. Which function is used to ensure that the data in written in the file immediately?
a. <filehandle>.write()
b. <filehandle>.writelines()
c. flush()
d. <filehandle>.close()
Q4. What is the datatype of the value returned by readlines() function?
a. Integer
b. String
c. List of strings
d. None of the above

Q5. What is the position of the cursor when the file is opened in append mode?
a. Start of file
b. End of file
c. At the 11th byte
d. Unknown

Q6. How to open a file such that close function is not needed to be called in orderto close the connection
between file and python program?
a. Using open() method
b. Using read() method
c. Using with keyword
d. Using open with method

39
Q7. What is the full form of CSV?
a. Common segregated values
b. Comma separated values
c. Common separated values
d. None of the above

Q8. If a file is opened for writing


a. File must exist before opening
b. File will be created if does not exist
c. None of the above
d. Both a and b

Q9. If the cursor in the file is at the end of the file, then what will the read()function return?
a. None
b. False
c. Exception
d. Empty string
Q10. Which is the value of mode parameter to set the offset of the cursor from theend of the file?
a. 0
b. 1
c. 2
d. None of the above

Answer Key
1.d 2.c 3.c 4.c 5.b 6.c 7.b 8.a 9.d 10.c
Questions – 2 Marks – Short Answer
Q1. What is the difference between opening mode ‘a’ and ‘w’?
Q2. What is the purpose of flush() in file handling operations?
Q3. What is the advantage of opening file using with keyword?
Q4. Given a file ‘data.txt’ write a function atoesidp() to display the file after replacing ‘a’ with ‘e’.
Q5. What is the advantage of saving a file in text form and binary form?
Q6. Write the output of the following program
f = open(‘data.txt’, ’w+’)
f.write(‘0123456789abcdef’)
f.write(‘xyz1234’)
f.seek(0)
print( f.read())
f.close()

Q7. If a file ‘f.txt’ contains data ‘Good’ and then what is the content of the file
f.txt then following program in run?
f = open(‘f.txt’, ‘w’)
f.write(‘Bye’)
f.close()

S. Answer Key
No

40
1 ‘w’ is used to write in file from the beginning. If file already exists then it
will overwrite the previous content.
‘a’ is also used to write in the file. If file already exists it will write after
the previous content.
2 The flush function forces the writing of data on disk still pending in output
buffer. Flush allows the user to send the content in file before closing thefile.

3 With keyword reduces the overheads involved in the closing of the file after file operation
or handling the file closing after exception have occurred. When file is opened using
‘with’ it will manage the closing of file
at the end of the operations or after an exception automatically.
4 def atoedisp():
f = open(‘data.txt’)
r = f.read()for ch in r:
if ch == ‘a’: print(‘e’, end = ‘’)
else:
print(ch, end = ‘’)
5 Text files are stored in the human readable format. These have someinternal conversions
like newlines etc.
Binary file store data in pure binary form and hence can be used on anymachine/hardware
with appropriate software.
6 0123456789abcdefxyz1234
7 Bye
Existing data will be overwritten.
Questions – 3 Marks – Long Answer

Q1. Write a program to read a text file and display the count of lowercase and uppercase letters in the file.

Q2. Write a method in python to read lines from a text file INDIA. TXT, to find and display the Occurrence of
the word "India".

Q3. Write a function count_line() in python that counts and display the lines starts with ‘P’ in the text file named
“data.txt”.
Q4. Write a program to read a text file line by line and display each word separated by a #.
Q5. Write a function vowelCount() in python that counts and display the numbers of vowels in the text file named
“Story.txt”.
S. Answer Key
No
1. myfile = open( "Answer.txt", "r")
ch = “ ” #initially stored a space ( a non-None value)
lcount = 0 #variable to store count of lowercase letters
ucount 0
while ch: #while ch stores a Non-None
valuech = myfile.read(1) #one character read from file
if ch.isupper() == True:
ucount ucount+1
else:
lcount = lcount + 1
print("Uppercase letters in the file: ", ucount)
41
print ("Lowercase letters in the file: ", lcount)
myfile.close()#close the file

2. def display1():
count = 0
file = open( 'INDIA. TXT ‘, 'r’)
LINE=file.read()
Words=LINE. split()
for W in Words:
if W= "India":
count count +1
print (count)
file.close()
3. def countline():
f=open(“data.txt”,’r’)
lines=f.readlines()
for i in lines:
if i[0]= = ‘P’:
print(i)
f.close()
4. myfile = open( "Answer.txt", "r")
line = " ”
while line:
line = myfile.readline() # one line read from file
# printing the line word by word using split()
for word in line.split():
print (word, end = '#’)
print()
#close the file
myfile.close()
5. def vowelCount():
f=open(‘Story.txt’,’r’):
s=f.read()
vow=[‘A’,’E’,’I’,’O’,’U’,’a’,’e’.’i’,’o’,’u’]
count=0
for x in s:
if x in vow:
count+=1
print(“No. of vowels in the given txt file is:”,count)
f.close()

Binary Files
Binary files store data in the binary format (0’s and 1’s) which is understandable bythe machine. So when we open
the binary file in our machine, it decodes the data and displays in a human-readable format.

Binary File Modes: File mode governs the type of operations read/write/appendpossible in the opened file. It
refers to how the file will be used once its opened.
File Description
Mode

42
rb Read Only: Opens existing file for read operation
wb Write Only: Opens file for write operation. If file does not exist, file is
created. If file exists, it overwrites data.
ab Append: Opens file in write mode. If file exist, data will be appended
at the end.
rb+ Read and Write: File should exist, Both read and write operations can
be performed.
wb+ Write and Read: File created if not exist, If file exist, file is truncated.
ab+ Write and Read: File created if does not exist, If file exist data is
truncated.

Pickle Module: Python Pickle is used to serialize and deserialize a python object structure. Any object on python
can be pickled so that it can be saved on disk.

Pickling: Pickling is the process whereby a Python object hierarchy is converted into a byte stream.

Unpickling: A byte stream is converted into object hierarchy. To use the picking methods in a program, we have
to import pickle module using import keyword.

Example:
import pickle In this module, we shall discuss to functions of pickle module, which are:
i. dump( ) : To store/write the object data to the file.
ii. ii. load( ) : To read the object data from a file and returns the object data.
Syntax:
Write the object to the file:
pickle.dump(List_name, file-object )
Read the object from a file:
pickle.load(file-object)
1 Mark Questions
1. The process of converting byte stream back to the original structure is known as
a. Pickling b. Unpickling c. Packing d. Zipping

2. Which file mode is used to handle binary file for reading.


a. rb b. rw c. r d. w

3. Which of the following is not a correct statement for binary files?


a. Easy for carrying data into buffer
b. Much faster than other file systems
c. Characters translation is not required
d. Every line ends with new line character ‘\n’

4. Which one of the following is correct statement?


a. import – pickle
b. pickle import
c. import pickle
d. All the above

5. Which of the following file mode opens a file for append or read a binary file and moves the files pointer at the
43
end of the file if the file already exist otherwise create a new file?
a. a
b. ab
c. ab+
d. a+
Answer Key
1. a 2. a 3. d 4. c 5. c

5 Mark Questions

1. A binary file “student.dat” has structure [rollno, name, marks].


i. Write a user defined function insertRec() to input data for a student and add to student.dat.
ii. Write a function searchRollNo( r ) in Python which accepts the student’s rollno as parameter and searches
the record in the file “student.dat” and shows the details ofstudent i.e. rollno, name and marks (if found)
otherwise shows the message as ‘No record found’.

2. Write a python program to create binary file dvd.dat and write 10 records init Dvd id,dvd name,qty,price
Display those dvd details whose dvd price more than 25.

S.No. Answer Key


1. i. import pickle
def insertRec():
f=open("student.dat","ab")
rollno = int (input("Enter Roll Number : "))
name=input("Enter Name :")
marks = int(input("Enter Marks : "))
rec = [rollno, name, marks ]
pickle.dump( rec, f )
f.close()

ii.
def searchRollNo( r ):
f=open("student.dat","rb")
flag = False
while True:
try:
rec=pickle.load(f)
if rec[0] == r :
print(rec[‘Rollno’])
print(rec[‘Name’])
print(rec[‘Marks])
flag = True
except EOFError:
break
if flag == False:
print(“No record Found”)
f.close()
2. import pickle
f=open("pl.dat","ab")
ch="Y"
while ch=="Y":
44
L=[]
pi=int(input("enter dvd id "))
pnm=input("enter dvd name ")
sp=int(input("enter qty "))
p=int(input("enter price(in rupees) "))
L.extend([pi,pnm,sp,p])
pickle.dump(l,f)
ch=input("do you want to enter more rec(Y/N): ").upper()
if ch=="Y":
continue
else:
break
f.close()
f=open("pl.dat","rb+")
try:
while True:
L=pickle.load(f)
if L[3]>25:
print(l)
except EOFError:
pass
f.close()

Working with CSV Files: CSV (Comma Separated Values)

A csv file is a type of plain text file that uses specific structuring to arrange tabular data. csv is a common format
for data interchange as it is compact, simple and general.
Each line of the file is one line of the table.
csv files have .csv as file extension.

Let us take a data.csv file which has the following contents:


Roll No., Name of student, stream, Marks
1, Anil, Arts, 426
2, Sujata, Science, 412

As you can see each row is a new line, and each column is separated with a comma.
This is an example of how a CSV file looks like.
To work with csv files, we have to import the csv module in our program.

Read a CSV file: To read data from a CSV file, we have to use reader( ) function. The reader function takes each
row of the file and make a list of all columns.

CODE:
import csv
with open('C:\\data.csv','rt') as f:
data = csv.reader(f) #reader function to generate a reader object
for row in data:
print(row)

OUTPUT:
45
['Roll No.', 'Name of student', 'stream', 'Marks']
['1', 'Anil', 'Arts', '426']
['2', 'Sujata', 'Science', '412']

Write data to a CSV file: When we want to write data in a CSV file you have to use writer( ) function. To iterate
the data over the rows (lines), you have to use the writerow( ) function.

CODE:
import csv
with open('C:\\data.csv', mode='a', newline='') as file:
writer = csv.writer(file, delimiter=',', quotechar='"' ) #write new record in file
writer.writerow(['3', 'Shivani', 'Commerce', '448'])
writer.writerow(['4', 'Devansh', 'Arts', '404'])

OUTPUT:
['Roll No.', 'Name of student', 'stream', 'Marks']
['1', 'Anil', 'Arts', '426']
['2', 'Sujata', 'Science', '412']
['3', 'Shivani', 'Commerce', '448']
['4', 'Devansh', 'Arts', '404']

When we shall open the file in notepad (Flat file) then the contents of the file will look like this:
Roll No.,Name of student,stream,Marks
1,Anil,Arts,426
2,Sujata,Science,412
3,Shivani,Commerce,448
4,Devansh,Arts,404
1 Mark Questions

1. What does the acronym CSV stand for in its full form?
a. Common Separated Value
b. Comma System Value
c. Comma Separated Value
d. Common System Vault

2. What is the default delimiter of a CSV file


a. Tab b. Comma c. Semicolon d. Space

3. In regards to separated value files such as .csv and .tsv, what is the delimiter?
a. Any character such as the comma (,) or tab (\t) that is used to separate the row data
b. Anywhere the comma (,) character is used in the file
c. Delimiters are not used in separated value files
d. Any character such as the comma (,) or tab (\t) that is used to separate the column data.

4. In separated value files such as .csv and .tsv, what does the first row in the file typically contain?
46
a. The source of the data
b. The author of the table data
c. Notes about the table data
d. The column names of the data

5. Assume you have a file object my_data which has properly opened a separated value file that uses the tab
character (\t) as the delimiter.What is the proper way to open the file using the Python csv module and assign it to
the variable csv_reader?
Assume that csv has already been imported.
a. csv_reader = csv.tab_reader(my_data)
b. csv_reader = csv.reader(my_data)
c. csv_reader = csv.reader(my_data, tab_delimited=True)
d. csv_reader = csv.reader(my_data, delimiter='\t')

Answer Key
1. c 2. b 3. d 4. d 5. d

4 Mark Questions
1. Write a Program in Python that defines and calls the following user defined functions:
(i) ADDPROD( ) – To accept and add data of a product to a CSV file ‘product.csv’. Each record consists of a
list with field elements as prodid, name and price to store product id, employee name and product price
respectively.
(ii) COUNTPROD( ) – To count the number of records present in the CSV file named ‘product.csv’.

2. Write a Program in Python that defines and calls the following user defined functions:

(i) add() – To accept and add data of a to a CSV file ‘stud.csv’. Each record consists of a list with field
elements as admno, sname and per to store admission number, student name and percentage marks
respectively.
(ii) search()- To display the records of the students whose percentage is more than 75.

3. Manoj Kumar of class 12 is writing a program to create a CSV file “user.csv” which will contain user name
and password for some entries. He has written the following code. As a programmer, help him to successfully
execute the given task.
import ______________ #Line1
def addCsvFile(UserName, Password):
fh=open('user.csv','_____________') #Line2
Newfilewriter=csv.writer(fh)
Newfilewriter.writerow([UserName,Password])
fh.close( ) # csv file reading code

def readCsvFile(): #to read data from CSV file


with open('user.csv','r') as newFile:
newFileReader=csv.______(newFile) #Line3
for row in newFileReader:
print(row) newFile.________________ #Line4
addCsvFile('Arjun','123@456')
addCsvFile('Arunima','aru@nima')
addCsvFile('Frieda','myname@FRD')
readCsvFile()

47
(a) What module should be imported in #Line1 for successful execution of the program?
(b) In which mode file should be opened to work with user.csv file in#Line2
(c) Fill in the blank in #Line3 to read data from csv file
(d) Fill in the blank in #Line4 to close the file

4. Radha Shah is a programmer, who has recently been given a task to write a python code to perform the
following CSV file operations with the help of two user defined functions/modules:

(a) . CSVOpen() : to create a CSV file called “ books.csv” in append mode containing information of books
– Title, Author and Price.
(b). CSVRead() : to display the records from the CSV file called “ books.csv” .where the field title starts
with 'R'. She has succeeded in writing partial code and has missed out certain statements, so she has left
certain queries in comment lines.

import csv
def CSVOpen( ):
with open('books.csv','______',newline='') as csvf: #Statement-1
cw= csv.writer(csvf)
______ #Statement-2
cw.writerow(['Rapunzel','Jack',300])
cw.writerow(['Barbie','Doll',900])
cw.writerow(['Johnny','Jane',280])

def CSVRead( ):
try:
with open('books.csv','r') as csvf:
cr=______ #Statement-3
for r in cr:
if ______: #Statement-4
print(r)
except:
print('File Not Found')
CSVOpen( )
CSVRead( )

You as an expert of Python have to provide the missing statements and other related queries based on the
following code of Radha.
(a) Write the appropriate mode in which the file is to be opened in append mode (Statement 1)
(b) Write the correct option for Statement 2 to write the names of the column headings in the CSV file,
books.csv
(c) Write statement to be used to read a csv file in Statement 3.
(d) Fill in the appropriate statement to check the field Title starting with „R‟ for Statement 4 in the above
program.

S.No. Answer Key


1. import csv
def ADDPROD():
f=open(“product.csv”,” a”)
x=csv.writer(f)
prodid=int(input(“enter product id:”))
employee_name=input(“enter employee name”)
48
product_price=int(input(“enter product price:”))
rec=[prodid , employee_name , “product_price]
x.writerow(rec)
f.close()
def COUNTPROD():
f1=(“product.csv”, ”r”)
t=csv.reader(f1)
c=0
for i in t:
c=c+1
print(“total number of records in this file is:”,c)
f1.close()
ADDPROD()
COUNTPROD()

2. import csv
def add():
fout=open("stud.csv","a",newline='\n')
wr=csv.writer(fout)
admno=int(input("Enter Admission No :: "))
sname=input("Enter Student name :: ")
per=int(input("Enter percentage :: "))
st=[fid,sname,per]
wr.writerow(st)
fout.close()

def search():
fin=open("stud.csv","r",newline='\n')
data=csv.reader(fin)
found=False
print("The Details are")
for i in data:
if int(i[2])>75:
found=True
print(i[0],i[1],i[2])
if found==False:
print("Record not found")
fin.close()
#main program
add()
print("Now displaying")
search()
3. a) csv
b) w
c) reader()
d) close()
4. (a) a
(b) cw.writerow(['Title','Author','Price'])
(c) csv.reader(csvf)
(d) r[0][0]=='R‟

49
Data Structure: Stack, operations on stack (push & pop), implementation of stack using list

Introduction :

Data structures: A data structure is a named group of data of different data types which is stored in a specific
way and can be processed as a single unit. It has well defined operations, behavior and properties.

Stack: It is a linear structure implemented in LIFO (Last In First Out) manner where insertions and deletions
are restricted to occur only at one end – stack’s top.

LIFO means element last inserted would be the first one to be deleted. For example, a pile of books, a stack
of coins, where you can remove only the top book or the coin placed at the top (Fig.1).

Fig.1 : Pile of Books / Stack of Coins

Some of the applications of Stack in real life are:


➢ Pile of clothes in an almirah. Fig.1
➢ Multiple chairs in a vertical pile
➢ Bangles worn on wrist
➢ Pile of boxes of eatables in a pantry or on a kitchen shelf

Stack follows these rules :


1) Data can only be removed from the top (pop). The removal of element from a stack is called POP
operation.
2) A new data element can only be added to the top of the stack (push). The insertion of element in a stack is
called PUSH operation.

Implementation of Stack using List

The basic operations performed on the Stack are:


1. Creating a Stack
2. PUSH Operation / Adding Elements to a Stack
3. Pop Operation / Deleting Elements from a Stack
4. Traversal / Displaying a Stack.
Checking the Status of Stack : Before implementing these operations, it is important to check Stack status.

1. Creating a Stack
To create an empty Stack, use inbuilt function list() or [] as per the syntax given below:
Syntax :
Stack=list()
Stack=[]
In order to access the elements in a Stack, index values are used. Thus, the first element in the Stack will
be Stack[0], and so on.

2. PUSH Operation adding Elements into a Stack


The list function append() is used to add elements into the Stack.
Syntax:
Stack.append(x)
50
Here, x is the element to be inserted into the Stack and is inserted at the end of the list implemented as a
Stack.
peek() :peek() function is used to get the most recent value of stack, i.e., top element of the stack without
removing it or value at the top. It will throw an exception if the stack is empty or null.

3. Pop Operation/Deleting an Element from a Stack


The list function pop() is used to pop / remove/delete elements from a Stack.
Syntax :
Stack.pop()
It returns the popped / deleted elements from the list.

4. Traversing /displaying Stack Elements


In this process the elements from the top position, i.e., last inserted element, get displayed and processed
in the reverse order.

MCQ / Short Answer Type Question – 1 Mark


1. Choose the correct output for the following stack operation(* top position)
Push(5) Push(8) Pop() Push(2) Push(5) Pop() Push(1)
(a) 8 5 2 5 1* (b) 8 5 5 2 1* (c) 2 5 5 1* (d) 5 2 1*
2. Which list method can be used to perform Push operation in a stack implemented by list?
(a) append() (b) extend() (c) push() (d) insert()
3. Which list method can be used to perform Pop operation in a stack implemented by list?
(a) pop() (b) pop(1) (c) remove() (d) pop(0)
4. Consider the following operation performed on a stack of size 3, What will be the output? (* top
position) Push(10) Push(20) Push(30) Pop() Push(40) Push(50)
(a) overflow (b) underflow (c) 10 20 30 40 50* (d) 10 20 40 50*
5. What is the situation called when an insertion is attempted in a full Stack?

6. What is the situation called when read/deletion is attempted in an empty Stack?


7. LIFO data structure is?
8. Name the operation for insertion in a stack.
9. Name the operation for deletion from a stack.
10. Define Stack.

ANSWER KEY
1.(d) 5 2 1* 2. (a) append() 3. (a) pop() 4. (a) overflow 5. Overflow 6.
Underflow 7. STACK 8. PUSH 9. POP 10. It is
a linear structure implemented in LIFO (Last In First Out) manner where insertions and deletions are
restricted to occur only at one end – stack’s top.
Long Answer Type Question – 3 Marks

1. A list contains following record of a customer:


[Customer_name, Phone_number, City]
Write the following user defined functions to perform given operations on the stack named ‘status’:
(i) Push_element() - To Push an object containing name and Phone number of customers who live in
Goa to the stack
(ii) Pop_element() - To Pop the objects from the stack and display them. Also, display “Stack Empty”
when there are no elements in the stack.

2. Vedika has created a dictionary containing names and marks as key-value pairs of 5 students.
Write a program, with separate user-defined functions to perform the following operations:
51
(i) Push the keys (name of the student) of the dictionary into a stack, where the corresponding value
(marks) is greater than 70.
(ii) (ii) Pop and display the content of the stack.

The dictionary should be as follows:

d={“Ramesh”:58, “Umesh”:78, “Vishal”:90, “Khushi”:60, “Ishika”:95}

Then the output will be:


Umesh Vishal Ishika

S.No. Answer Key


1. status=[]
def Push_element(cust):
if cust[2]= ="Goa":
L1=[cust[0],cust[1]]
status.append(L1)

def Pop_element ():


num=len(status)
while len(status)!=0:
dele=status.pop()
print(dele)
num=num-1
else:
print("Stack Empty")
stk=[]
d={"Ramesh":58, "Umesh":78, "Vishal":90, "Khushi":60, "Ishika":95}

def push(stk,item):
for i in item:
if item[i]>70:
stk.append(i)

def Pop(stk):
if stk= =[]:
return None
else:
return stk.pop()

52
Unit II: Computer Networks

Network: A computer network is a set of computers connected together for the purpose of sharing
resources. Each computer on the network is called a node.

Advantages for Networking


1. Resource sharing – All programs, data and peripherals are available to everyone irrespective of the
location of the resource and the user.
2. Reliability – Backup copy of a file is kept on different machines, which is available in case of hardware
crash or any other problem.
3. Cost factor –Cost is reduced since the resources can be shared
4. Communication Medium - Changes done by a user on a shared resource are conveyed to all.

Disadvantages of Networking
1. Threat to data: A computer network may be used by unauthorized users to steal or corrupt the data
and even to deploy computer virus or worms on the network.
2. Difficult to set up:

Evolution of Networking:

➢ 1969 - First network came into existence


➢ ARPANET – Advanced Research Project Agency Network
➢ MID 80’S - NSFNET (National Science Foundation Network)

Internet:
➢ a global computer network providing a variety of information and communication facilities,
consisting of interconnected networks using standardized communication protocols
➢ Network of Networks
➢ Popularly known as “NET”
53
Intranet:
➢ Intranet is a local or restricted communications network, especially a private network created using
World Wide Web softwares.
➢ It is managed by any person/ organization
➢ Intranet user can avail services of Internet whereas Internet user cannot access intranet directly.

Interspace:
➢ Interspace is a client/server software program that allows multiple users to communicate online
with real time audio, video and text chat in dynamic 3D environment.
➢ Online video conferencing is an example of Interspace.

Switching techniques are used for transferring data across network. In large network, there might be
multiple path linking the sender and receiver. Information may be switched as it travels through various
communication channel.
Three types of Switching techniques
1. Circuit Switching
➢ First the complete physical connection between two computers is established and then the data are
transmitted from the source computer to the destination
➢ When a call is placed the switching equipment within the system seeks out a physical copper path
all the way from the sender to the receiver.
➢ It is must to setup an end-to-end connection between computers before any data can be sent.
➢ The circuit is terminated when the connection is closed.
➢ In circuit switching, resources remain allocated during the full length of a communication, after a
circuit is established and until the circuit is terminated and the allocated resources are freed

2. Packet Switching Packet switching introduces the idea of cutting data i.e. at the source entire message is
broken in smaller pieces called packets which are transmitted over a network without any resource being
allocated.
➢ Then each packet is transmitted and each packet may follow any rout available and at destination
packets may reach in random order.
➢ At the destination when all packets are received they are merged to form the original message.
➢ In packet switching all the packets of fixed size are stored in main memory.

3. Message Switching In message Switching, data is first stored by one node then forward to another node
to transfer the data to another system.
➢ In message Switching, data is first stored, then forwarded to the next node
➢ In Message Switching there is no upper bound on size of packet whereas in Packet Switching each
packet is of fixed size.
➢ In Packet Switching data packets are stored in main memory whereas in Message Switching
Message is stored in Hark disk which makes it reducing the access time

54
Communication terminologies:
Communication Channel (Transmission media): Is a medium through which a message is transmitted to
its intended destination. Communication channel can be wired (Guided) or Wireless (Unguided).

Bandwidth: Is a range of frequencies within a given band that is used for transmitting an analog signal.
Bandwidth is expressed in Hz, KHz, and MHz

Data transfer rate: DTR is the amount of data in digital form that is moved from one place to another in a
given time on a network. Data rates are often measured in megabits (million bits) or megabytes (million
bytes) per second.

Twisted pair cable It consists of two identical 1 mm thick copper wires insulated and twisted together. The
twisted pair cables are twisted in order to reduce crosstalk and electromagnet ic induction

Co-axial Cables It consists of a solid wire core surrounded by one or more foil or braided wire shields,
each separated from the other by some kind of plastic insulator. It is mostly used in the cable wires.

Optical fiber An optical fiber consists of thin glass fibers that can carry information in the form of visible
light.

Wireless Media (Unguided media)

Infrared Wave Transmission Short Range Communication: Infrared waves can travel from a few
centimetres to several meters.(Approx. 5m )

Radio Wave Transmission : Radio waves can cover distances ranging from a few
meters (in walkie-talkies) up to covering an entire city

Micro Wave Transmission: Microwave signals travel at a higher frequency than radio waves and are used
for transmitting data over several miles or kilometres.

55
Satellite Link
Satellite is a relay station in orbit above the earth that receive from one end of earth (uplink) regenerates,
and redirects signals to other end of earth (downlink).

Network devices:
Modem (MOdulator DEModulator) is an electronic device which converts digital
signals into analog signals for transmission over telephone lines (Modulation). At
the receiving end, a modem performs the reverse function and converts analog
signal into digital form (Demodulation) A modem can also amplify a signal so that
it can travel a long distance without attenuation.

RJ-45 (Registered Jack – 45) is an eight wired connector that is used to connect
computers on a local area network (LAN), especially Ethernet.

Ethernet card is a kind of network adapter and is also known as Network Interface
Card (NIC). These adapters support the Ethernet standard for high-speed network
connections via cables. An Ethernet Card contains connections for either coaxial
or twisted pair cables or fiber optic cable

Switch/Hub is an electronic device that connects several nodes to form a network


and redirects the received information to the destination. It has ports into which
the cables from individual computers' NICs are inserted.
Switch is an intelligent hub redirects the received information only to the
intended node(s).
Hub broadcasts the information all the connected nodes

Repeater When the data is transmitted over a network for long distances, the
data signal gets weak due to attenuation. A repeater regenerates the received
signal and re-transmits it to its destination.

Router is a network device used to establish connection between two similar networks. They can connect
networks with different architectures such as Token Ring and Ethernet. But, routers cannot transform
information from one data format to another such as TCP/IP to IPX/SPX.

Gateway is a device, which is used to connect dissimilar networks and perform the necessary translation
so that the connected networks can communicate properly. A gateway can translate information between
different network data formats and network architectures. It can translate TCP/IP to AppleTalk so
computers supporting TCP/IP can communicate with Apple brand computers.

56
Wi-Fi cards are small and portable cards that allow your computer to connect to the internet through a
wireless network.

Network Topologies It refers to the geometrical arrangement of nodes in a (LAN). The criteria for
choosing a topology: Installation cost, Reliability, Flexibility, Fault detection etc.

Bus Topology In bus topology all the nodes are connected to a main cable called backbone. If any node
has to send some information to any other node, it sends the signal to the backbone. The signal travels
through the entire length of the backbone and is received by the node for which it is intended.

Star Topology In star topology each node is directly connected to a hub/switch. If any node has to send
some information to any other node, it sends the signal to the hub/switch.

Tree topology is a combination of bus and star topologies. It is used to combine multiple star topology
networks. All the stars are connected together like a bus. This bus-star hybrid approach supports future
expandability of the network

57
Network Types:
PAN (Personal Area Network): Spread in the proximity of an individual

LAN (Local Area Network): Spread across a room, building, or campus

MAN (Metropolitan Area Network): Spread within a city

58
WAN (Wide Area Network): Spread across a city, country, or continent.

Network Protocol A protocol is the special set of rules that two or more machines on a network follow to
communicate with each other. Some of the important protocols used are as follows:

TCP/IP (Transmission Control Protocol / Internet Protocol): Communication between two computers
on internet is done using TCP/IP protocol. TCP/IP is a two-layer protocol.
➢ Using the TCP protocol a single large message is divided into a sequence of packets of size
limits from 128 to 4096 bytes.
➢ Each packet is independent and has the address of sender and destination.
➢ The IP (Internet protocol) does the routing for the packets. It keeps track of all the different routes
available to the destination. If one route is not available it finds the alternate route to the destination.
➢ At the destination, the TCP protocol re-assembles the packets into the complete message.

FTP (File Transfer Protocol) The File Transfer Protocol (FTP) is a standard network protocol used for the
transfer of computer files from a server to a client using the Client–server model on a computer
network.
PPP (Point to Point Protocol): In computer networking, Point-to-Point Protocol (PPP) is a data link
protocol used to establish a direct connection between two nodes. The Point-to-Point Protocol (PPP) is an
encapsulation protocol for transporting IP traffic across point-to-point links. PPP is used over many types
of physical networks including serial cable, phone line, trunk line, cellular telephone, radio links, and fibre
optic links etc.
Simple Mail Transfer protocol (SMTP): Simple Mail Transfer Protocol, a protocol for sending e-mail
messages between servers. Most e-mail systems that send mail over the Internet use SMTP to send
messages from one server to another; In addition, SMTP is generally used to send messages from a mail
client to a mail server. The messages can then be retrieved with an e-mail client using either POP or
IMAP. This is why you need to specify both the POP or IMAP server and the SMTP server when you
configure your e-mail application.
ESMTP (Extended Simple Mail Transfer Protocol) specifies extensions to the original SMTP protocol
for sending e-mail that supports graphics, audio and video files, and text in various national languages.

59
MIME (Multi-Purpose Internet Mail Extensions) is an extension of the original Internet e-mail protocol
that lets people use the protocol to exchange different kinds of data files on the Internet: audio, video,
images, application programs, and other kinds, as well as the ASCII text handled in the original protocol,
the Simple Mail Transport Protocol (SMTP).
Post Office Protocol Version 3 (POP3): POP3 is a client/server protocol used for opening the remote e-
mail boxes, the POP3 mail server receives e-mails, filters and holds them into the appropriate user
folders. When a user connects to the mail server to retrieve his mail, the messages are downloaded from
mail server to the user's hard disk.
Remote Access Protocol (Telnet) : This protocol helps a user (Telnet Client) to log in at a remote
computer (Telnet Server) and function as if he/she were connected directly to that computer. Telnet is the
main internet protocol for creating a connection with a remote machine. It allows you to connect to remote
computers (called remote hosts) over a TCP/IP network (such as the Internet).

Introduction to Web Services


WWW (World Wide Web): WWW is a network of web servers. It can be defined as a hypertext
information retrieval system on the Internet. It is the universe of the information available on the internet.
All the web pages on WWW use HTTP for making hypertext jumps.

HTML (Hypertext Markup Language)


➢ HTML is a markup language to create and design web content.
➢ It is used to display the data in formatted manner.
➢ It has a variety of predefined tags and attributes for defining the layout and structure of the web document.
➢ HTML is not case sensitive

XML (eXtensible Markup Language)


➢ XML is a markup language that is self-descriptive.
➢ It is used to carry, store or exchange data.
➢ It does not have predefined tags. It is possible to define new tags in XML. It allows the programmer
to use customized tags.
➢ XML is case sensitive.
➢ A HTML document has the extension .xml
HTTP is the protocol that is used for transferring hypertext (text, graphic, image, sound, video etc.)
between two computers and is particularly used on the World Wide Web. It is a TCP/IP based communication
protocol and provides a standard for Web browsers and servers to communicate. HTTP is based on
Client/Server principle. Communication between the host and the client occurs through a request/response
pair. A connection is established between two computers - out of which one is client (generally the browser)
that initiates the request and the other is the server that responds to the request. Also HTTP identifies the
resource that the client has requested for and informs the server about the action to be taken. When the user
clicks on the hypertext link, the client program on their computer uses HTTP to contact the server, identify
the resource and ask the server to respond with an action. The server accepts the request and then uses HTTP
to respond to perform the action.

60
Domain Names: Every computer on the network has a unique numeric address assigned to it which is a
combination of four numbers from 0-255 separated by a dot. For example, 59.177.134.72 since it is
practically impossible for a person to remember the IP addresses. A system has been developed which assigns
domain names to web servers and maintains a database of these names and corresponding IP addresses on
DNS (Domain Name Service) server.

URL (Uniform resource locator): A URL is a formatted text string used to identify a network resource
on the Internet. Network resources can be plain Web pages, text documents, graphics, downloadable files,
services or programs. Every network resource on the web has a unique URL in the following format:
Protocol: // domain name /path / file name The URL text string consists of three parts:
➢ Network Protocol: The network protocol identifies the protocol to be used to access the network
resource. These strings are short names followed by the three characters ': //’. Some examples of
protocols include http, gopher, ftp and mailto.
➢ Domain name: It identifies the host/server that holds the resource. For example: www. School.com
is a domain name.
➢ Resource Location: It consists of the path or directory and the file name of resource. For example
in the URL : http://www.school.com/syllabus/preprimary/nursery.htm the file nursery.htm is
stored in the sub directory preprimary, of the directory syllabus on the server www.school.com
Website: Related webpages from a single web domain is termed as a website. A website has multiple
webpages providing information about a particular entity.
Web browser: Web browser is software program to navigate the web pages on the internet. A bowser
interprets the coding language of the web page and displays it in graphic form. Internet works on client -
server model. A web browser is a client which requests the information from the web server. The web server
sends the information back to the client. Some of the web browsers are: Netscape Navigator, Internet
Explorer, Mozilla Firefox etc.
Web Server: A Web server is a computer or a group of computers that stores web pages on the internet. It
works on client/server model. It delivers the requested web page to web browser. Web servers use special
programs such as Apache or IIS to deliver web pages over the http protocol. Each server has a unique IP
address and domain name. In order to access a webpage, the user writes the URL of the site on the address
bar of the browser. The machine on which the browser is running sends a request to the IP address of the
machine running the web server for that page. Once the web server receives that request, it sends the page
content back to the IP address of the computer asking for it. The web browser then translates that content
into all of the text, pictures, links, videos, etc. A single web server may support multiple websites or a single
website may be hosted on several linked servers.
Web hosting: Web hosting is the process of uploading/saving the web content on a web server to make
it available on WWW. In case an individual or a company wants to make its website available on the
internet, it should be hosted on a web server.
Web page: Web page is an electronic document designed using HTML. It displays information in textual
or graphical form. It may also contain downloadable data files, audio files or video files. Traversal from one
webpage to another web page is possible through hyperlinks.
61
MCQs:
1. Combination of two or more networks are called
A. Internetwork B. WAN C. MAN D. LAN

2. Which topology covers security, robust and eliminating traffic factor?


A. Mesh B. Ring C. Star D. Bus

3. National Internet Service Provider (ISP) networks are connected to one another by private switching
stations called
A. Network Access Points B. Peering Points C. National ISP D. Regional ISP

4. Multipoint topology is
A. Bus B. Star C. Mesh D. Ring

5. A communication path way that transfers data from one point to another is called
A. Link B. Node C. Medium D. Topology

6. Common LAN topologies are


A. Bus and ring B. Mesh and Ring C. Star D. both A & C
7. Network providing a high speed connectivity is
A. MAN B. LAN C. WAN D. Internetwork

8. Synonymous of rule is
A. Standard B. Protocol C. Forum D. Agency

9. Connection in which multi devices share a single link is called


A. Point to point B. Multipoint C. Time Shared D. Spatially Shared

10. Elapsed time between an inquiry and a response is called.


A. Transit Time B. Delay Time C. Processing Time D. Response time

11. Nodes are another name of


A. Devices B. Links C. Medium D. Modes

12. Star topology is less expensive then


A. Mesh B. Ring C. Bus D. Hybrid

13. Difficult reconnection and fault isolation are disadvantages of


A. Star topology B. Mesh topology C. Ring topology D. Bus topology

14. Connection of telephone regional office is practical example of

62
A. Ring B. Hybrid C. Mesh D. Bus

15. Cable TV and DSL are examples of


A. Interconnection of network B. LAN C. MAN D. WAN

16. In Star topology, central controller is called


A. Node B. router C. Hub D. Modem

17. Largest professional engineering society in world is


A. American National Standards Institute B. Electronic Industries Association
C. Institute of Electrical and Electronics Engineers D. International Organization for Standardization

18. Newest evolution in LAN technology is


A. Wireless B. Internet C. DSL D. TV Network

19. Working document with no official status and a 6-month lifetime is called
A. Internet draft B. Internet standard C. Internet Protocol D. Regulatory Agencies

20. Organization that is developing cooperation in realms of scientific, technological and economic activity
is .
A. Institute of Electrical and Electronics Engineers B. International Organization for Standardization
C. American National Standards Institute D. Electronic Industries Association

21. Internetworking protocol is known as


A. TCP B. IP C. ISP D. TCPIP

22. Defacto means


A. by fact B. by law C. by nature D. by network

23. Repeater is used in


A. Mesh Topology B. Ring Topology C. Bus Topology D. Star Topology

24. In bus topology, device linking all nodes in a network is


A. Router B. DropLine C. Backbone D. hub

25. ATM is an example of


A. MAN B. Point to Point WAN C. Switched WAN D. LAN

Answer:
1A 2A 3B 4A 5A 6D 7A 8B 9B 10D 11A 12A 13D 14C
15C 16C 17C 18A 19A 20B 21D 22A 23B 24C 25C

(Short Answer Questions)


63
1. What Port does HTTP and HTTPS use?
Ans: HTTP uses TCP port 80 and HTTPS uses TCP port 443.

2. What is Extranet?
Ans: External users are allowed or provided with access to use the network application of the organization.

3. How can you recover the data from a system which is infected with virus?
Ans: In another system (not infected with virus) install an OS and antivirus with the latest updates. Then
connect the HDD of the infected system as a secondary drive. Now scan the secondary HDD and clean it.
Then copy the data into the system.

4. What protocols can be applied when you want to transfer files between different platforms?
Ans: FTP

5. What is the use of default gateway?


Ans: Default gateways provide means for the local networks to connect to the external network.

6. What happens when you use cables longer than the prescribed length?
Ans: Cables that are too long result in signal loss. This means that data transmission and reception would
be affected because the signal degrades over length.

7. What common software problems can lead to network defects?


Ans:
• Client server problems
• Application conflicts
• Error in configuration
• Protocol mismatch
• Security mismatch
• User policy and rights issue.

8. You need to connect two computers for file sharing. Is it possible to do this without using a hub or
router?
Ans: Yes, you can connect two computers together using only one cable. A crossover type cable can be used
in this scenario. In this setup, the data transmit pin of one cable is connected to the data receive pin of the
other cable and vice-versa.

9. When you move the NIC cards from one PC to another PC, does the MAC address gets transferred as
well?
Ans: Yes, because MAC addresses are hard wired into the NIC circuitry, not the PC.

10. What can be done to fix signal attenuation problems?


Ans: A common way of dealing with such a problem is to use repeaters and hubs because it will help
regenerate the signal and therefore prevent signal loss. Checking if cables are properly terminated is also a
must.

64
11. Why can’t wireless network detect collisions?
Ans: CSMA/CD can’t be used on a wireless. Using CSMA/CD, if a collision is detected on the medium,
end-devices would have to wait a random amount of time before they can start retransmission process.

12. How long is an IPV6 address?


Ans: 128 bits
13. You have 10 users plugged into a hub running 10 Mbps half-duplex. There is a server connected to the
switch running 10 Mbps half-duplex as well. How much bandwidth does each host have to the server?
Ans: 10 Mbps
14. What protocol does PPP use to identify the Network Layer protocol?
Ans: NCP

15. Which protocol is used to send a destination network unknown message back to originating hosts?
Ans: ICMP

16. Which protocol does ping use?


Ans: ICMP

17. What protocol is used to find the hardware address of a local device?
Ans: ARP
18. What is hop count?
Ans: Hop count is the number of routers occurring in between the source and destination network. The path
with the lowest hop count is considered as the best route to reach a network and therefore placed in the
routing table.
19. How many maximum hop counts are allowed for RIP (Routing Information Protocol)?
Ans: 15.
Hop count of 16 is considered as network unreachable.
20. What is congestion?
Ans: It is a state occurring in network layer when the message traffic is so heavy that it slows down
network response time.

Very Short Answer Questions:


1) What do you mean by Network?
Answer: Set of devices connected to each other over the physical medium is known as a computer network.
For example the Internet.
2) What do you mean by Node?
Answer: In the computer network, the node is known as a device.
3) What do you mean by Network Topology?
Answer: A network topology is a physical structure of the network which defines how the computers or
node will be connected to each other.
4) What is Routers?
Answer: A router is a device which is responsible for sending data from source to destination over the
computer network.

65
5) What do you mean by HTTP?
Answer: HTTP stands for Hyper Text Transfer Protocol and the port for this is 80. This protocol is
responsible for web content.
6) What do you mean by TCP and UDP?
Answer: TCP stands for Transfer control protocol and UDP stands for User Datagrams protocol and TCP is
a connection-oriented protocol and UDP is a Connectionless protocol.
7) What do you mean by a Firewall?
Answer: Firewall is a concept of a security system that will helps computers to protect it with unauthorized
access or any cyber-attack.
8) What do you mean by DNS?
Answer: DNS Stands for Domain Name System. It’s an internet address mapping process with the local
name. We can also call it as an internet phonebook.
9) What do you mean by Proxy server?
Answer: Proxy server prevents the external users which are unauthorized to access the network.
10) What do you mean by NIC?
Answer: NIC stands for Network interface card. It is an adapter that will be installed on the computer and
because of that NIC, only that computer will interact with the network.
11) What do you mean by ASCII?
Answer: ASCII is the American Standard Code for Information Interchange.
12) What are the types of mode available in Network?
Answer: Data transferring mode in a computer network will be of three types: Simplex, Half-Duplex and
Full Duplex.
13) What do you mean by SLIP protocol?
Answer: SLIP stands for Serial Line Interface Protocol. It is used for sending IP datagram over a network
in a single line.
14) What do you mean by Decoder?
Answer: A decoder is a program which converts the encrypted data into its actual format.

66
NETWORKING (4 Marks Questions)
1. Multipurpose Public School, Bengaluru is setting up the network between its different wings of
school campus. There are 4 wings named as:-

SENIOR(S), JUNIOR(J), ADMIN(A) and HOSTEL(H)

(i) Suggest the best wired medium and draw the cable layout to efficiently connect various wings of
Multipurpose Public School, Bengaluru.
(ii) Name the most suitable wing where the servers should be installed. Justify your answer.
(iii) Suggest a device/software and its placement that would provide data security for the entire
network of the school.
(iv) Suggest a device and a protocol that shall be needed to provide wireless internet access to all
smartphone/laptop users in the campus of Multipurpose Public School, Bengaluru.

67
Answers:
(i) Best wired medium: Optical fibre/CAT5/CAT6/CAT7/CAT8/Ethernet Cable.
Layout:

(ii) Wing Senior (S)- Because it has maximum number of computers.


(iii) Firewall- Placed with the Server at SENIOR(S).
(iv) DEVICE NAME: WiFi Router/WiMax/Wireless modem
Protocol: WAP/TCP-IP/VoIP/MACP

2. Intelligent Hub India is a knowledge community aimed to uplift the standard of skills and
knowledge in the society. It is planning to setup its training centres in multiple towns and villages
pan India with its head offices in the nearest cities. They have created a model of their network with
a city, a town and 3 villages as given.
As a network consultant, you have to suggest the best network related solution for their
issues/problems raised
in (i) to (iv) keeping in mind the distance between various locations and given parameters.

68
Note:
• In Villages, there are community centres, in which one room has been given as training center to this
organization to install computers.
• The organization has got financial support from the government and top IT companies.
1. Suggest the most appropriate location of the SERVER in the YHUB (out of the 4 locations), to get
the best and effective connectivity. Justify your answer.
2. Suggest the best wired medium and draw the cable layout (location to location) to efficiently
connect various locations within the YHUB.
3. Which hardware device will you suggest to connect all the computers within each location of
YHUB?
4. Which server/protocol will be most helpful to conduct live interaction of Experts from Head office
and people at YHUB locations?
Answers:
(i) YTOWN
Justification

1. Since it has the maximum number of computers.


2. It is closet to all other locations.
(ii) Optical Fiber

Layout:

(iii) Switch or Hub


(iv) Video conferencing or VoIP or any other correct service/protocol

69
3. Indian School, in Mumbai is starting up the network between its different wings. There are four
Buildings named as SENIOR, JUNIOR, ADMIN and HOSTEL as shown below:

The distance between various buildings is as follows:

Number of Computers in Each Building :

1. Suggest the cable layout of connections between the buildings.


2. Suggest the most suitable place (i.e., building) to house the server of this school, provide a suitable
reason.
3. Suggest the placement of the following devices with justification.
o Repeater
o Hub/Switch
4. The organization also has inquiry office in another city about 50-60 km away in hilly region.
Suggest the suitable transmission media to interconnect to school and inquiry office out of the
following :
o Fiber optic cable
o Microwave
o Radiowave
Answers:

1.

70
2. Server can be placed in the ADMIN building as it has the maximum number of computers.
3. Repeater can be placed between ADMIN
and SENIOR building as the distance is more than 110 m.
4. Radiowaves can be used in hilly regions as they can travel through obstacles.

4) Vidya Senior Secondary Public School in Nainital is setting up the network between its different wings.
There are 4 wings named as SENIOR(S), JUNIOR(J), ADMIN(A) and HOSTEL(H).
Distance between various wings are given below:

1. Suggest a suitable Topology for networking the computers of all wings.


2. Name the most suitable wing where the Server should be installed. Justify your answer.
3. Suggest where all should Hub(s)/Switch(es) be placed in the network.
4. Which communication medium would you suggest to connect this school with its main branch in
Delhi ?
Answers:

1.
2. Server should be in Wing S as it has the maxi-mum number of computers. 1
3. All Wings need hub/switch as it has more than
one computer.
4. Fiber Optics.

71
5) Trine Tech Corporation (TTC) is a professional consultancy company. The company is planning to set
up their new offices in India with its hub at Hyderabad. As a network adviser, you have to understand
their requirement and suggest them the best available solutions. Their queries are mentioned as (i) to (iv)
below.
Physical Locations of the blocked of TTC

1. What will be the most appropriate block, where TTC should plan to install their server?
2. Draw a block to cable layout to connect all the buildings in the most appropriate manner for
efficient communication.
3. What will be the best possible connectivity out of the following, you will suggest to connect the
new setup of offices in Bangalore with its London based office:
o Satellite Link
o Infrared
o Ethernet Cable
4. Which of the following device will be suggested by you to connect each computer in each of the
buildings:
o Switch
o Modem
o Gateway

72
Answers:
1. Finance block because it has maximum
number of computers.

2.
3. Satellite link
4. Switch

6) G.R.K International Inc. is planning to connect its Bengaluru Office Setup with its Head Office in Delhi.
The Bengaluru Office G.R.K. international Inc. is spread across and area of approx. 1 square kilometer,
consisting of 3 blocks – Human Resources, Academics and Administration.
You as a network expert have to suggest answers to the four queries (i) to (iv) raised by them.

1. Suggest the most suitable block in the Bengaluru Office Setup, to host the server.
Give a suitable reason with your suggestion.
2. Suggest the cable layout among the various blocks within the Bengaluru Office Setup for
connecting the Blocks.
3. Suggest a suitable networking device to be installed in each of the blocks essentially required for
connecting computers inside the blocks with fast and efficient connectivity.
4. Suggest the most suitable media to provide secure, fast and reliable data connectivity between Delhi
Head Office and the Bengaluru Office Setup.
Answers:
1. Human Resources because it has maximum number of computers.

2.
3. Switch 1
4. Fiber Optics

73
(Abbreviations)

1 NIU Network Interface Unit


2 MAC Media Access Control
3 TCP/IP Transmission Control
Protocol/Internet Protocol
4 PAN Personal Area Network
5 LAN Local Area Network
6 MAN Metropolitan Area
Network
7 WAN Wide Area Network
8 UTP Unshielded Twisted Pair
9 STP Shielded Twisted Pair
10 Mbps Mega bits per sec
11 EMI Electro Magnetic
Interference
12 RJ Registered Jack
13 Wi-Fi Wireless Fidelity
14 VPN Virtual Private Network
15 IAAS Infrastructure As A
Service
16 PAAS Platform As A Service
17 SAAS Software As A Service
18 DAAS Desktop As A Service
19 IOT Internet Of Things
20 NIC Network Interface Card
21 CSMA/CD Carrier Sense Multiple
Access/Collision Detection
22 CSMA/CA Carrier Sense Multiple
Access/Collision
Avoidance
23 DNS Domain Name System
24 DHCP Dynamic Host
Configuration Protocol
25 ISP Internet Service Provider
26 URL Uniform Resource Locator
27 HTTP Hyper Text Transfer
Protocol
28 FTP File Transfer Protocol
29 FDMA Frequency Division
Multiple Access
30 TDMA Time division Multiple
Access
31 CDMA Code Division Multiple
Access

74
STUDY MATERIAL
CLASS - XII

TOPIC: DTABASE MANAGEMENT


Data - It is a collection of raw facts and figures to be used for a specific purpose such as a survey or
analysis. Any number, character can be considered as data.

Information – processed data are called information. It is related to some other entity.
E.g. 4 is a roll number of shyam, here 4 is information.

Database – it is a collection of interrelated data in organized manner. A table or group of tables is called
database.

Database Management System (DBMS) – It is a type of software that is responsible for storing,
manipulating, maintaining and utilizing database.

E.g. MS Access, MYSQL, FoxPro, Oracle etc.

Relational Database Management System (RDBMS) – it is similar to DBMS with some advance feature
like joining of tables, Integrity constraint feature, group by with having etc.

E.g. MYSQL, FoxPro, Oracle etc.

Relational Data Model:-


Data is organized in two-dimensional tables called relations. The tables or relations are related to each other.

Characteristics of relational database are:-

➢ Data is arranged into rows and columns,


➢ Each relation is represented as a table.
➢ Every row in a table represents a single entity.
➢ At any given row or column position, there is one and only one value.

Terminology of Relational database:

Relation – Table is called Relation in RDMBS

Attribute – Column of a table is called attribute of a relation in RDBMS

Tuple – row of a table is called tuple in RDBMS

Degree –Total number of attributes or columns of a table or relation is called degree in RDBMS

Cardinality –Total number of tuples or rows of a table or relation is called cardinality in RDBMS

Domain – It is a pool of values from which the actual values appearing in the given column are drawn.

75
Board type question
1. Define the term Domain with respect to RDBMS. Give one example to support your answer.
Ans. It is a pool of values from which the actual values appearing in the given column are drawn.
Ex - All the names of name columns of any given table.
2. Write the difference between degree and cardinality.
Ans. Total number of attributes or columns of a table or relation is called degree and total number of tuples
or rows of a table or relation is called cardinality

-----------------------------------------------------------------------------------------------------------------------

Structured Query Language (SQL) - Structured Query Language (SQL) is a standardized programming
language that is used to manage relational databases and perform various operations on the data in them.

MYSQL Elements:
1. Literals
2. Data types
3. Null
4. Comments

Literals
It means the fixed value or constant value. It may be of character, numeric or date time type.
Character and date/time literals are always in single quotation marks whereas numeric literals must be
without single quotation marks.
For example – ‘Virat’, 12, 12.56, ‘04-20-2018’.
date and time values are always in the format YYYY-MM-DD HH:MI:SS.
Special character like quotes are always written be preceding it back-slash(\). For example if we want to store
value as Tom’s Cat then it should be written as Tom\’s Cat

Data Type
Means the type of value and type of operation we can perform on data. For example, on numeric value we
can store numbers and perform all arithmetic operations and so on.
76
MySQL support three categories of data types:
➢ Numeric
➢ Date and time
➢ String types
➢ Numeric Data Types

Data type Description


INT Numbers without decimal. Store up to 11 digits. -2147483648 to 2147483647

FLOAT(M,D) Real numbers i.e. number with decimal. M specify length of numeric value
including decimal place D and decimal symbol. For example if it is given as
FLOAT(8,2) then 5 integer value 1 decimal symbol and 2 digit after decimal
TOTAL – 8. it can work on 24 digits after decimal.

DOUBLE(M,D) Real numbers with more precision up to 53 place after decimal.

DECIMAL It is used to store exact numeric value that preserves exact precision for e.g.
money data in accounting system.
DECIMAL(P,D) means P no. of significant digits (1-65), D represent no. of
digit after decimal(0-30), for e.g. DECIMAL(6,2) means 4 digit before
decimal and 2 digit after decimal. Max will be 9999.99

Date and Time Types


DATE-A date in YYYY-MM-DD format between 1000-01-01 to 9999-12-31.
DATETIME-Combination of date and time. For example to store 4th December 2018 and time is afternoon
3:30 then it should be written as – 2018-12-04 15:30:00
TIMESTAMP - Similar to DATATIME but it is written without hyphen for example the above date time is
stored as 20181204153000
TIME-To store time in the format HH:MM:SS
YEAR(M) -To store only year part of data where M may be 2 or 4 i.e. year in 2 digit like 18 or 4 digit like
2018.
String Types
CHAR(M)
o Fixed length string between 1 and 255.
o It always occupies M size, irrespective of actual number of characters entered.
o Mostly use in the case where the data to be insert is of fixed size like Grade (A,B,C,..) or Employee code as
E001, E002, etc
VARCHAR(M)
o Variable length string between 1 and 65535 (from MySQL 5.0.3) , earlier it was 255
o It takes size as per the data entered for example with VARCHAR(20) if the data entered is MOBILE then it
will take only 6 byte.
o It is useful for the data like name, address where the number of character to be entered is not fixed.

Difference between CHAR & VARCHAR

Char varchar
Fixed length string Variable length string
Fast, no memory allocation every time Slow, as it take size according to data so

77
every
time memory allocation is done
It takes more memory It takes less space

Board type question:


1. In a table in MYSQL database, an attribute X of data type varchar(20) has the value “AMIT”. The attribute
Y of data type char(20) has value “AMRITA”. How many characters are occupied by attribute X and attribute
Y?
a. 4,20 b. 6,4
c. 20,20 d. 4,6
Ans. d .4,6
-----------------------------------------------------------------------------------------------------------------------------------

MySQL - MySQL is freely available open source RDBMS software that uses Structured Query Language
(SQL) to create and manage databases.

Categories of SQL commands

There are three categories:

1. Data Definition Language(DDL)

2. Data Manipulation Language(DML)

3. Transaction Control Language(TCL)

DATA DEFINITION LANGUAGE COMMANDS (DDL) –These commands are used to create or modify
the tables in SQL.

MAIN DDL COMMANDS

1. CREATE TABLE

2. ALTER TABLE (WITH ADD & MODIFY)

3. DROP TABLE (AFTER DELETE RECORDS)

OTHER DDL COMMANDS

1. CREATE DATABASE

2. USE

3. SHOW (DATABASES & TABLES)

4. DESC

78
DATA DEFINITION LANGUAGE COMMANDS (DDL):

CREATE TABLE- IT IS USED TO CREATE TABLE.

EXAMPLE – CREATE TABLE STUDENT


(
ROLL INT,
NAME CHAR(15),
ADDR VARCHAR(25),
MARKS INT
);

ALTER TABLE- it is used to change the data type and size of columns. It is also used to add new column or
delete column.

EXAMPLE –

1. ALTER TABLE STUDENT ADD


PERCENTAGE INT;

2. ALTER TABLE STUDENT


MODIFY NAME CHAR(20);

3. ALTER TABLE STUDENT


DROP ROLL;

DROP TABLE - IT IS USED TO DELETE THE TABLE.

EXAMPLE – DROP TABLE STUDENT;

OTHER DDL COMMANDS

1. SHOW DATABASES - IT IS USED TO DISPLAY THE NAME OF ALL THE DATABASES OF


MYSQL SERVER.

2. USE – IT IS USED TO OPEN ANY DATABASE.

EX – USE TEST;

3. CREATE DATABASE – IT IS USED TO CREATE A NEW DATABASE.

79
EX – CREATE DATABASE NITYA;

4. SHOW TABLES - IT IS USED TO DISPLAY THE NAME OF ALL TABLES IN A DATABASE.

5. DESC – IT IS USED TO SHOW THE STRUCTURE OF TABLE

EX – DESC STUDENT;

DATA MANIPULATION LANGUAGE COMMANDS ( DML) – It is used to manage the records of a


table. We can easily access, store, modify, update and delete the existing records.

Types of DML commands

1. INSERT

2. DELETE

3. UPDATE

4. SELECT

INSERT - IT IS USED TO INSERT THE RECORDS IN THE TABLE.

EXAMPLE –

1. INSERT INTO STUDENT


VALUES (1,‘NITYA’,’ALLAHABAD’,345)

2. INSERT INTO STUDENT


(NAME,MARKS,ROLL)
VALUES (‘NITI’,344,2);
NOTE – SECOND METHOD IS USED TO INSERT SPECIFIC RECORDS IN ANY SEQUENCE

DELETE - IT IS USED TO DELETING THE RECORDS OF A TABLE.

EX – 1. DELETE FROM STUDENT;


(DELETE ALL RECORDS)

2. DELETE FROM STUDENT


WHERE ROLL =1;

3. DELETE FROM STUDENT


WHERE ROLL =1 AND MARKS<300;

UPDATE - IT IS USED TO CHANGE THE RECORDS OF A TABLE.

EX – UPDATE STUDENT
80
SET MARKS=500
WHERE NAME=‘NITYA’;

NOTE – THIS COMMAND IS ALSO USED TO FILL THE DATA IN PLACE OF NULL VALUE

BOARD TYPE QUESTION:

1. Write SQL commands in (i) to (ii)


Table name: Coaching

(i) Increase the fee by 5% of students whose city is “Delhi”.


(ii) Delete the record of students who have age less than 35
Ans. (i) update coaching set fee=(fee)+(fee*5)/100 where city=”Delhi”
(ii) Delete from coaching where age<35;

SELECT COMMAND - This command is used to display the records of the table.

Different forms of Select command:

1. To view the records of Specific column(s).

Select roll from stu;


Select roll, name from stu;

2. To view all records

Select * from stu;

3. Select with “where” clause

Select * from stu


Where roll=1;
81
Select * from stu
Where name=‘amit’;

4. Combine more than one condition (by using AND, OR operator)


Select * from stu
Where roll=3 OR name=‘amit’;

Select * from stu


where roll=3 AND name=‘amit’;

5. Condition based on “Range”


Select * from stu
Where roll between 6 and 23;

Select * from stu


Where roll IN(2,7,15);

Select * from stu


Where roll NOT IN(2,3);

6. Records based on pattern matching


There are two characters used for pattern matching
a. Percent(%) – it means any character in any number.
b. Underscore( _ ) – it means only one any character

Select * from stu


Where name like ‘a%’;

Select * from stu


Where name like ‘_m_t’;

Select * from stu


Where name like ‘_m%’;

7. Sorting of Data
Ascending order
1. Select * from stu
Order by name;
Or
Select * from stu
Order by name asc;

Descending order

82
2. Select * from stu
Order by name desc;

8. With Distinct keyword – to remove duplicate data from any column

Select distinct name from stu;

Board Type Question

1. Write given commands for student table.


Student
Roll Name City Fee
1 Rohan Allahabad 500
2 Nitya Patna 300
3 shree Mumbai 500
a. To display only name and roll whose fee is less than 300.
b. To display all the records of student whose city is Patna and fee is more than 300.
c. To display the city of student whose name last letter is n.
d. Show the records of student in ascending order according to their name.

Ans.

a. Select name,roll from student where fee<300;


b. Select * from student where city=”patna” and fee>300;
c. Select city from student where name like “%n”;
d. Select * from student order by name;

2. Write the output of given query:


a. SELECT COUNT(DISTINCT fee) FROM STUDENT;
b. SELECT NAME, Roll FROM student WHERE Roll<3 AND NAME LIKE "%an";
c. SELECT Roll, City, Fee FROM student WHER name = "nitya" AND fee
BETWEEN 100 AND 500;
Ans.
a. 2
b.
NAME ROLL
Rohan 1

83
c.
Roll City Fee
2 Patna 300

-----------------------------------------------------------------------------------------------------------------------------------

Functions in SQL:

Function is used to perform some particular task and it returns zero or more values as a result.
Categories of functions in SQL
1. Single row functions -
Single row functions are applied on a single value and return a single value.
There are three categories of Single row function — Numeric (Math), String, Date and Time.

2. Multi row functions


Aggregate functions are also called Multiple Row functions. These functions work on a set of records as a
whole and return a single value for each column of the records on which the function is applied

Single Row functions:

a. Numeric functions

Function Description Example


POWER(X,Y) It calculates X to the power mysql> SELECT
It can also be written as Y. POWER(2,3);
POW(X,Y) Output:
8
ROUND(N,D) It rounds off number N to D mysql>SELECT
number of decimal places. ROUND(2912.564, 1);
Note: If D=0, then it rounds Output:
off the number to the nearest 2912.6
integer. mysql> SELECT
ROUND(283.2);
Output:
283
MOD(A, B) It returns the remain mysql> SELECT MOD(21,
der after dividing number A 2);
by number B. Output:
1
84
b. String functions

Function Description Example

UCASE(string) converts string into mysql> SELECT


OR uppercase. UCASE(“Informatics
UPPER(string) Practices”);
Output:
INFORMATICS
PRACTICES
LOWER(string) converts string into mysql> SELECT
OR lowercase. LOWER(“Informatics
LCASE(string) Practices”);
Output:
informatics practices
MID(string, pos, n) Returns a substring of size n mysql> SELECT
OR starting from the specified MID(“Informatics”, 3, 4);
SUBSTRING(string, pos, n) position (pos) of the string. If Output:
OR n is not specified, it returns form
SUBSTR(string, pos, n) the substring from the mysql> SELECT
position pos till end of the MID(‘Informatics’,7);
string. Output:
atics
LENGTH(string) Return the number of mysql> SELECT
characters in the specified LENGTH(“Informatics”);
string. Output:
11
LEFT(string, N) Returns N number of mysql> SELECT
characters from the left side LEFT(“Computer”, 4);
of the string. Output:
Comp

RIGHT(string, N) Returns N number of mysql> SELECT


characters from the right side RIGHT(“SCIENCE”, 3);
of the string. NCE
INSTR(string, substring) Returns the position of the mysql> SELECT
first occurrence of the INSTR(“Informatics”,
substring in the given string. “ma”);
Returns 0, if the substring is Output:
not present in the string. 6
LTRIM(string) Returns the given string after mysql> SELECT
removing leading white LENGTH(“ DELHI”),
space characters. LENGTH(LTRIM(“
DELHI”));
Output:
+--------+--------+
|7|5|
85
+--------+--------+
1 row in set (0.00 sec)

RTRIM(string) Returns the given string after mysql>SELECT


removing trailing white space LENGTH(“PEN
characters. “)LENGTH(RTRIM(“PEN
“));
Output:
+--------+--------+
|5|3|
+--------+--------+
1 row in set (0.00 sec)
TRIM(string) Returns the given string after mysql> SELECT
removing both leading and LENGTH(“ MADAM
trailing white space “),LENGTH(TRIM(“
characters. MADAM “));
Output:
+--------+--------+
|9|5|
+--------+--------+
1 row in set (0.00 sec)

c. Date and Time functions

Function Description Example


NOW() It returns the current system mysql> SELECT NOW();
date and time. Output:
2019-07-11 19:41:17
DATE() It returns the date part from mysql> SELECT
the given date/time DATE(NOW());
expression. Output:
2019-07-11
MONTH(date) It returns the month in mysql> SELECT
numeric form from the date. MONTH(NOW());
Output:
7
MONTHNAME(date) It returns the month name mysql> SELECT
from the specified date. MONTHNAME(“2003-11-
28”);
Output:
November
YEAR(date) It returns the year from the mysql> SELECT
date. YEAR(“2003-10- 03”);
Output:
2003
DAY(date) It returns the day part from mysql> SELECT
86
the date. DAY(“2003-03- 24”);
Output:
24
DAYNAME(date) It returns the name of the day mysql> SELECT
from the date. DAYNAME(“2019-07-11”);
Output:
Thursday

2. Aggregate or Multi row function

Function Description Example with output


MAX(column) It returns the largest value mysql> SELECT
from the specified column. MAX(Price) FROM
INVENTORY;
Output:
673112.00
MIN(column) It returns the smallest mysql> SELECT
value from the specified MIN(Price) FROM
column. INVENTORY;
Output:
355205.00

AVG(column) It returns the average of the mysql> SELECT


values in the specified AVG(Price) FROM
column. INVENTORY;
Output:
576091.625000
SUM(column) It returns the sum of the mysql> SELECT
values for the specified SUM(Price) FROM
column. INVENTORY;
Output:
4608733.00
COUNT(*) It returns the number of mysql> SELECT
records in a table. COUNT(*) from
Note: In order to display the MANAGER;
number of records that
matches a particular criteria +----------+
in the table, we have to use | count(*) |
COUNT(*) with WHERE +----------+
clause.
|4|
+----------+
1 row in set (0.00 sec)

87
COUNT(column) Returns the number of mysql> SELECT * from
values in the specified MANAGER;
column ignoring the NULL
values. +------ +---------+
Note: | MNO | MEMNAME |
In this example, let us +------ +---------+
consider a MANAGER
| 1 | AMIT |
table having two attributes
and four records. | 2 | KAVREET |
| 3 | KAVITA |
| 4 | NULL |
+------+----------+
4 rows in set (0.00 sec)
mysql> SELECT
COUNT(MEMNAME)
FROM MANAGER;
+----------------+
| COUNT(MEMNAME) |
+----------------+
|3|
+----------------+
1 row in set (0.01 sec)

Board type question:

1. Write the differences between Count(column name) and count(*) function.


Ans. COUNT(*) returns the count of all rows in the table, whereas COUNT() is used with Column_Name
passed as an argument and counts the number of non-NULL values in a column that is given as an
argument.

-----------------------------------------------------------------------------------------------------------------------------------

Group By clause - It is used to combining those records that have identical values. It is used with aggregate
functions.

88
Group By with having -
Having clause is used to place condition on aggregate function in conjunction with group by clause.
89
Board type question

Relation: PRODUCT

PCODE PNAME COMPANY PRICE STOCK MFG_DATE WARRANTY

P001 TV BPL 10000 200 12-JAN-2008 3

P002 TV SONY 12000 150 23-MAR-2007 4

P003 PC LENOVO 39000 100 09-APR-2008 2

P004 PC COMPAQ 38000 120 20-JUN-2009 2

P005 HANDYCAM SONY 18000 250 23-MAR-2007 3

1. Answer the given question:


(i) What will be the degree and cardinality of given table?
Ans. Degree= 7 Cardinality =5
(ii)Write a query to find the total price grouped by pname from product table.
Ans. select sum(price) from product group by pname;
(iii) What will be the output of given commands:
Select AVG (price), PNAME from PRODUCT group by PNAME; ( write output)

AVG(Price) PNAME
2100 TV
38500 PC
90
18000 HANDYCAM

Board type question


In MYSQL database, if a table, A has degree 2 and cardinality 4, and another table, B has degree 4 and
cardinality 2, what will be the degreeand cardinality of the Cartesian product of A and B?
a. 6,8 b. 8,6
c. 6,6 d.8,8

91
Board type question

Table : Brand

BID BName

M02 Dant Kanti

M03 Medimix

92
M04 Pepsodent

M05 Dove

1. Write SQL queries for the following:


(i) Display product name and brand name from the tables PRODUCTand BRAND.
(ii) Display the structure of the table PRODUCT.

(iii) Display the average rating of Medimix and Dove brands


(iv) Display the name, price, and rating of products in descending orderof rating.
Ans.

(i) SELECT PName, BName FROM PRODUCT P,BRAND B WHERE P.BID=B.BID;


(ii) DESC PRODUCT;
(iii) SELECT BName, AVG(Rating) FROM PRODUCT P, BRAND B
WHERE P.BID=B.BID
GROUP BY BName
HAVING BName='Medimix' OR
BName='Dove';
(iv) SELECT PName, UPrice, Rating FROM PRODUCT
ORDER BY Rating DESC;

Key – It is a columns or set of columns used to uniquely identification of records.

There are following type of keys:

93
Candidate keys : all the columns of a table which consists of unique values and can be used to uniquely
identification of records are called candidate keys. Among all candidate keys one attribute is selected as
primary key.

Ex – adm_no, Roll_no, contact_no etc

Primary key – it is a column of a table consisting unique values and used to uniquely identification of
records.

Ex- adm_no

Alternate key – all the candidate keys which are not selected as primary key, called Alternate keys

Ex – roll_no, Contact_no

Foreign key – A primary key of one table is called foreign key of other table if a relationship is created
between them.

Board type question

1. Give one difference between alternate key and candidate key.

2. Which of the following statements is FALSE about keys in a relationaldatabase?


a. Any candidate key is eligible to become a primary key.
b. A primary key uniquely identifies the tuples in a relation.
c. A candidate key that is not a primary key is a foreign key.
A foreign key is an attribute whose value is derived from the primarykey of another relation.

3. Ms. Shalini has just created a table named “Employee” containing columns Ename,
Department and Salary.
After creating the table, she realized that she has forgotten to add a primary key column in the table. Help her
in writing an SQL command to add a primary key column EmpId of integer type to the table Employee.
Thereafter, write the command to insert the following record in the table:
EmpId- 999
Ename- Shweta Department: Production Salary:
26900

Constraints -
94
Constraints are the certain types of restrictions on the data values that an attribute can have.

Types of constraint

NOT NULL Ensures that a column cannot have NULL


values where NULL means missing/
unknown/not applicable value.
UNIQUE Ensures that all the values in a column are
distinct/unique, it may be applied upon more
columns.
DEFAULT A default value specified for the column if no
value is provided
PRIMARY KEY The column which can uniquely identify each
row/record in a table. Only one column can be
created as primary key.

EXAMPLE –

Board type question

1. Amit is working in a database named XIIC, in which he has created a table named “Student”
containing columns Roll, Name, marks, and address.
After creating the table, he realized that the attribute, city of data type string has to be added. This attribute
city cannot be left blank. Help Amit to write the commands to complete the task.

Ans.

Alter table student

Add city char(20) not null;

------------------------------------------------------------------------------------------------------------------

95
DATABASE CONNECTIVITY

In order to connect to a database from within Python, you need a library that provides connectivity
functionality. There are many different libraries available for Python to accomplish this. We shall work with
‘mysql connector library’ for same.

Code to install MYSQL connector-

pip install mysql-connector-python

CONNECTING TO MYSQL FROM PYTHON

Steps for creating Database connectivity applications-

Step 1: Start python

Step 2: Import the packages required for database programming

Step 3: Open a connector to database

Step 4: Create a cursor instance

Step 5: Execute a query

Step 6: Extract data from result set

Step 7: Clean up the environment.

Example---

import mysql.connector as sqltor

mycon= sqltor.connect(host=”localhost”, user=”root”, passwd=”kvs”, database=”test”)

cursor= mycon.cursor()

cursor.execute(“select * from student”)

data= cursor.fetchmany(3)

for row in data:

print(row)

mycon.close()

96
EXTRACT DATA FROM RESULTSET

Once the result of query is available in the form of a resultset stored in a cursor object, we can extract
data from the resultset using any of the following fetch() functions.

(i) <data>= fetchall(): It will return all the records retrieved as per query in a tuple form (i.e. now <data>
will be tuple)

(ii) <data>= fetchone(): It will return one record from the resultset as a tuple or a list. First time it will return
the first record, next time it will fetch the next record and so on.

(iii) <data>= fetchmany(<n>): This method accepts number of records to fetch and returns a tuple.

(iv) <variable>= rowcount: It returns the n number of rows retrieved from the cursor so far.

Board Type Question

1. Arnav wants to write a program in Python to insert the following record in the table named Studentin
MYSQL database, SCHOOL:

• rno(Roll number )- integer


• name(Name) - string
• DOB (Date of birth) – Date
• Fee – float
Note the following to establish connectivity between Python andMySQL:

• Username - root
• Password - kvs
• Host – localhost
• Database – XII
The values of fields rno, name, doband feehas to be accepted from the user. Help Arnavr to write the
program in Python.
Ans.

import mysql.connector as sqltor

mycon= sqltor.connect(host=”localhost”, user=”root”, passwd=”kvs”, database=”XII”)

cursor= mycon.cursor()

97
rno=int(input(“enter roll=”))

name=input(“enter name=”))

dob=input(“enter dob=”)

fee= int(input(“enter feel=”))

query1=”insert into student({},’{}’,’{}’,{})”.format(rno,name,dob,fee)

cursor.execute(query1)

mycon.commit()

print(“data added successfully”)

mycon.close()

2. Nitya has created a table named Studentin MYSQL database,


SCHOOL:
• rno(Roll number )- integer
• name(Name) - string
• DOB (Date of birth) – Date
• Fee – float
Note the following to establish connectivity between Python andMySQL:
a. Username - root
b. Password – tiger
c. Host - localhost

Nitya, now wants to display the records of students whose fee is more than 5000. Help Nitya to write the
program in Python.

Ans.

import mysql.connector as sqltor

mycon= sqltor.connect(host=”localhost”, user=”root”, passwd=”tiger”, database=”XII”)

cursor= mycon.cursor()

query1=”select * from student where fee>{}”.format(500)

cursor.execute(query1)

98
data= cursor.fetchall()

for row in data:

print(row)

mycon.close()

99

You might also like