Class XII Computer Science Python Review
Class XII Computer Science Python Review
Computer Science(083)
INDEX
S. NO. NAME OF THE CHAPTER/UNIT PAGE NO
1 REVIEW OF PYTHON 7 - 19
2 FUNCTIONS 20 - 27
4 DATA STRUCTURE 35 - 39
5 COMPUTER NETWORKS 40 - 64
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
5. Practical
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 user- id.
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.
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 sensitised to avoid plagiarism and violations of copyright issues while working on
projects. Teachers should take necessary measures for this.
REVIEW OF PYTHON
Introduction to Python
Python is a free and open-source, object-oriented, high-level programming language
developed by Guido van Rossum in 1990.
Python is easy to learn and use, interactive, portable programming language.
Python is Dynamic Typing, does not need type declaration, variable assumes data type based on
value assigned
It is an interpreted language, as Python programs are executed by an interpreter.
Python is case-sensitive. For example, NUMBER and number are not same in Python.
There are two ways to use the Python interpreter: Interactive mode and Script mode
Tokens(Lexical unit)
Smallest individual unit of a python program. There are 5 types of Tokens in Python.
i) Keyword
ii) Identifiers
iii) Literals
iv) Operators
v) Punctuators
1. Keywords- Keywords are reserved words which conveys the special meaning to the Python interpreter.
List of keywords in Python is given in Appendix-1
2. Identifiers-Names given to any variable, constant, function or module etc. The rules for naming
an identifier in Python are as follows:
The name should begin with an uppercase or a lowercase alphabet or an underscore sign (_).
This may be followed by any combination of characters a–z, A–Z, 0–9 or underscore (_).
No special symbols can be used except underscore _ in identifiers. An identifier should not start
with a digit.
Keyword can‟t be used as an identifier.
String literals:
A string literal is a group of Characters surrounded by a single(„‟), double(“ ”), or triple quotes.
Example:
# in single quote
s = 'Hello Welcome to KVS'
# in double quotes
t = "'Hello Welcome to KVS "
# in tripple quotes
t = "'Hello\
Welcome to\
KVS "
# multi-line String
m = '''geek
for
geeks'''
Numeric literals:
They are immutable and there are three types of numeric literal: Integer, Float , Complex
Integer literal:
Both positive and negative whole numbers without fractional part. It can be written in Decimal, Binary,
Octal and Hexadecimal format.
# Binary Literals
a = 0b10100
# Decimal Literal
b = 50
# Octal Literal
c = 0o320
# Hexadecimal Literal
d = 0x12b
print(a, b, c, d)
Output
20 50 208 299
Complex literal :
The numerical will be in the form of a + bj, where „a„ is the real part and „b„ is the complex part.
Example:
z = 7 + 5j
k = 7j
print(z, k)
OUTPUT:
(7+5j) 7j
Boolean literal:
There are only two Boolean literals in Python. They are True and False. In Python, True represents
the value as 1 and False represents the value as 0.
Example:
a = (1 == True)
b = (1 == False)
c = True + 3
d = False + 7
print("a is", a)
print("b is", b)
print("c:", c)
print("d:", d)
OUTPUT:
a is True
b is False
c: 4
d: 7
Special literal:
Python contains one special literal (None). „None‟ is used to define a null variable. If „None‟ is
compared with any variable other than a „None‟, it will return False.
Example:
EMPTY = None
VAR=10
if VAR != None:
print(“TRUE”)
print (EMPTY)
Output:
TRUE
None
Data types ( Type of data ) - Provide information about domain of values and operations that can be
performed on data.
Type Value
bool True or False
int Whole number
float Numbers with fractional part
complex Numbers having real and imaginary part( x+yj)
string text enclosed in single or double quote
list list of comma separated values of any data type between square [ ]
brackets
tuple list of comma separated values of any data type between parenthesis ( ) .
dictionary Unordered set of comma-separated key:value pairs , within braces { }
Strings
Strings are homogeneous sequence of characters, represented by enclosing within single, double
or triple quotes.
String is immutable. String elements cannot be changed in-place.
Characters in a String are indexed and can be accessed by their position - forward indexing 0 to
len(String)-1 and backward indexing from -1 to -len(String)
Strings can be manipulated using operators like concatenation (+), repetition (*) and membership
(in and not in).
Example
s = 'Welcome to KVS'
forward indexing 0 1 2 3 4 5 6 7 8 9 10 11 12 13
W e l c O m e t o K V S
backward indexing -14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
Lists
A list is a heterogeneous sequence of data values (items) of same or different type
within square brackets.
Lists are mutable. List elements can be accessed using index. Indexing is similar
to string – both forward and backward indexing is used.
List may be Empty list, Long List, Nested List
Examples:
L=[ ] #empty List
L=[12,35,68,90]
L=[123, “Hello”, 6.8]
Examples:
T=( ) #empty tuple
T=10,
T=(10,)
T=(123, “Hello”, 6.8)
Dictionary
Python Dictionaries are unordered collection of key:value pairs and are represented by
enclosing within braces {}
Dictionaries are mutable (values can be changed, however keys should be
immutable type)
Examples:
D1={ } # empty dictionary
D2 = dict( ) # empty dictionary
D3 = { 1: “Rohan”, 2: “Sohan”, 3:”Mohan” }
D4={'empno':1,'name':'Shivam','dept':'sales', 'salary':25000}
1 Mark Questions
6. Which of the following statement(s) would give error on executing the following code?
T=(10, "Harish" , 2500) #Statement1
S="Thank you" #Statement2
T=T+("Odisha" , "Hockey") #Statement3
S=S+T #Statement4
print(S,T) #Statement5
(a) Statement 3
(b) Statement 4
(c) Statement 5
(d) Statement 4 and 5
10. Identify the valid arithmetic operator in Python from the following.
a) & b) = c) ** d) or
11. Suppose a tuple T is declared as T = (10, 13, 63, 39), which of the following isincorrect?
a) print(T[1])
b) T[2] = -51
c) print(max(T))
d) print(len(T))
12. Write a statement in Python to declare a dictionary whose keys are 1, 2, 3 and values are
Monday, Tuesday and Wednesday respectively.
13. Name the built-in mathematical function / method that is used to return absolute value of a
number.
14. If the following code is executed, what will be the output of the
followingcode? name="Computer Science with Python"
print(name[-2:-10:-2])
17. Name the Python Library modules which need to be imported to invoke thefollowing functions:
(i) tan() (ii) randrange ()
23. List L is defined as L=[1,2,3,4,5], Which of the following statement/statements removes the
middle element 3 from it so that the list L equals [1,2,4,5] ?
(a) del L[2] (b) L[2:3] = [ ] (c) L[2 : 2]=[ ] (d) L[ 2 ] = [ ] (e) [Link](3)
24. Identify the invalid logical operator in Python from the following.
a) and b) or c) not d)booean
25. method of list is used to delete a given element from the list.
(i) del (ii) pop(0 ) (iii) remove( ) (iv) pop( )
26. If the following code is executed, what will be the output of the following code?
Title="Python Programming Language"
print(Title[5:9], Title[-2:-6:-1])
(a) n Pr gaug (b) Error (c) n Pro gaug d) n Pro guag
29. Suppose list1 is [12, 33, 22, 14, 25], What is list1[:-1]?
a) [12, 33, 22, 14] b) Error c) 25 d) [25, 14, 22, 33, 12]
32. Suppose d = {“john”:40, “peter”:45}, to delete the entry for “john” which command do we use?
a) [Link](“john”:40) b) [Link](“john”)
c) del d[“john”] d) del d(“john”:40)
41. What will be the output of the following Python code snippet?
print(„abcdefcd‟.replace(„cd‟,‟12‟))
a) ab12ef12 b) abcdef12 c) ab12efcd d) None
42. A=[12,23,[20,30],[27,56,4],30]
[Link](30)
print(A[:2:-1])
44. dc1={}
dc1[2]=6
dc1['10']=2
dc1[2.0]=5
s=0
for i in dc1:
s+=dc1[i]
print(s)
47. mydict={'empno':1,'name':'Shivam','dept':'sales','salary':25000}
print([Link]())
print([Link]())
48. d1={1:100,2:200,3:300,4:400}
d2={1:111,2:222,5:555,4:444}
[Link](d2)
print(d1)
49. key=('Eno','Ename','Sal')
value=[1]
[Link](2)
d1=[Link](key,value)
print(d1)
2 Mark Questions
8. Rewrite the following code in Python after removing all syntax error(s).Underline each
correction done in the code.
val = input("Value:") adder
=0
for C in range(1,Val,3)
adder+=C
if C%2=0:
print (C*10)
else:
print (C*)
print (adder)
9. Rewrite the following code in Python after removing all syntax error(s).Underline each
correction done in the code.
25=Val
for I in the range(0,Val)
if I%2=0:
print( I+1)
Else:
print (I‐ 1)
a. y= 5 a= 10 b. y= 10 a= 5 c. y= 5 a= 12 d. No Output (Error)
a. 16 b. 18 c. 27 d. 24
15. Which of the following number can never be generated by the following code:
[Link](0,100)
a. 0 b. 1 c. 99 d.100
18. Amar wants to import only sqrt() function of math module. Help him to write the correct code.
a. import math
b. from math import sqrt
c. import sqrt from math
d. import sqrt
19. Which of the fllowing options can be the output for the following
code? import random
List=[“Delhi”,”Mumbai”,”Chennai”,”Kolkata”] for y
in range(4):
x=[Link](1,3) print(List[x],end=”#”)
a. Delhi#Mumbai#Chennai#Kolkata
b. Mumbai#Chennai#Kolkata#Mumbai#
c. Mumbai#Mumbai#Mumbai#Delhi#
d. Mumbai#Mumbai#Chennai#Mumbai#
1. What possible outputs(s) are expected to be displayed on screen at the time of execution of the
program from the following code? Also specify the maximum values that can be assigned to each of
the variables FROM and TO.
import random
AR=[20,30,40,50,60,70];
FROM=[Link](1,3) TO=[Link](2,4)
for K in range(FROM,TO+1):
print (AR[K],end=”#“)
(i) 10#40#70# (ii) 30#40#50#
(iii) 50#60#70# (iv) 40#50#70#
5. Rewrite the following code is Python after removing all syntax errors(s). Underline each
correction done in the code.
def display()
for Name in [Ramesh, Suraj, Priya]
if Name [0] = „S‟:
Print (Name)
6. Observe the following Python code very carefully and rewrite it after removing all syntactical
errors with each correction underlined.
def execmain():
x = input("Enter a number:")
if (abs(x)= x):
print("You entered a positive number")
else:
x=*-1
print("Number made positive : ",x)
execmain()
9. Write definition of a method/function DoubletheOdd(Nums) to add and display twice of odd values
from the list of Nums.
For example :
If the Nums contains [25,24,35,20,32,41]
The function should display
Twice of Odd Sum: 202
11. Write a function OCCURRENCE() to count occurrence of a character in any given string.
here function take string and character as parameters.
12. Write a Python function to search an element in a list using binary search.
14. Find and write the output of the following python code:
def fun(s):
k=len(s)
m=" "
for i in range(0,k):
if(s[i].isupper()):
m=m+s[i].lower()
elif s[i].isalpha():
m=m+s[i].upper()
else:
m=m+'bb'
print(m)
fun('school2@com')
16. Write a python function showlarge() that accepts a string as parameter and prints the words
whose length is more than 4 characters.
Eg: if the given string is “My life is for serving my Country” The output should be
serving
Country
Text File
o Text file stores information in ASCII OR UNICODE character. In text file everything will be
stored as a character for example if data is “computer” then it will take 8 bytes and if the data
is floating value like 11237.9876 it will take 10 bytes.
o In text file each like is terminated by special character called EOL. In text file some
translation takes place when this EOL character is read or written. In python EOL is „\n‟
or
„\r‟ or combination of both.
Binary files
o It stores the information in the same format as in the memory i.e. data is stored according to
its data type so no translation occurs.
o In binary file there is no delimiter for a new line
o Binary files are faster and easier for a program to read and write than text files.
o Data in binary files cannot be directly read, it can be read only through python program
for the same.
Opening File : File can be opened for either – read, write, append.
SYNTAX:
file_object = open(filename)
OR
file_object = open(filename, mode) default mode is “read”
Closing file : As reference of disk file is stored in file handle so to close we must call the close()
function through the file handle and release the file.
Syntax: [Link]()
1. Which of the following statements correctly explain the function of tell() method?
a. tells the current position within the file.
b. tell the name of file.
c. move the current file position to a different location.
d. it changes the file position only if allowed to do so else returns an error.
2. Which of the following statements correctly explain the function of seek() method?
a. tell the current position within the file.
b. indicate that the next read or write occurs from that position in a file.
c. determine if you can move the file position or not.
d. move the current file position to a different location at a defined offset.
3. Which of the following command is used to open a text file “c:\[Link]” in append-mode?
a. outfile = open(“c:/[Link]”, “a”)
b. outfile = open(“c:\\[Link]”, “ab”)
c. outfile = open(“c:\[Link]”, “ab+”)
d. outfile = open(“c:\\[Link]”, “a”)
4. Which of the following commands can be used to read “n” number of characters from a file
using the file object <file>?
a. [Link](n)
b. n = [Link]()
c. [Link](n)
d. [Link]()
5. Which of the following commands can be used to read the entire contents of a file as a string
using the file object <tmpfile>?
a. [Link](n)
b. [Link]()
c. [Link]()
d. [Link]()
8. Unpickling is done by .
a. open() b. close() c. load() d. dump()
9. In separated value files such as .csv , what does the first row in the file typically contain?
a. The author of the table data
b. The source of the data
c. Notes about the table data
d. The column names of the data
10. 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.tab_reader(my_data)
b. [Link](my_data)
c. [Link](my_data, delimiter='\t')
d. [Link](my_data, tab_delimited=True)
2. Write a Python program to count all the line having 'a' as last character
3. Write a method/function Count() to count numbers of words having 4 characters from a text
file “[Link]”.
4. Write a function disp() to in python to read lines from a text file and display those lines starting with
„G‟ or „g‟ along with line number from the text file “[Link]”.
5. A text file contains alphanumeric text (say [Link]). Write a program that reads this text file and
prints only the numbers or digits from the file.
6. Write a function remove_lowercase( ) that accepts two filenames, and copies all lines that do
not start with a lowercase letter from the first file into the second.
11. A binary file “[Link]” has structure [empid,empname]. Write a function delrec(empid) in
python that would read contents of the file “[Link]” and delete the details of those employee
number is passed as argument.
13. write a program to add/insert records in file “[Link]”. Structure of record is roll number, name
and class.
14. Write a programme to display all the record from [Link] whose marks is more then 70. Format of
record stored in [Link] is rollno, name , class and marks
15. Amar is a Python programmer. He has written a code and created a binary file [Link] with
employeeid, ename and salary. The file contains 10 records. He now has to update a record based on
the employee id entered by the user and update the salary. The updated record is then to be written in
the file [Link]. The records which are not to be updated also have to be written to the file
[Link]. If the employee id is not found, an appropriate message should to be displayed. As a
Python expert, help him to complete the following code based on the requirement given above:
import_________#Statement 1
def update_data():
rec={}
fin=open("[Link]","rb")
fout=open("______________") #Statement 2
found=False
eid=int(input("Enter employee id to update their salary :: "))
while True:
try:
rec=_______________#Statement 3
if rec["Employee id"]==eid:
found=True
rec["Salary"]=int(input("Enter new salary::
")) pickle___________#Statement 4
else:
[Link](rec,fout)
except:
break
if found==True:
print("The salary of employee id ",eid," has been updated.")
else:
print("No employee with such id is not found")
[Link]()
[Link]()
(i) Which module should be imported in the program? (Statement1)
(ii) Write the correct statement required to open a temporary file named [Link]. (Statement 2)
(iii) Which statement should Aman fill in Statement 3 to read the data from the binary file, [Link]
and in Statement 4 to
(iv) write the updated data in the file, [Link]?
DATA STRUCTURE
DATA STRUCTURE is physical implementation that clearly defines a way of storing, accessing and
manipulation of data stored in data structure. Every data structure has a specific way of insertion and
deletion like STACK work on LIFO i.e. all operation will take from one end i.e. TOP where as
QUEUE works on FIFO i.e. item inserted first will be removed first and new item will always added
to the end of QUEUE. In python we will use LIST as a data structure for implementation of stack.
OPERATIONS DESCRIPTION
INSERTION Addition of new data to data structure
DELETION Removal of data element from data structure
SEARCHING Finding specific data element in data structure
TRAVERSAL Processing all data elements one by one
SORTING Arranging data elements in ascending or descending order
MERGING Combining elements of two similar data structure to form a new data
structure.
Operation on Stacks:
Stack( ): It creates a new stack that is empty. It needs no parameter and returns an empty stack.
push(item): It adds a new item to the top of the stack.
pop( ): It removes the top item from the stack.
peek( ): It returns the top item from the stack but does not remove it.
isEmpty( ): It tests whether the stack is empty.
size( ): It returns the number of items on the stack
PUSH Operation:
The process of adding one element or item to the stack is represented by an operation
called as the PUSH operation.
The new element is added at the topmost position of the stack.
POP Operation:
The process of deleting one element or item from the stack is represented by an
operation called as the POP operation.
Application of Stacks:
It is used to reverse a word. You push a given word to stack – letter by letter and then pop letter
from the stack.
“Undo” mechanism in text editor.
Backtracking: This is a process when you need to access the most recent data element in a series
of elements. Once you reach a dead end, you must backtrack.
Language Processing: Compiler‟ syntax check for matching braces in implemented by using stack.
Conversion of decimal number to binary.
Conversion of infix expression into prefix and postfix.
Quick sort
Runtime memory management.
8. If the name of linear list of 10 elements is LIL, then its element will be referenced
a) LIL[0], LIL[1], LIL[2]………LIL[9]
b) LIL[0],LIL[1],LIL[2]………LIL[10]
c) LIL(0),LIL(1),LIL(2)………LIL(9)
d) LIL(0),LIL(1),LIL(2)………LIL(10)
9. what is searching?
a) Involves searching for the specified data element in a data structure.
b) it data structure means processing all the data elements of it .
c) Arranging data elements of a data structure in a specified order.
d) Combining elements of two similar data structures to form a new data structures of same type
10. Which search technique searches the given ITEM in minimum possible comparisons in a
sorted linear list.
a) Linear search
b) Binary search
c) Double search
d) trinary search
12. Python provides a method that itself takes care of shifting of elements and removing
the corresponding material.
a) add
b) insort
c) remove
d) bisect
13. Lst=[[2,3,4],[22,32,43],[50,60,70],[9,10,11]]
what will be the output of
print(Lst[:2])
a)[1,2,3,4,5] b)[[1,2],
[3,4]]
c)[[2,3,4],[22,32,43]]
d)[[50,60,70],[9,10,11]]
14. What is the situation when one tries to push an item in stack that is full.
a) peek
b) underflow
c) overflow
d) pop
15. What is called when one tries to pop/delete an item from an empty stack.
a) peek
b) underflow
c) overflow
d) pop
4. Write the function sumAlternate(MYLIST) as argument and calculate the sum of all
alternate elements of MYLIST and print it
For e.g. if the elements are
[5, 11, 17, 19, 25, 29, 30, 32, 56, 90]
Output should be : Total=133
5. Write a function EvenOdd(MYLIST), which doubles each Odd elements of MYLIST and half
each Even element of MYLIST.
For e.g. if MYLIST = [10,11,40,4,17,23,45,100,80]
output should be [5,22,20,2,34,46,90,50,40]
7. Write a function in python, Push(Employee) and Pop(Employee) to add a new Employee and delete
a Employee from a List of Employee Names, considering them to act as push and pop operations of
the Stack data structure.
8. Write a Python function/method SwapMiddle(Codes) to swap the first half of the content of the list
Codes with second half of the list Codes and display the swapped values.
For e.g. if the list Codes contains : [22,44,55,66,88,11] then function should swap and display as:
[66,88,11,22,44,55]
9. Write a function in python, Push(Package) and Pop(Package) to add details of employee contain
information (Empid, Ename and Salary) in the form of tuple in Package and delete a Package from a
List of Package Description, considering them to act as push and pop operations of the Stack data
structure
Connections among computers makes computer networks. In a computer network, two or more autonomous
computing devices are connected to each other to exchange information orshare resources.
Advantages
Resources such as printer, scanner, projector, etc. are shared among deviceswhich is cheaper
than buying separatelyfor each computer
Software can be installed centrally ratherthan on each computer. It's cheaper thanbuying licenses
for every computer
Shared storages can be used to accessfiles and data from any machine on thenetwork
Disadvantages
Systems are more complex to run. Specialists might be required for managing which increases
the cost
If networks are badly managed, it can become unusable and productivity mayfall
If the central server fails, it becomes impossible for other machines to carryout any work.
Files' security is harder to implement, [Link] from viruses
Network Basics
Host or node or workstation refers to the computers/devices that are attached to thenetwork.
A server is the computer which facilitates the sharing of data, software and hardware resourceson
the network. A server serves the requests ofthe clients.
A client is a host computer thatrequests for services from a server.
Other than wiring and computers, Network Hardware consists of : NIC(Network Interface Unit)
: Network Card connected to the host to establish networkconnections, Hub, Switch, Router.
Hosts in a network interact with other hosts and server(s) through a Communication Channel which can
be:
Wired : When connections are through guided media like twisted-pair, coaxial, optical fiber.
Wireless : When connections are through unguided media like Microwaves, radio waves,
satellites, infrared waves, lasers etc.
Types of Networks
Local Area Network (LAN)
Small computers networks that are confined to a localized area. Data, information,
programs,printers, storage, modems, etc. are shared.
e.g. office, building, industry.
Wide Area Network (WAN)
These networks spread across countries or on a very big geographical area. It can even be
agroup of LANs that are spread across several locations. Internet is the largest WAN.
Metropolitan Area Network (MAN)
These networks spread across an area as big as a city. Now, this term has become
[Link] is generally used.
Personal Area Network(PAN)
It's an interconnection of devices within the range of an individual person, typically
within a range of 10m.
Wired Networks
As the name suggests hosts and other devices are connected by wires or cables. Mostly
used in LANs. Although, these days there are wireless LAN too.
a. Twisted Pair Cable : It's a pair of insulated wires that are twisted together to
improve electromagnetic capability and to reduce noise from outside sources.
These are available in CAT1, CAT2, CAT3, CAT4, CAT5, CAT6.
b. Coaxial Cable(coax) : It consists of a solid wire core surrounded by one or more
foilor wire shields, each separated by some kind of plastic insulator.
Most commonly used are thicknet, thinnet.
c. Fiber Optic Cable/ Optic Fiber Cable : It consists of a bundle of glass threads,
eachthread is capable of transmitting information modulated onto light waves.
Common Fiber Optic Cables are single node and multi-node.
Wireless Networks
Information is transferred using electromagnetic waves like IR(Infrared), RF(Radio frequencies),
satellite, etc. through environment/air as the media.
Wi-fi in home is an example of Wireless LAN. Satellites are used for Wireless [Link]
commonly used transmission media in wireless networks are :
a. Microwave : These are high frequency waves that can be used to transmit data
overlong distances. There's a transmitter, receiver & atmosphere.
e.g. Mobile phone calls
b. Radio waves : These are waves of frequency range 30Hz - 300GHz, used to
transmit television & radio. All radios use continuous sine waves to transmit
information.
e.g. Wi-Fi also uses radio waves to transmit between devices and router.
c. Satellite(Satellite Microwave) : It's a microwave relay system which uses
synchronoussatellite to relay the radio signal transmitted from ground station.
Communication satellites owned by both govt. and pvt. organizations have been places in
stationary orbits about 22,300 miles above the earth's surface. Satellite accepts signals
transmitted from earth station,
amplify them, and return them to another earth station. It's used when we need to transmit data over a
very large distance.
d. Infrared : It uses infrared light to send data. This is found in everyday life - TV remotes,
automatic doors, wireless speakers. It transmits data through the air and canpropogate
throughout a room(bouncing off surfaces), but can't penetrate walls. It's become common
in PDAs (Personal Digital Assistant). It's considered to be a secure one.
e.g. hand held devices like palm pilots, etc.
Switching Techniques
[Link] Switching
The complete physical connection between two computers is established and then data is transmitted from the
source computer to the destination computer. A proper end-to-end path (connection) using a physical copper
wire is made.
2. Message Switching
Source computer sends data or the message to the switching office first, which stores the datain its
buffer. It then looks for a free link to another switching office and then sends the data to this office.
This process is continued until the data is delivered to the destination computers.
This is also known as store and forward.
3. Packet Switching
In Message switching, there's no limit on block size. Packet switching places a tight upper limiton block size.
Also in message switching, data packets are stored on the disk in message switching whereas in
packet switching, all packets of fixed size are stored in main memory.
This improves the performance as the access time is reduced, thus the overall performance of the
network is improved.
Bandwidth
Bandwidth(Width of allocated band of frequencies) is the difference between the highest and lowest
frequencies. High bandwidth channels are called Broadband. Low bandwidth channels are
called narrowband channels. It's unit is Hertz(same as frequency) which represents cycles per
second. A kilohertz(KHz) represents a thousand Hertz(Hz).
1 MegaHertz(MHz) = 1000 KiloHertz(KHz)
1 GigaHertz(GHz) = 1000 MegaHertz(MHz)
1 TetraHertz(THz) = 1000 GigaHertz(MHz)
Network Topology
The pattern of interconnection of nodes in a network is called Network Topology.
Star topology
It consists of a central node to which all other nodes are connected by a single path.
e.g. data processing, voice communication, etc.
It is easy to install and wire.
If one node fails, network stays stable.
Connecting or removing devices doesn't affect the network.
Diagnosis is
easy. Disadvantages
Requires more cable length.
If hub, switch, or concentrator fails, nodes attached are
disabled. More expensive than linear topology.
Mesh Topology
Each node is connected to more than one node, which provides and alternative route in thecase host
is either down or busy. It's excellent for long distance networking as it provides back-up &
rerouting which is ideal for distributed networks.
Each connection can carry its own data load.
It can mange high traffic as multiple devices can transmit work simultaneously.
It's robust, provides security and privacy.
Diagnosis is easy.
Installation, configuration & Management is
difficult. Bulk wiring is required, cables cost is
more.
Chances of redundancy is high which leads to higher cost and lower effeciency.
Tree or Expanded Star Topology
It's the combination of linear bus and star topologies. Groups of star-configured workstations
connected to a linear bus backbone.
It provides high security.
Scalability is high as more leaf nodes(star-configured nodes) can be [Link] uses point-
to- point wiring for individual segments.
It's supported by several hardware and software [Link]
backbone falls, individual star groups keep on working.
Disadvantages
Overall cable length increases.
If backbone falls all leaf nodes gets disconnected. Difficult to configure and wire than
other topologies. If hub, switch or concentrator fails, attached nodes gets disconnected.
NETWORK TERMINOLOGIES
NIC (Network Interface Card)
It's a special device attached to each node and the server which helps them establish all important
connections with the network. Each node's NIC has a unique number identifying it,known as the node
address.
NIC is also known as Terminal Access Point(TAP) or Network Interface Unit(NIU).
MAC address
Manufacturers assigns a unique physical address to each NIC card known as MAC address(Media
Access Control Address). It's a 6-byte address, each byte separated by a colon.
80 : 1A : 04 : 36 : 8E : 21
WiFi card
It's either an internal or external LAN(Local Area Network) adapter with a built-in wireless radioand
antenna. There are multiple types. Most common Wi-Fi cards used in desktop computers are
PCI- Express Wi-Fi cards made to fit the slot in motherboards.
MODEM(Modulator Demodulator)
This device is used to convert the digital signals into analog
signals(Audio Frequency tones)and vice versa. Mainly used to
connect telephone/radio lines to a computer terminal.
Internal modems are fixed within the computer. External
modems are connected externally as other nodes.
Ethernet Card
It's a NIC that connects a computer to a computer network. In most of t he
new computers the ethernet port is built into computer, whereas in the earlier
computer it was available on an expansion card that used to be plugged
into the motherboard.
Router
As the name suggests, it handles routes of the data packets. It's a networking
device, that forwards data packet between computer networks. This creates an
overlay i nternet connection which connects multiple independent networks. It's
basic role is to determine best possible route(shortest path) for the data packets to
be transmitted.
Hub
A hub is a connecting device which connects multiple computers together to form a LAN. It
connects multiple devices through RJ45 connectors in a star topology.
Signal entering any port is broadcasted out on all other ports.
Switch
It's a multi-ported device which connects multiple computers together
to form a LAN similarto hub, but switch is a smart hub. It has the
intelligence to send the data directly to the destination rather than broadcast
to whole network. Data packets received from one end are refreshed and
delivered to address of the destination.
Gateway
It's a device that connects dissimilar networks. As the name suggests it acts as an entrance toanother
network(maybe with different protocol structure). It's also called protocol converter as it convert data
packets from one protocol to other. It also conceals the IP address of the user sending out information,
outsiders can only see the IP address of the gateway.
Network Protocol
A protocol means the rules that are applicable for a network. It defines standardized formats for data
packets, techniques for detecting and correcting errors and so on. It's a formal description of message
formats and rules that devices must follow to exchange data seamlessly without any interruptions and
contradictions.
Remote Login(Telnet)
It's a program that allows user to establish a virtual terminal connection between two machines
using TCP/IP. It's an internet utility that lets you log onto remote computer systems.
Internet
It's a worldwide network of computer networks that evolved from the first network ARPANET. It'san
interconnection of large and small networks around the globe that allows all the computers to
exchange information with each other.
To accomplish connections between all computers there must be a common set of rules for
communication, known as protocols.
Wireless/Mobile Communication
It refers to the method of transferring information between devices without any physical
connection. e.g. Wi-Fi, Bluetooth, Radio Waves, etc.
GSM(Global System for Mobile communication)
GSM(Global System for Mobile communication) is a wide area wireless communications system that uses
digital radio transmission to provide voice, data, and multimedia communication services. It's one of the
leading digital cellular system. It uses TDMA(Time Division Multiple Access), which allows eight
simultaneous calls on the same radio frequency.
1G
1G networks(NMT, C-Nets, AMPS, TACS) are considered to be the first analog cellular systemsstarted
in 1980s. It was purely designed for voice calls with almost no consideration of data services.
2G(GSM)
2G networks(GSM, CDMAOne, D-AMPS) are the first digital cellular systems launched early
1990s, offering improved sound quality, better security and higher total capacity. In
CDMAtechnology, data and voice packets are separated using codes and then transmitted using a
wide frequency range.
2.5G
2.5G networks(GPRS, CDMA2000 1x) are enhanced versions of 2G networks with data ratesupto
144kbps. GPRS offered first always-on data service.
3G
3G networks(UMTS FDD and TDD, CDMA2000 1x EVDO, CDMA2000 3x, TD-SCDMA, Arib
WCDMA, EDGE, IMT-2000 DECT) are 3rd generation wireless technologies with enhancements like
high-speed transmission, advanced multimedia access and global roaming. Stationary speedsof
2Mbps and mobile speeds of 384kbps for a true 3G.
4G
4G is an improved version of 3G but only in terms of fast web-experience. It offers downlink data
rates over 100Mbps, low latency, very efficient spectrum use and low-cost implementations. It's
also referred as MAGIC(Mobile Multimedia, Anywhere, Global Mobility, Integrated Wireless &
Customized Services). 4G is convergence of wired and wireless networks, including GSM, WLAN and
bluetooth as well as computers, communication devices and others.
5G
5G is the fifth generation of broadband cellular networks began worldwide in 2019. 5G's service area
is divided into small geographical areas called cells. Devices in a cell are connectedto network by
radio waves through a local antenna in the cell. Greater bandwidth and higher download speeds
eventually
upto 10Gbps. This increased speed is achieved partly by using higher frequency radio waves than
previous cellular networks. However they have a shorter range, requiring smaller geographic cells.
Mobile Processors
A mobile processor is a CPU chip designed for portable computers/mobile phones. It's typically housed
in a smaller chip package without fan, in order to run cooler it uses lower voltages than other
components. They have more sleep mode capabilities to conserve powerand prolonged battery
life.
e.g. Qualcomm Snapdragon 865, Exynos 990, Apple A14, etc.
Chat
It's an application to communicate with a person, group on internet in real time by typing text. We type a
message in our device which is immediately received by the recipient, then recipient can respond to
our message, which is received by us immediately.
Video Conferencing
It's a two-way video conversation between two or more participants on the internet or a private
network. Each user has a video camera, microphone and speaker on his/her computer,participants
speak to one another, they hear each other's voices and see a video image of otherparticipants.
Wi-Fi(Wireless Fidelity)
Wi-Fi is a family of wireless network protocols, based on IEEE 802.11 family of standards, which are
commonly used for local area networking of devices and internet access. Wi-Fi is a trademarkof Wi-Fi
Alliance, it's not a technical term, alliance has enforced its use to describe only a narrowrange of
connectivity technologies including wireless local area network(WLAN).
WiMAX
WiMAX(Worldwide Interoperability for Microwave Access) is a family of wireless broadband
digital communication system. It can provide broadband wireless access(BWA) up to 50km for
fixed stations and 5-15km for mobile stations which is significantly larger than WiFi(30- 100m).
WiMax requires a tower called WiMax Base Station, similar to a cellphone tower, which is
connected to the Internet using a standard wired high-speed connection.
Domain Name
Domain name is a component of a URL, it's the identification string that defines the name of theparticular
website.
Website
A website is a collection of web pages usually containing hyperlinks to each others representing
information of a company or individual on the World Wide Web. It's a location on a net server which has
a unique URL.
Web Browser
It's a client software that is used to access various kinds of internet resources using HTTP which also helps us
navigate through World Wide Web and display web pages.
e.g. Google Chrome, Mozilla Firefox, Opera, Safari, etc.
Web Servers
It's a computer that stores data and makes them available to rest of the world(Internet). Aserver may be
dedicated, meaning its sole purpose is to be a web server. A non-dedicated server can be used for
basic computing in addition to acting as a server. It responds to the requests made by web
browsers.
Web Hosting
It's a service that allows user to upload and store a website's HTML documents and other data on a web
server. It makes the file available on the World Wide Web to be used by public. It's also known as
site hosting.
4 In which topology are all the nodes connected through a single Coaxial cable?
(a) Star
(b) Tree
(c) Bus
(d) Ring
6 Central Computer which is more powerful than other computers in the network is called
.
(a) Client
(b) Server
(c) Hub
(d) Switch
7 Network in which every computer is capable of playing the role of a client, or a server or
both at same time is called
(a) peer-to-peer network
(b) local area network
(c) dedicated server network
(d) wide area network
13 Hub is a
(a) Broadcast device
(b) Uni-cast device
(c) Multi-cast device
(d) None of the above
14 Switch is a
(a) Broadcast device
(b) Uni-cast device
(c) Multi-cast device
(d) None of the above
16 Protocols are
(a) Agreements on how communication components and devices are to communicate
(b) Logical communication channels for transferring data
(c) Physical communication channels used for transferring data
(d) None of above
18 A firewall is
(a) An established network performance reference point.
(b) Software or hardware used to secureagainstrd a private network from a public
network.
(c) A virus that infects macros.
(d) A predefined encryption key used to encrypt and decrypt data transmissions.
21 What factors should be considered when selecting the appropriate cable for connecting a
PC to a network? (Choose two)
(a) type of system bus
(b) motherboard model
(c) computer manufacturer
(d) distance of cable and speed of transmission
22 Which cable connectors are used to connect a cat6 cable from a router's console port to a
PC?
(a) RJ-11
(b) RJ-12
(c) RJ-45
(d) none
24 Which of the following devices can be used at the centre of a star topology?
(a) Router
(b) Repeater
(c) Modem
(d) Hub
25 Data is converted in a form so as to travel over telephone lines using this device.
(a) Modem
(b) Hub
(c) Switch
(d) Router
29 Networks devices that sends the data over optimizing paths through connected hops is
(a) Hub
(b) Router
(c) Bridge
(d) Gateway
31 Which portion of the URL below records the directory or folder of the desired resource ?
[Link]
(a) http
(b) firstfloor
(c) [Link]
(d) [Link]
38 Bluetooth is an example of
a) Wide area network
b) Virtual private network
c) Local area network
d) Personal area network
39 MAC address is of
a) 24 bits
b) 36 bits
c) 42 bits
d) 48 bits
42 Which of the following protocol is used for remote terminal connection service?
a) RARP
b) UDP
c) FTP
d) TELNET
44 It allows a visited website to store its own information about a user on the user‟s
computer:
a) Spam
b)cookies
c)Malware
d)Adware
45 In which of the following switching methods, the message is divided into small
packets?
a) Message switching
b) Packet switching
c) Circuit switching
d) None of these
48 Which of the following cable consist of a solid wire core surrounded by one or more
foil or wire shields?
a) Ethernet Cables
b)Coaxial Cables
c) Fibre Optic Cables
d)Power Cable
Expanded form
1. ARPANET: Advanced Research Projects Agency NETwork
2. NSFnet: National Science Foundation network
3. Internet: Inter networking
4. TCP/IP: Transmission Control Protocol / Internet Protocol
5. NIU: Network Interface Unit
6. TAP: Terminal Access Point
7. NIC: Network Interface Card
8. MAC Address: Media Access Control Address
9. bps: bits per second
10. Bps: Bytes per second
11. kbps: kilo bits per second
12. Kbps: Kilo bytes per second
13. mbps: mega bits per second
14. Mbps: mega bytes per second
15. kHz: kilohertz
16. MHz: megahertz
17. GHz: gigahertz
18. THz: terahertz
19. LAN: Local Area Network
20. UTP: Unshielded Twisted Pair Cable
21. CAT1: Category 1 UTP cable (same acronym for other CATs)
22. STP: Shielded Twisted Pair Cable
23. LEDs: Light Emitting Diodes
24. LDs: Laser Diodes
25. PDAs: Personal Digital Assistants / Personal Data Assistant
26. WAN: Wide Area Network
27. MAN: Metropolitan Area Network
28. PAN: Personal Area Network
29. P-P link: Point to Point Link
30. Modem: Modulator – Demodulator
31. RTS: Request To Send
32. RJ-45: Registered Jack-45
33. DEC: Digital Equipment Corporation (company that made Ethernet)
34. RJ-11: Registered Jack-11
35. BNC: Bayone-Neill-Concelman
36. AUI connector: Attachment Unit Interface (15 pin connector)
37. subnets: subnetworks (also called LAN segments)
38. SNA: Systems Network Architecture
39. ISP: Internet Service Provider
40. OSI model: Open Systems Interconnection Model
41. IP address: Internet Protocol Address
42. FDDI networks: Fiber Distributed Data Interface networks
43. NOSS: Networking Operating System Software
44. ISDN: Integrated Services Digital Network
45. AP: Access Point
46. NFS: Network File System
47. HTTP: Hypertext Transfer Protocol
48. WWW: World Wide Web
49. URI: Uniform Resource Identifier
50. URL: Uniform Resource Locator
51. URN: Uniform Resource Name
52. MIME: Multipurpose Internet Mail Extensions
53. SMTP: Simple Mail Transfer Protocol
54. NNTP: Network News Transfer Protocol
55. FTP: File Transfer Protocol
56. PPP: Point to Point Protocols
57. GSM: Global System for Mobile communications
58. SIM: Subscriber Identification Module / Subscriber Identity Module
59. CDMA: Code-Divison Multiple Access
60. WLL/WiLL: Wireless in Local Loop
61. PBX: Private Branch Exchange
62. PSTN: Public Switched Telephone Network
63. GPRS: General Packet Radio Service
64. LTE: Long Term Evolution
65. SMS: Short Message Service
66. VoIP: Voice over Internet Protocol
67. Wi-Fi: Wireless Fidelity
68. WiMAX: Worldwide Interoperability for Microwave Access
69. EDGE: Enhanced Data rates for GSM Evolution
70. Telnet: Teletype Network
71. HTML: Hypertext Markup Language
72. DNS: Domain Name System
73. POP: Post Office Protocol
74. XML: eXtensible Markup Language
75. DHTML: Dynamic HTML
76. SSL: Secure Socket Layer
[Link] is RJ 45 connector?
• Used with twisted pair cable
• Full form is Registered Jack
• Plugin to network devices
• Primarily for LANs
9. What is repeater?
• Repeater is a network device used to boost the signal.
• Used to boost the signals to send for long distance.
• Also known as signal booster.
• Its task is to amplify the signal.
MODEM stands for Modulator/Demodulator. It is device used to convert analog signal to digital signal and
vice versa. It is basically used to run internet on your computer/device.
RJ45 stands for Registered Jack 45. It is an 8 wire connector used to connect computers on a. LAN or
Ethernet Card.
Switching is the technique of transmitting information from one device/network to another. There
A switch is a device used to interconnect computers on a network but it provides dedicated bandwidth to all
connected computers.
A bridge is a network device used to interconnect two networks that follow same protocols.
A router is a network device used to interconnect networks having different protocols. Router forwards
data from one computer to another by shortest path.
A WiFi card is an internal or external Local area network adapter with a builtin wireless radio and antenna.
Q1. An App. Development Company has set up its new center at Bhubaneswar for its office andweb based
activities. It has 4 blocks of buildings named Block A, Block B, Block C, BlockD.
a) Suggest the most suitable place (i.e. block) to house the server of this companywith a suitable reason.
b) Suggest the ideal layout to connect all the blocks with a wired connectivity.
c) Which device will you suggest to be placed/installed in each of these blocks toefficiently connect all
the computers within these blocks.
d) Suggest the placement of a repeater in the network with justification.
e) Suggest the best topology for block C if available hub/switch maximum number of port is 24.
Q2. AIIMS is setting up its center in Bhubaneswar with fourspecialized departments for Orthopedics,
Neurology and Pediatrics along with an administrative office in separate buildings. The physical distances
between these department buildings and the number of computers to be installed in these departments and
administrative office are given as follows.
You, as a network expert, have to answer the queries as raised by them in (i) to
(iv). Shortest distances between various locations in metres :
Administrative Office to Orthopedics Unit 55
Neurology Unit to Administrative Office 30
Orthopedics Unit to Neurology Unit 70
Pediatrics Unit to Neurology Unit 50
Pediatrics Unit to Administrative Office 40
Pediatrics Unit to Orthopedics Unit 110
Number of Computers installed at various locations are as
follows Pediatrics Unit 40
Administrative Office 140
Neurology 50
Orthopedics Unit 80
(i) Suggest the most suitable location to install the main server of thisinstitution to
get efficient connectivity.
(ii) Suggest the best cable layout for effective network connectivity of thebuilding
having server with all the other buildings.
(iii) Suggest the devices to be installed in each of these buildings for
connectingcomputers installed within the building out of the following:
• Switch
• Gateway
(iv) Suggest a device/software to be installed in the given network to take care ofdata security.
(v) Suggest an efficient as well as economic wired medium to be used within each unit for
connecting computer systems out of the following network cable : Co-axial Cable,
Ethernet Cable, Single Pair Telephone Cable.
Q3. Pixel Design and Training Institute is setting up its centre in Jodhpur with four specialised units for
Design, Media, HR and Training in separate buildings. The physical distances between these units and the
number of computers to be installedin these units are given as follows.
You as a network expert, have to answer the queries as raised by the administratoras given in (i) to (v).
Shortest distances between various locations in metres :
Design Unit to Media Unit 60
Design Unit to HR Unit 40
Design Unit to Training Unit 60
Media Unit to Training Unit 100
Media Unit to HR Unit 50
Training Unit to HR Unit 60
Number of computers installed at various locations are as follows :
Design Unit 40
Media Unit 50
HR Unit 110
Training Unit 40
i) Suggest the most suitable location to install the main server of this institution toget efficient
connectivity.
(ii) Suggest by drawing the best cable layout for effective network connectivity of thebuilding
having server with all the other units.
(iii) Suggest the devices to be installed in each of these buildings for connectingcomputers installed
within each of the units.
(iv) Suggest an efficient as well as economic wired medium to be used within eachunit for
connecting computer systems out of the following network cable :
Co-axial Cable, Ethernet Cable, Single Pair Telephone Cable.
(v) Suggest a protocol that shall be needed to provide Video Conferencing solutionbetween Jodhpur and
HQ which is situated in Delhi.
Q4. Dal-Tech is planning to start their offices in four major cities in India to provide regional IT infrastructure
support in the field of Education and Culture. The company has planned to setup their head office in New
Delhi in three locations and have name their New Delhi office as “Sales Office”, “Head Office” and “Tech
Office”. The company‟s regional offices are located in “Coimbatore”, “Kolkata”, and “Ahmedabad”.
Approximate distance between these office as per network survey team is asfollows:
a) Suggest network type for connecting each of the following set of their offices:
Head Office and Tech Office
Head Office and Coimbatore Office
b)Which device you will suggest to be procured by the company for connecting all the computers with in
each of their offices.
c) Which of the following communication media, you will suggest to be procured by the company for
connecting their local offices in New Delhi for very effective and fast communication.
Telephone Cable ii) Optical fibre iii) Ethernet cable
d) Suggest a Cable /Wiring layout for connecting the company‟s local offices located in New Delhi.
e) Suggest the most suitable location to install the main server of this institution toget efficient connectivity.
Q5. Don Corporation is a professional IT company. The company is planning toset up their new offices in
India with its hub at Delhi. The company has 03 Block named Conference Block, Finance Block, and
Human Resource Block.
Suggest them the best available solutions based on the queries (i) to (v) asmentioned below
: Block to Clock distance in Meters :
Human Resource to Conference Block – 55 mtr.
Human Resource to Finance – 110 mtr
Conference to Finance – 90 mtr.
No. of computers to be installed in each block :-
Human Resource – 150
Finance - 45
Conference – 75
(i) What will be the most appropriate block, where Don Corporation should plan tohouse
the server?
(ii) Suggest the cable layout to connect all the buildings in the mostappropriate manner
for efficient communication.
(iii) What will the best suitable connectivity out of the following to connect the offices
in Bangalore with its New York based office.
(a) Infrared (b) Satellite Link (c ) Ethernet Cable
(b) Suggest the placement of the following devices with justification.
(c) Hub / Switch (b) Repeater
(iv) Which service / protocol will be most helpful to conduct the live interactions of Experts
from New York to Human Resource Block.
(v) Suggest a device/software to be installed in the given network to take care ofdata security.
Hint/Answer Q1:
a) Block C. Reason: Highest number of
computer. b)
Hint/Answer Q2:
(i) Administrative Office. Reason: Highest number of computer.
(ii)
(iii) Switch
(iv) Firewall
(v) Ethernet Cable
Hint/Answer Q3:
(i) HR Unit. Reason: Highest number of computer.
(ii)
(iii) Switch/Hub
(iv) Ethernet Cable
(v) VoIP (Voice over Internet Protocol)
Hint/Answer Q4:
a)
LAN : Head Office and Tech Office WAN:
Head Office and Coimbatore Office
b) Switch/Hub
c) Ethernet cable
d)
e) Head Office
Hint/Answer Q5:
(i) Human Resource. Reason: Highest number of computer.
(ii)
For more information contact: 7355032293/[Link]@[Link] Page 76
(iii) (b) Satellite Link
(iv) VoIP (Voice over Internet Protocol)
(v) Firewall
Introduction to database
• It is a collection of data about one particular enterprise (school, hospital, college, bank etc).
• It is basically a record keeping system, where all the data of the enterprise is stored at one place.
• Each application uses one or the other database at backend to store data generated by the app.
RDBMS terminology:-
• Relation- data arranged in rows and columns which is also known as a table.
• Tuple/record- row of a relation is known as a tuple/record.
• Attribute/ field- column of a relation is known as an attribute/field.
• Degree- number of attributes in a relation is called degree of a relation.
• Cardinality- number of tuples in a relation (excluding header row) is called cardinality of a relation
• Domain-it is set of valid values from which actual values appearing in a field are
drawn. eg. House color of a student in school
Exercise I:
What is a primary key? Explain with an example. 2
Define referential integrity. 2
What is candidate and alternate key? Give an example 2
Identify the degree and cardinality of the Student relation given below . 1
Identify the foreign key in given below Student and Department relations. 1
UPDATE <table_name>
SET <column1>= <value1>, <column2> = <value2>
WHERE <condition>; Eg:-
UPDATE student
SET dob=“2001-12-27”
WHERE admn=1234;
7. The ALTER TABLE statement is used to add, delete, or modify columns in an existing table
and can also be used to add and drop various constraints on an existing table.
Eg1:- query to add a column “f_name” of data type varchar (with size 20 and constraint NOT
NULL) ,in the table student.
ALTER TABLE student ADD f_name varchar(20) NOT NULL;
Eg2:- query to modify the column name, increase the size of column from 20 to 30
ALTER TABLE student MODIFY COLUMN name varchar(30) not null;
Eg3: query to drop the column dob
ALTER TABLE student DROP COLUMN dob;
10. The SELECT statement is used to select data from a [Link] data returned is stored in
a result table, called the result-set.
i. The following SQL statement selects the "CustomerName" and "City" columns from the
"Customers" table:
SELECT CustomerName, City
FROM Customers;
ii. The following SQL statement selects all the columns from the "Customers"
table: SELECT * FROM Customers;
iii. The following SQL statement selects only the DISTINCT values from the Country"
column in the "Customers" table:
SELECT DISTINCT Country FROM Customers;
iv. The following SQL statement selects all fields from "Customers" where country
is "Germany" AND city is "Berlin":
SELECT * FROM Customers
WHERE Country='Germany' AND City='Berlin';
v. The following SQL statement selects all fields from "Customers" where city is "Berlin"
OR "München":
SELECT * FROM Customers
WHERE City='Berlin' OR City='München';
vi. The following SQL statement selects all fields from "Customers" where country is
NOT "Germany":
SELECT * FROM Customers
WHERE NOT
Country='Germany';
vii. The following SQL statement selects all fields from "Customers" where country is
"Germany" AND city must be "Berlin" OR "München" (use parenthesis to form
complex expressions):
SELECT * FROM Customers
WHERE Country='Germany' AND (City='Berlin' OR City='München');
viii. The following SQL statement selects all customers from the "Customers" table, sorted by
the "Country" column:
SELECT * FROM Customers
ORDER BY Country;
x. The following SQL statement selects all customers from the "Customers" table, sorted by
the "Country" and the "CustomerName" column.
This means that it orders by Country, but if some rows have the same Country, it orders them
by CustomerName:
SELECT * FROM Customers
ORDER BY Country,
CustomerName;
xi. The following SQL statement selects all customers from the "Customers" table,
sorted ascending by the "Country" and descending by the "CustomerName" column:
SELECT * FROM Customers
ORDER BY Country ASC, CustomerName DESC;
xii. The GROUP BY statement groups rows that have the same values into summary rows, like
"find the number of customers in each country".
The GROUP BY statement is often used with aggregate functions (COUNT, MAX, MIN,
SUM, AVG) to group the result-set by one or more columns.
The HAVING clause is used to filter groups based on the specified conditions.
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s);
xiii. The following SQL statement lists the number of customers in each
country: SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY
Country;
xiv. The following SQL statement lists the number of customers in each country. Only
include countries with more than 5 customers:
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5;
xv. Condition Based on Pattern Matches:-using LIKE operator, pattern matching on strings is
possible.
Percent (%)- used for matching any substring
Underscore(_) - used for matching one character.
Eg1. Query to display records of employees whose name begin with „A‟ and
ends with „T‟.
SELECT *
FROM TABLE
WHERE name like “A%T”;
Eg2. Query to display records of employees whose name has second letter as
For more information contact: 7355032293/[Link]@[Link] Page 83
„n‟.
SELECT *
Exercise 2:
Write difference between Data Definition Language and Data Manipulation Language. 1
Differentiate the following statement 1
i. DELETE FROM <table_name>;
ii. DROP TABLE <table_name>;
Consider the above given table EXAM of database CBSE and write SQL queries for the following :-
5
i. To display the name of all Subjects in descending order of their subject codes.
ii. To display the content of the EXAM table in alphabetic order of SubjectName
whose exam date is on or after 20-Mar-2014.
iii. To display Subjectname and NumberofStudents from the table EXAM.
iv. To display NumberofStudents whose avgMarks in the range 90 to 250
v. To display lowest and highest marks scored.
Scode SubjectName NOS AvgMarks ExamDate
083 Computer Sc 67 95 22-Mar-2014
301 English 110 85 01-Mar-2014
041 Maths 110 80 20-Mar-2014
042 Physics 100 90 05-Mar-2014
043 Chemistry 100 85 11-Mar-2014
Consider the following tables PRODUCT & CLIENT. Write SQL commands for the statement
(i) to (v) and give outputs for SQL queries (vi) to (vii) 6
Table: PRODUCT
PID Pname Manufacturer Price
HP01 Complan HLL 195
FW01 Face Wash Himalaya 65
BS01 Bar Soap Patanjali 12
CC01 Cold Cream Ponds 55
HL01 Horlicks TDH 215
Table: CLIENT
CID Cname City PID QTY
56 Gopal & Sons Varanasi FW01 120
48 Paradise For You Delhi BS01 80
14 Beauty Collection Lucknow CC01 100
18 Dreamz Varanasi HL01 200
10 Dhanuka Stores Kolkata HP01 150
Consider the following tables Items. Write SQL commands for the statements (i) to (vi).6
Table: Items
No ItemName CostPerItem Qua Date_of_purcha Warrant Operation
. ntity se y al
1 Computer 60000 9 21/5/96 2 7
MYSQL FUNCTIONS
STRING FUNCTIONS
Function Description
Char() Returns the character for each integer passed
Concat() Returns concatenated string
Lower()/lcase Returns the argument in lowercase
Substring()/substr() Returns the specified sbustring
Upper()/ucase() Converts to uppercase
Ltrim() Removes leading spaces
Rtrim Removes trailing spaces
Trim Removes leading and trailing spaces
Instr() Returns the index of the first occurrence of substring
Length() No of characters in a string
Left() Returns leftmost no. of characters
Right() Returns the specified right most no. of characters
Mid() Returns a substring starting from the specified position
Numeric functions
Mod() Returns the remainder of one expression after dividing by another
Power()/pow() Returns the value of on exp raised to the power of another
Exercise 3:
Write the output of the following queries: 1x10
i. SELECT ROUND(15.193,1);
ii. SELECT MOD(11,4);
iii. SELECT MOD(-9,4);
iv. SELECT SUBSTR(“COMPUTER SCIENCE”, 6,3);
v. SELECT INSTR(“CORPORATE FLOOR”, “OR”);
vi. SELECT TRUNCATE(15.79,1);
vii. SELECT CONCAT(“I”, “LIVE”, “IN”,”DELHI”);
viii. SELECT MONTH(“2022-02-03”);
ix. SELECT CURDATE();
x. SELECT MONTHNAME(“2022-06-03”)
Identify the statement to add a column phone char(10) to the table students. 1
i. ALTER TABLE STUDENTS ADD PHONE VARCHAR(10);
ii. ADD PHONE;
iii. UPDATE ADD COLUMN PHONE;
iv. NONE
Which of the following will select only one copy of each set of duplicate rows from a table?
1
i. SELECT UNIQUE
ii. SELECT DICTINCT
iii. SELECT DIFFERENT
iv. ALL OF THESE
The following query is to display salary from greater to smaller and name in alphabetical order
1
Which query will display details of students whose name begin with “Ab”? 1
i. SELECT * FROM student WHERE name LIKE “Ab%”;
ii. SELECT * FROM student WHERE name LIKE “Ab_”;
iii. SELECT * FROM student WHERE name LIKE “Ab”;
iv. SELECT * FROM student WHERE name LIKE “%Ab”;
In SQL, name the clause that is used to display the tuples in ascending order of an attribute.
In SQL, write the query to display the list of tables stored in a database. 1
Which of the following types of table constraints will prevent the entry of duplicate rows? 1
Unique b) Distinct c) Primary Key d) NULL
A departmental store MyStore is considering to maintain their inventory using SQL to store the data.
As a database administer, Abhay has decided that :
• Name of the database - mystore
• Name of the table – STORE
• The attributes of STORE are as follows:
Write the outputs of the SQL queries (i) to (iii) based on the relations Teacher and Posting
given below: 3
Table : Teacher
Name
T Age Department Date_of_join Salary Gender
Jugal
1 Computer
3 Sc 10/01/2017 12000 M
Sharmila
2 History
3 24/03/2008 20000 F
Sandeep
3 Mathematics
3 12/12/2016 30000 M
Sangeeta
4 History
3 01/07/2015 40000 F
Rakesh
5 Mathematics
4 05/09/2007 25000 M
Shyam
6 History
5 27/06/2008 30000 M
Shiv
7 Om Computer
4 Sc 25/02/2017 21000 M
Shalakha
8 Mathematics
3 31/07/2018 20000 F
Table : Posting
P_ID Department Place
1 History Agra
2 Mathematics Raipur
3 Computer Science Delhi
Which function is used to display the total number of records from table in a database?
(a) sum(*)
(b) total(*)
(c) count(*)
(d) return(*)
Table : Placement
P_ID Department Place
1 History Ahmedabad
2 Mathematics Jaipur
3 Computer Sc Nagpur
fetchall()- Fetches all (remaining) rows of a query result, returning them as a sequence of sequences (a
list of tuples)
fetchone()-Fetches the next row of a query result set, returning a single sequence or None when no more
data is available
fetchmany (n)-Fetches the next set of „n‟ rows of a query result, returning a sequence of sequences. It
will return number of rows that matches to the size argument.
Example-7 SELECT QUERY WITH WHERE CLAUSE & VIEW MULTIPLE RECORDS
import [Link]
con=[Link](host="localhost",user="root",passwd="system", database=" STUD_DB")
cur=[Link]()
[Link]("select * from student where marks>90")
res=[Link]()
count=[Link]
print("total no of
rows:",count) for rec in res :
print(rec)
2. The given program is used to connect with MySQL and show the all the records from the table
“master” from the database “test”.
Write the following missing statements to complete the code:
Statement 1 – to import the library object
Statement 2 – to connect with existing local database server
Statement 3 - to form the cursor object
import .connector as pymysql # Statement 1
dbcon=pymysql. (host=”localhost”, user=”root”, passwd =“root”, database= “test”) #
Statement 2
if [Link]()==False:
print(“Error in establishing connection:”)
cur=dbcon_______________() # Statement 3
query=”select * from
master” [Link](query)
resultset=[Link](3)
for row in resultset:
print(row)
[Link]()
3. The given program is used to connect with MySQL and show the all the records from the table “Student”
from the database “School”.
Write the following missing statements to complete the code:
Statement 1 – to form the cursor object
Statement 2 – to execute the query that extracts records of students whose marks are greater than 75.
Statement 3- to read the complete result of the query (records whose marks are greater than 75) into
the object named data, from the table student in the database.
import random
AR=[20,30,40,50,60,70]
FROM=[Link](1,3) 2
TO=[Link](2,4)
for K in range(FROM,TO):
print (AR[K],end=”#“)
(i)10#40#70# (ii)30#40#50#
(iii)50#60#70#(iv)40#50#70#
30. Define Primary Key of a relation in SQL. Give an Example using a dummy table. 2
31. Consider the following Python code is written to access the record of CODE
passed to function: Complete the missing statements:
def Search(eno):
#Assume basic setup import, connection and cursor is created
2
query="select * from emp where empno= ".format(eno)
[Link](query)
results = mycursor.
print(results)
32. Differentiate between DDL and DML with one Example each.2 2
33. What will be the output of following program:
s="welcome2kv"
n=
len(s)
m=""
for i in range(0, n): 2
if (s[i] >= 'a' and s[i] <= 'm'):
m = m +s[i].upper()
elif (s[i] >= 'n' and s[i] <=
'z'): m = m +s[i-1]
elif (s[i].isupper()):
m = m + s[i].lower()
For more information contact: 7355032293/[Link]@[Link] Page
101
else:
m = m +'#'
print(m)
Section-II
34. Write code in Python to calculate and display the frequency of each item in a list.
Ex. A[5,2,7,3,4,5,1,7,5]
Out will as :
5- 3
3
2-1
7-2
3- 1
1 -- 1
35. Write a function COUNT_AND( ) in Python to read the text file “[Link]”
and count the number of times “AND” occurs in the file. (include AND/and/And in
the counting)
OR 3
Write a function DISPLAYWORDS( ) in python to display the count of words
starting with “t” or “T” in a text file „[Link]‟.
36. Write a output for SQL queries (i) to (iii), which are based on the table: SCHOOL
and ADMIN given below:
TABLE: SCHOOL
CODE TEACHERNAME SUBJECT DOJ PERODS EXPERIENCE
1001 RAVI SHANKAR ENGLISH 12/03/2000 24 10
1009 PRIYA RAI PHYSICS 03/09/1998 26 12
1203 LISA ANAND ENGLISH 09/04/2000 27 5
1045 YASHRAJ MATHS 24/08/2000 24 15
1123 GANAN PHYSICS 16/07/1999 28 3
1167 HARISH B CHEMISTRY 19/10/1999 27 5
1215 UMESH PHYSICS 11/05/1998 22 16
TABLE: ADMIN
CODE GENDER DESIGNATION 3
1001 MALE VICE PRINCIPAL
1009 FEMALE COORDINATOR
1203 FEMALE COORDINATOR
1045 MALE HOD
1123 MALE SENIOR TEACHER
1167 MALE SENIOR TEACHER
1215 MALE HOD
Section-III
38. PVS Computers decided to open a new office at Ernakulum, the office consist of
Five Buildings and each contains number of computers. The details are shown
below.
Building-2
Building-1 Building-3
n the building
Building
General instructions:
This question paper contains five sections, Section A to E.
All questions are compulsory.
Section A have 18 questions carrying 01 mark each.
Section B has 07 Very Short Answer type questions carrying 02 marks each.
Section C has 05 Short Answer type questions carrying 03 marks each.
Section D has 03 Long Answer type questions carrying 05 marks each.
Section E has 02 questions carrying 04 marks each. One internal choice is given in Q35 against part
C only.
All programming questions are to be answered using Python Language only.
Section – A
Q01. State True or False (1)
“Tuple is datatype in Python which contain data in key-value pair.”
Q22. Explain the use of „Foreign Key‟ in a Relational Database Management System. Give (2)
example to support your answer.
Q24. Predict the output of the Python code given below: (2)
data=["L",20,"M",40,"N",60]
times=0
alpha="
" add=0
for c in range(1,6,2):
times = times + c
alpha = alpha + data [c-1] +
"@" add = add + data[c]
print (times, add, alpha)
Q25. Differentiate between order by and group by clause in SQL with appropriate example. (2)
OR
LAYS ONION 10 5
LAYS TOMATO 20 12
UNCLE CHIPS SPICY 12 10
UNCLE CHIPS PUDINA 10 12
HALDIRAM SALTY 10 20
HALDIRAM TOMATO 25 30
(i) Select BRAND_NAME, FLAVOUR from CHIPS where PRICE <> 10;
(ii) Select * from CHIPS where FLAVOUR=”TOMATO” and PRICE > 20;
(iii) Select BRAND_NAME from CHIPS where price > 15 and QUANTITY < 15;
(iv) Select count( distinct (BRAND_NAME)) from CHIPS;
(v) Select price , price *1.5 from CHIPS where FLAVOUR = “PUDINA”;
(vi) Select distinct (BRAND_NAME) from CHIPS order by BRAND_NAME desc;
Q27. Write a function countINDIA() which read a text file „[Link]‟ and print the frequency (3)
of the words „India‟ in it (ignoring case of the word).
Example: If the file content is as follows:
OR
Write a function countVowel() in Python, which should read each character of a text file
“[Link]” and then count and display the count of occurrence of vowels (including small
Table: ISSUED
BID QTY_ISSUED
HIST66 10
COMP11 5
LITR88 15
(i) Display book name and author name and price of computer type books.
(ii) To increase the price of all history books by Rs 50.
(iii) Show the details of all books in ascending order of their prices.
(iv) To display book id, book name and quantity issued for all books which have
been issued.
OR
Write a function in Python, Push(SItem) where, SItem is a dictionary containing the details
of stationary items– {Sname:price}.
The function should push the names of those items in the stack who have price greater than
25. Also display the count of elements pushed into the stack.
For example:
If the dictionary contains the following data:
Ditem = {“Rubber”:5, "Pencil":5, "Pen":30, "Notebook": 60, "Eraser":5, “Watch”: 250}
The stack should contain
Pen
Notebook
Watch
The output should be:
The count of elements in the stack is 3
Section – D
Q31. Aryan Infotech Solutions has set up its new center at Kamla Nagar for its office and web (5)
based activities. The company compound has 4 buildings as shown in the diagram below:
Orbit
Building
Sunrise
Jupiter
Building
Building
Oracle
Building
#main-code
a=10
b=5
printMe(a,b)
printMe(r=4,q=2)
(B) The code given below inserts the following record in the table Student:
RollNo Name Clas Marks
Integer String Integer Integer
Note the following to establish connectivity between Python and MySQL:
* Username is root
* Password is toor@123
* The table exists in a “stud” database.
* The details (RollNo, Name, Clas and Marks) are to be accepted from the
user. Write the following missing statements to complete the code:
Statement 1 – to form the cursor object
Statement 2 – to execute the command that inserts the record in the table Student.
Statement 3 - to add the record permanently in the database
import [Link] as mysql
def sqlData():
con1=[Link](host="localhost",user="root", password="toor@123",
database="stud")
mycursor =___________________________________________#Statement 1
rno=int(input("Enter Roll Number :: "))
OR
(A) Predict the output of the code given below:
s="C++VsPy"
m=""
for i in range(0, len(s)):
if (s[i] >= 'a' and s[i] <= 'm'):
m = m +s[i].upper()
elif (s[i] >= 'n' and s[i] <=
'z'): m = m +s[i-1]
elif (s[i].isupper()):
m = m + s[i].lower()
else:
m = m +'&'
print(m)
(B) The code given below reads the following record from the table named student
and displays only those records who have marks greater than 90:
RollNo Name Clas Marks
Integer String Integer Integer
Q33. What is the advantage of using a csv file for permanent storage? (5)
Q35. Vishnu is a Python programmer. He has written a code and created a binary file (1+
[Link] with studentid, subjectcode and marks. The file contains 10 records. 1+
He now has to update a record based on the studentid id entered by the user and update the 2)
marks. The updated record is then to be written in the file [Link]. The records which are
not to be updated also have to be written to the file [Link]. If the student id is not found,
an appropriate message should to be displayed.
As a Python expert, help him to complete the following code based on the requirement
given above:
import #Statement 1
-
General Instructions:
1. This question paper contains five sections, Section A to E.
2. All questions are compulsory.
3. Section A have 18 questions carrying 01 mark each.
4. Section B has 07 Very Short Answer type questions carrying 02 marks each.
5. Section C has 05 Short Answer type questions carrying 03 marks each.
6. Section D has 03 Long Answer type questions carrying 05 marks each.
7. Section E has 02 questions carrying 04 marks each. One internal choice is given in Q35 against part c only.
8. All programming questions are to be answered using Python Language only.
SECTION A
1 State True or False: 1
“Python is a dynamically typed language”.
Which of the following will be correct output if the given expression is evaluated?
a) True b) False c) NONE d) NULL
a) [1,2,3]
b) ["One", "Two", "Three"]
c) [2,3]
d) ["Two", "Three"]
6 Which of the following mode in the file opening statement creates a new file if the file does not exist? 1
10 In the relational model, relationships among relations/table are created by using keys. 1
a) composite b) alternate c) candidate d) foreign
11 The correct statement to place the file handle fp1 to the 10th byte from the current position is: 1
a) [Link](10) b) [Link](10, 0) c) [Link](10, 1) d) [Link](10, 2)
14 Suppose str1= 'welcome'. All the following expression produce the same result except one. Which 1
one?
a) str[ : : -6] b) str[ : : -1][ : : -6] c) str[ : :6] d) str[0] + str[-1]
Q17 and 18 are ASSERTION AND REASONING based questions. Mark the correct choice as
a) Both A and R are true and R is the correct explanation for A
b) Both A and R are true and R is not the correct explanation for A
c) A is True but R is False
d) A is false but R is True
SECTION B
19 Identify the errors in the program segment given below. Rewrite the corrected code and underline 2
each correction.
250=Number
WHILE Number <= 1000:
if Number => 750:
print(Number)
Number = Number+100
else
print(Number*2)
Number = Number+50
def Findoutput():
L="Program"
X=""
L1=[]
count =
1 for i in
L:
if i in ['a', 'e', 'i', 'o', 'u']:
X=X+[Link]()
else:
if count%2 != 0:
X=X+str(len(L[:count]))
else:
X=X+i
count=count+1
print(X)
Findoutput()
OR
def Display(str):
m=""
for i in range(0,len(str)):
if(str[i].isupper()):
m=m+str[i].lower()
elif str[i].islower():
m=m+str[i].upper()
else:
if i%2!=0:
For more information contact: 7355032293/[Link]@[Link] Page 109
m=m+str[i-1]
else:
m=m+"$"
print(m)
Display('Fun@Python3.10')
21 Write two points of difference between HTTP and FTP. 2
OR
State two advantages and two disadvantages of star topology over bus topology?
23 What do you understand by Candidate keys in a table? Give a suitable example of Candidate keys 2
from a table containing some meaningful data.
25 Differentiate between DROP and DELETE commands in SQL with appropriate example. 2
OR
Differentiate CHAR and VARCHAR datatypes of SQL with appropriate example.
SECTION C
1+2
EMPLOYEE DEPARTMENT
ENO ENAME DOJ DNO DNO DNAME
E1 RASMI 2005-05-12 D1 D1 ACCOUNTS
E2 ANUP 2006-07-10 NULL D2 HR
E3 RITESH 2005-07-28 D3 D3 ADMIN
b) Write the output of the queries (i) to (iv) based on the table Crockery given below:
Table: CROCKERY
FID NAME DATEOFPURCHASE COST DISCOUNT
B001 CUP 03-Jan-2018 4500 10
For more information contact: 7355032293/[Link]@[Link] Page 110
T010 PLATE 10-Mar-2020 5100 5
B004 SPOON 19-Jul-2021 2200 0
C003 GLASS 30-Dec-2016 1200 3
OR
Write a function in Python which reads the content of a text file [Link] and prints all the lines
containing the word THE (ignore case sensitivity).
28 a) Write SQL queries for (i) to (iv) based on the tables: 2+1
TABLE: CUSTOMER
CNO CNAME ADDRESS
101 Richa Jain Delhi
102 Surbhi Sinha Chennai
103 Lisa Thomas Bangalore
104 Imran Ali Delhi
105 Roshan Singh Chennai
TABLE: TRANSACTION
TRNO CNO AMOUNT TYPE DOT
T001 101 1500 Credit 2017-11-23
T002 103 2000 Debit 2017-05-12
T003 102 3000 Credit 2017-06-10
T004 103 12000 Credit 2017-09-12
T005 101 1000 Debit 2017-09-05
i) To display the details of all transactions of TYPE Credit from the table TRANSACTION.
ii) To display all CNO, CNAME and DOT (date of transaction) of those CUSTOMERS from tables
CUSTOMER and TRANSACTION who have done transactions more than or equal to 2000.
iii) To display the last date of transaction (DOT) from the table TRANSACTION for the customer
having CNO as 103.
iv) To display the total number of transactions and sum of amount from the table TRANSACTIONS
for different customers.
29 Write the definition of a method SUM5_7(X), which receives a number list X and displays the sum of 3
all those numbers which are multiple of 7 but not a multiple of 5.
Ex: if X is [7, 14, 35, 43, 40]
The function should display:
Sum is: 21
For more information contact: 7355032293/[Link]@[Link] Page 111
30 Vedika has created a dictionary containing names and marks as key-value pairs of 10 students. Write 3
a program, with separate user-defined functions to perform the following operations:
OR
Ridhima has a list of numbers (complex, integer and floating point). Write a program, with
separate user-defined functions to perform the following operations:
Traverse the content of the list and push all the positive integers of the list into a stack.
Pop and display the content of the stack.
For Example:
If the sample Content of the list is as follows: N=[2+3j, -78, 45, 34, -23, 36.75, 62+9j, 23.7, 69, 10.5]
Sample Output of the code should be:
45 34 69
SECTION D
31 Alpha Pvt Ltd is setting up the network in Chennai. There are four blocks- Block A, Block B, Block C &
Block D.
Distance between various blocks are as given Number of computers in each block are given
below: below:
i) Suggest the most suitable block to place the server with a suitable reason. 1
ii) Suggest the cable layout for connections between the various blocks. 1
iii) Suggest the placement of following devices: 1
(a) Switch/Hub (b) Repeater
iv) The organization is planning to link its front office situated in the city to a hilly region (30 KM away 1
from front office) where cable connection is not possible. Suggest an economic way to connect
with reasonably high speed.
1
OR
Text1="AISSCE,2023"
Text2=""
I=0
while I<len(Text1):
if Text1[I]>="0" and Text1[I]<="9":
Val = int(Text1[I])
b) The code given below Searches and displays the details of customers of a particular city, from the
table Customer. Customer table contains records of type:
CustNo – integer
CustName – string
CustCity – string
Mobile – char(10)
(i) State the difference between seek() and tell() functions of Python.
(ii) Write a Program in Python that defines and calls the following user defined functions:
(a) ADD() – To accept and add data of an patient to a CSV file ‘PATIENT_RECORD.CSV’. Each record
consists of a list with field elements as [PatientNo, PatientName, Age, Doctor] to store the patient
number, name of patient and the name of doctor who visited the patient, respectively.
SECTION E
34 Consider the table ITEMS 4
(1+1+2)
ItemNo ItemName SuppCode Quantity
2005 Notebook Classic 23
2003 Ball Pen 0.25 24 50
2002 Get Pen Premium 21 150
2006 Get Pen Classic 25 60
2001 Eraser Small 26 220
35 Alia has written a code and created a binary file [Link] with employeeid, ename and salary. 4
The file contains 10 records. She now has to update a record based on the employee id entered by
the user and update the salary. The updated record is then to be written in the file [Link].
The records which are not to be updated also have to be written to the file [Link]. If the
employee id is not found, an appropriate message should be displayed. As a Python expert, help her
to complete the following code based on the requirement given above:
import pickle
def update_data():
rec=[]
fin=open(____________________) #Statement 1
fout=open("[Link] ", "wb")
found=False
eid=int(input("Enter employee id to update their salary : "))
while True:
try:
rec=_______________#Statement 2
if rec["employeeid"]==eid:
found=True
rec["salary"]=int(input("Enter new salary :: "))
[Link](rec,fout)
else:
#Statement 3
except:
break
if : #Statement 4
For more information contact: 7355032293/[Link]@[Link] Page 115
print("The salary of employee id ",eid," has been updated.")
else:
print("No employee with such id is not found")
[Link]()
[Link]()
i) Write the correct statement to open the file [Link] to read the records of the
file. (Statement 1)
ii) Write the statement to read the data from the binary file [Link]. (Statement 2)
iii) Statement 3 to write the records which are not updated in the file [Link]. Write the
condition to check if the record updated (Statement 4).
Section A
1 Write full form of CSV. 1
2 Which is valid keyword? 1
a. Int b. WHILE [Link] [Link]
3 Which of the following is not a valid identifier name in Python? 1
a) 5Total b) _Radius c) pie d)While
4 Consider the following expression: 1
51+4-3**3//19-3
Which of the following will be the correct output if the expression is evaluated?
a. 50
b. 51
c. 52
d. 53
5 Select the correct output of the code: 1
Str=“Computer”
Str=Str[-4:]
print(Str*2)
a. uter
b. uterretu
c. uteruter
d. None of these
6 Which module is imported for working with CSV files in Python? 1
a. csv
b. python-csv connector
c. CSV
d. [Link]
7 Fill in the blank: 1
command is used to update records in the MySQL table.
(a) ALTER (b) UPDATE (c) MODIFY (d) SELECT
8 Which command used to fetch rows from the table in database? 1
(a) BRING (b) FETCH (c) GET (d) SELECT
def CALLME(n1=1,n2=2):
n1=n1*n2
n2+=2
print(n1,n2)
CALLME()
CALLME(3)
OR
mylist = [2,14,54,22,17]
tup =
tuple(mylist) for i
in tup:
print(i%3, end=",")
25 Answer the following : 2
i) Name the package imported for connecting Python with MySQL database.
ii) What is the purpose of cursor object?
OR
b. Write the Outputs of the MySQL queries (i) to (iv) based on the given above tables:
i. SELECT DISTINCT(CITY) FROM TRAINER WHERE SALARY>80000;
ii. SELECT TID, COUNT(*), MAX(FEES) FROM COURSE GROUP BY
TID HAVING COUNT(*)>1;
iii. SELECT [Link], [Link] FROM TRAINER T, COURSE C WHERE
[Link]=[Link] AND [Link]<10000;
iv. SELECT COUNT(CITY),CITY FROM TRAINER GROUP BY CITY;
27 Write a method/function COUNTLINES_ET() in python to read lines from a text file 3
[Link], and COUNT those lines which are starting either with „E‟ or starting
with
„T‟ and display the Total count separately.
For example:
If [Link] consists of
“ENTRY LEVEL OF PROGRAMMING CAN BE LEARNED FROM PYTHON. ALSO, IT
IS VERY FLEXIBLE LANGUGAE. THIS WILL BE USEFUL FOR VARIETY OF
USERS.”
Then, Output will be:
No. of Lines with E: 1
No. of Lines with T: 1
OR
Write a method/ function SHOW_TODO() in python to read contents from a text file
[Link] and display those lines which have occurrence of the word „„TO‟‟ or
„„DO‟‟.
For example :
If the content of the file is
“THIS IS IMPORTANT TO NOTE THAT
SUCCESS IS THE RESULT OF HARD WORK.
WE ALL ARE EXPECTED TO DO HARD WORK.
AFTER ALL EXPERIENCE COMES FROM HARDWORK.”
For more information contact: 7355032293/[Link]@[Link] Page 120
The method/function should display:
THIS IS IMPORTANT TO NOTE THAT
WE ALL ARE EXPECTED TO DO HARD WORK.
28 a. Write the outputs of the SQL queries (i) to (iv) based on the relations Teacher and 3
Posting given below:
OR
Section-D
31 Prithvi Training Institute is planning to set up its centre in Jaipur with four specialized 5
blocks for Medicine, Management, Law courses along with an Admission block in
separate buildings. The physical distances between these blocks and the number of
computers to be installed in these blocks are given below. You as a network expert have
to answer the queries raised by their board of directors as given in (i) to (v).
i. Suggest the most suitable location to install the main server of this
institution to get efficient connectivity.
ii. Suggest by drawing the best cable layout for effective network
connectivity of the blocks having server with all the other blocks.
iii. Suggest the devices to be installed in each of these buildings for
connecting computers installed within the building out of the following:
Modem, Switch, Gateway, Router
iv. Suggest the most suitable wired medium for efficiently connecting each
computer installed in every building out of the following network
cables:
Coaxial Cable, Ethernet Cable, Single Pair, Telephone Cable
v. Suggest the type of network implemented here.
def result(s):
n = len(s)
m=''
for i in range(0, n):
if (s[i] >= 'a' and s[i] <= 'm'):
m = m + s[i].upper()
elif (s[i] >= 'n' and s[i] <= 'z'):
m = m + s[i-1]
elif (s[i].isupper()):
m = m + s[i].lower()
else:
m = m + '#'
print(m)
result('Cricket')
Msg1="WeLcOME"
Msg2="GUeSTs"
Msg3=""
for I in range(0,len(Msg2)+1):
if Msg1[I]>="A" and Msg1[I]<="M":
Msg3=Msg3+Msg1[I]
elif Msg1[I]>="N" and
Msg1[I]<="Z":
Msg3=Msg3+Msg2[I]
else:
Msg3=Msg3+"*"
print(Msg3)
b) Your friend Jagdish is writing a code to fetch data from a database Shop and table
name Products using Python. He has written incomplete code. You have to help him
write complete code:
import as m # Statement-1
object1 = [Link](
host="localhost",
user="root",
password="root",
database="Shop"
)
object2 = object1_______# Statement-2
query = '''SELECT * FROM Products WHERE NAME LIKE "A%";'''
object2. (query) # Statement-3
[Link]()
34 ABC Gym has created a table TRAINER. Observe the table given below and answer the 1+1
following questions accordingly. +2
Section E
35 1+1
SECTION A
1. Fill in the Blank 1
The explicit conversion of an operand to a specific type is called (a)Type casting (b) coercion (c) translation
(d) None of these
2. Which of the following is not a core data type in Python? 1
(a)Lists (b) Dictionaries (c)Tuple (d) Class
3. What will the following code do? 1
dict={"Exam":"AISSCE", "Year":2022}
[Link]({"Year”:2023} )
SECTION B
19. Preety has written a code to add two numbers .Her code is having errors. Rewrite the correct code and 2
underline the corrections made.
def sum(arg1,arg2):
total=arg1+arg2;
print(”Total:”,total)
return total;
sum(10,20)
print(”Total:”,total)
20. Write two points of difference between Hub and Switch. 2
OR
Write two points of difference between Web PageL and Web site.
21. Write the output of following code and explain the difference between a*3 and (a,a,a) 2
a=(1,2,3)
print(a*3)
print(a,a,a)
22 Differentiate between DDL and DML with one Example each. 2
23 (a) Write the full forms of the following: 2
(i) SMTP (ii) PPP
(b) What is the use of TELNET?
24 What do you understand the default argument in function? Which function parameter must be given default 2
argument if it is used? Give example of function header to illustrate default argument
OR
Ravi a python programmer is working on a project, for some requirement, he has to define a function with
name CalculateInterest(), he defined it as:
118
119
CAMPUS
WEB
DESIGNING
Block Distance
App development to Web designing 28 m
App development to Movie editing 55 m
Web designing to Movie editing 32 m
Kashipur Campus to Mussoorie Campus 232 km
Number of computers
Block Number of Computers
App development 75
Web designing 50
Movie editing 80
(i) Suggest the most appropriate block/location to house the SERVER in the Kashipur campus (out of
the 3 blocks) to get the best and effective connectivity. Justify your answer. 1
(ii) Suggest a device/software to be installed in the Kashipur Campus to take care of data security. 1
(iii) Suggest the best wired medium and draw the cable layout (Block to Block) to economically connect 1
various blocks within the Kashipur Campus.
(iv) Suggest the placement of the following devices with appropriate reasons:
aSwitch / Hub 1
b Repeater
(v) Suggest a protocol that shall be needed to provide Video Conferencing solution between
1
Kashipur Campus and Mussoorie Campus.
(b)The code given below reads the following record from the table named studentand displays only
those records who have marks greater than 75:
RollNo – integer
Name – string
Clas – integer
Marks – integer
122
33. What is the advantage of using a csv file for permanent storage? Write a Program in Python that defines 5
and calls the following user defined functions:
(i) ADD() – To accept and add data of an employee to a CSV file ‘[Link]’. Each record consists of
a list with field elements as empid, name and mobile to store employee id, employee name and
employee salary respectively.
(ii) COUNTR() – To count the number of records present in the CSV file named
‘[Link]’. OR
Give any one point of difference between a binary file and a csv file. Write a Program in Python that defines
and calls the following user defined functions:
123
35. Anuj Kumar of class 12 is writing a program to create a CSV file “[Link]” which will contain user name and
password for some entries. He has written thefollowing code. As a programmer, help him to successfully
execute the giventask.
import______________# Line 1
def addCsvFile(UserName,PassWord): # to write / add data into the CSV file 4
f=open(' [Link]','________') # Line 2
newFileWriter = [Link](f)
[Link]([UserName,PassWord])
[Link]()
#csv file reading code
def readCsvFile(): # to read data from CSV file
with open(' [Link]','r') as newFile:
newFileReader = csv__________(newFile) # Line 3
for row in newFileReader:
print (row[0],row[1])
newFile_______________# Line 4
addCsvFile(“Arjun”,”123@456”)
addCsvFile(“Arunima”,”aru@nima”)
addCsvFile(“Frieda”,”myname@FRD”)
124
APPENDIX – 1
Keywords in Python
Precedence of Operators
( ) Parentheses Highest
** Exponentiation
~ x Bitwise nor , +x, -x Positive, Negative (Unary +, -)
*(multiply), / (divide), //(floor division), %(modulus)
+(addition), - (subtraction)
& Bitwise and
^ Bitwise XOR
| Bitwise OR
=, %=, /=, //=, -=, +=, *=, **= (Relational Operators)
125
APPENDIX – 2
Mathematical Functions
fabs() function
returns the absolute [Link](1.0) gives
value of num. 1.0.
fabs [Link](num)
Negative value is [Link](-1.0) gives -
converted to positive 1.0.
value.
126
log10() function
returns the base 10 math.log10(1.0) give
log10 math.log10(num) logarithm for num. base 10 logarithm for
Error occurs if num 1.0.
<=0.
degrees() converts
[Link](3.14)
degrees [Link](x) angle x from radians
would give 179.91.
to degrees.
radians() converts
[Link](179.91)
radians [Link](x) angle x from degrees
would give 3.14.
to radians.
[Link](4) gives
factorial [Link](arg) Returns factorial
24
Returns greatest
gcd [Link](x,y) [Link](8,6) gives 2
common divisor
127
APPENDIX – 3
Functions / Methods used with Strings
128
2
>>>[Link](“be”,7)
1
>>>[Link](“be”,7,11)
0
lower() It converts the string into lowercase >>>str=”My Favourite Food”
>>[Link]()
„my favourite food‟
islower() It returns True if all the letters in the >>>str=”my favourite food”
string are in lowercase. >>[Link]()
True
upper() It converts the string into uppercase >>>str=”My Favourite Food”
>>[Link]()
„MY FAVOURITE FOOD‟
isupper() It returns True if all the letters in the >>>str=”My Favourite Food”
string are in uppercase. >>[Link]()
False
lstrip() It returns the string after removing >>> “ Hello”.lstrip()
the space from the left of the string „Hello‟
rstrip() It returns the string after removing >>> “Hello ”.rstrip()
the space from the right of the string „Hello‟
strip() It returns the string after removing >>> “ Hello ”.strip()
the space from the both side of the „Hello‟
string
isspace() It returns True if the string contains str= “ “
only whitespace characters, str1= “”
otherwise returns False. >>>[Link]()
True
>>>[Link]()
False
swapcase() It converts uppercase letter to >>>"Hello World".swapcase()
lowercase and vice versa of the 'hELLO wORLD'
given string.
>>>"Hello
World".swapcase().swapcase()
'Hello World'
partition() Splits string at the first occurrence >>> Nm= “I Love India”
of argument sep and returns 3- tuple >>>[Link](„Lo‟)
containing the part before the ('I ', 'Lo', 've India')
separator , the separator itself
and the part after separator.
ord() It returns the ASCII/Unicode of the >>>ch= „A‟
character. >>>ord(ch)
65
chr() It returns the character represented >>>ch=65
by the imputed Unicode /ASCII >>>chr(ch)
number „A‟
129
startswith() Returns True if the string starts with >>> “abcd”.startswith(“cd”)
the substring ,otherwise returns False
False. >>> “abcd”.startswith(“ab”)
True
130
APPENDIX – 4
Functions / Methods used with Lists
131
>>>L2
[„u‟,‟i‟,‟d‟,‟b‟]
clear() It removes all the elements >>> L=[„u‟,‟b‟,‟i‟,‟d‟]
from the list. >>>[Link]()
>>>L
[]
count() It counts how many times an >>> L=[„u‟,‟b‟,‟i‟,‟d‟,‟b‟]
element has occurred in a list >>>[Link](„b‟)
and returns it. 2
pop() It removes the element from >>>L=[„u‟,‟b‟,‟i‟,‟d‟]
the end of the list or from the >>>ele=[Link]()
specified index and also >>>ele
returns it. „d‟
>>>L
[„u‟,‟b‟,‟i‟]
>>>ele=[Link](2)
>>>ele
„i‟
del Statement It removes the specified L=[10,20,30,40,50]
element from the list or entire del L[3]
list print(L)
[10, 20, 30, 50]
del L # removes entire list
remove() It is used when we know the >>> L=[„u‟,‟b‟,‟i‟,‟d‟]
element to be deleted, not the >>>[Link](„b‟)
index of the element. >>>L
[„u‟,‟i‟,‟d‟]
max() Returns the element with the >>> L=[10,20,30,40,50]
maximum value from the >>>max(L)
list. 50
min() Returns the element with the >>> L=[10,20,30,40,50]
minimum value from the >>>min(L)
list. 10
sum() Returns sum of elements in >>> L=[10,20,30,40,50]
the list. >>>sum(L)
150
132
APPENDIX – 5
Functions / Methods used with Tuples
133
APPENDIX – 6
Functions / Methods used with Strings
dict_items([('a', 'apple'),
('b', 'boy'), ('c', 'cat'),
('d', 'dog')])
keys( ) It returns a list of the key values mydict={'empno':1,'name':'Shivam','dept':'sales',
in a dictionary 'salary':25000}
print([Link]())
key=('Eno','Ename','Sal')
value=[1]
[Link](2)
d1=[Link](key,value)
print(d1)
{'Eno': [1, 2], 'Ename': [1, 2], 'Sal': [1, 2]}
clear( ) It removes all the elements from D={'a': 'apple', 'b': 'boy', 'c': „cat‟}
the Dictionary. [Link]()
print(D)
{}
135
APPENDIX – 7
Answer Key (Revision Tour)
1 Mark Questions
1. Ans. True
2. Ans. (a) continue
3. Ans. b) {'Exam': 'AISSCE', 'Year': 2023, 'Total': 500, 'Pass_Marks': 165}
4. Ans. False
5. Ans.(d) Python .s an .nterpreted language
6. Ans. Statement 4
7. Ans. ( c) 13.0
8. Ans. C) eval
9. Ans. [82, 5, 7]
10. Ans. C) **
11. Ans. b) T[2] = -51
12. Ans. dict={1: „Monday‟ ,2: „Tuesday‟ ,3: „Wednesday‟}
13. Ans. [Link]()
14. Ans. otPh
15. Ans. a. string
16. Ans. (i) keyword (ii) identifier
17. Ans. (i) math (ii) random
18. Ans. (i)
19. Ans. (a) infinite times
20. Ans. (iii) 100+200
21. Ans. (iii) error
22. Ans. (i) 27
23. Ans. (a) ,(b) , (e)
24. Ans. d) Boolean
25. Ans. (iii) remove( )
26. Ans. (a) n Pr gaug
27. Ans. (ii) True
28. Ans. a) [„h‟, „e‟, „l‟, „l‟, „o‟]
29. Ans. a) [12, 33, 22, 14]
30. Ans. b) [Link](2, 5)
31. Ans. [30, 40, 50, 20, 34, 55]
32. Ans. c) del d[“john”]
33. Ans. c) {1, “A”,2 “B”}
34. Ans. c) Keys can be List
35. Ans. b) 33
36. Ans. c) Error
37. Ans. a) 25
38. Ans. Rahul is playing
39. Ans. a) True
40. Ans. a) oses
41. Ans. a) ab12ef12
42. Ans. [[27, 56, 4]]
43. Ans. roPotP
44. Ans. 7
45. Ans.(1,2,3)
46. Ans. (10, 40, 30)
47. Ans. dict_keys(['empno', 'name', 'dept', 'salary'])
136
dict_values([1, 'Shivam', 'sales', 25000])
48. Ans. {1: 111, 2: 222, 3: 300, 4: 444, 5: 555}
49. Ans. {'Eno': [1, 2], 'Ename': [1, 2], 'Sal': [1, 2]}
50. Ans. {'Exam': 'AISSE', 'Year': 2023}
2 Marks Questions
1. Ans.
a) NIAIAEEB
b) dict_items([('Name', 'Rahul'), ('age', 45), ('address', 'Bhubaneswar')])
2. Ans.
{'ball': 1}
{'ball': 1, 'pen': 1}
{'ball': 2, 'pen': 1}
{'ball': 2, 'pen': 1, 'pencil': 1}
3. Ans.
[10]
[10, 11]
[10, 11, 12]
[10, 11, 12, 13]
4. Ans. GMAILbbCOM
5. Ans. Gnd**M
6. Ans. a) 7 b) True
7. (i) Ans 14 50 (ii) Ans. 12 7 10
8. Ans:
val = int(input("Value:"))
adder = 0
for C in range(1,val,3) :
adder+=C
if C
%2==0:
print (C*10)
else:
print (C)
print (adder)
9. Ans.
Val=25
for I in the range(0,Val) :
if I%2==0:
print( I+1)
else:
print (I‐ 1)
10. Ans.
17
{(1, 2, 4): 5, (4, 2, 1): 4, (1, 2): 8}
1 Mark Questions
1. (a) def
2. (b) def function_name( )
3. (b) 25
137
4. (d) No Output (Error)
138
5. (a) Function
6. (c) sum( )
7. (a) A function definition begins with “define”
8. (a) Parameter
9. (c) Both the statements are True
10. (b) 18
11. (c) def div(p1=4,p2,p3):
12. (b) Tuple
13. (b) Local Variable
14. (b) random
15. (d) 100
16. (c) 45
17. (a) A python standard library consists of a number of modules
18. (b) from math import sqrt
19. (c) Mumbai#Mumbai#Chennai#Mumbai#
20. (a) 3 5 5
3. Ans.
24
23
64
4. Ans.
50#5
5. Ans:
def display( ): #:
for Name in ["Ramesh","Suraj", "Priya"]: # inverted code and
: if Name [0] = "S": # indentation
print (Name) # small p in print()
6. Ans:
def execmain():
x = int(input("Enter a number:")) if
(abs(x)== x):
print("You entered a positive number")
else:
x*=-1
print("Number made positive : ",x)
execmain()
7. Ans:
The new string is:, pASs@2022
8. Ans:
def Tot(Number) : #Method to find Total #Error 1
139
Sum=0
for C in range (1, Number+1): #Error
2 Sum+=C
return Sum #Error 3
print(Tot(3)) #Function Call #Error 4
9. Ans:
l=[25,24,35,20,32,41]
s=0
for i in l:
if i%2!=0:
s+=i*2
print(s)
10. Ans:
def sepeven_odd(A):
even_sum=0
odd_sum=0
for i in A:
if i%2==0:
even_sum+=i
else:
odd_sum+=i
print("Even sum=",even_sum)
print("Odd sum=", odd_sum)
x=[34,12,67,33,79,6,23]
sepeven_odd(x)
11. Ans:
def OCCURRENCE(s,c):
count=0
for i in s:
if i==c:
count+=1
return count
x=input("Enter any string")
y=input("enter charater to find out frequency")
z=OCCURRENCE(x,y)
print(z)
12. Ans.
def b_search(A,x):
l=0
u=len(A)-1
while l<=u:
m=(l+u)//2
if
x==A[m]:
return True
elif x>A[m]:
l=m+1
else:
u=m-1
return False
140
A=[12,34,45,67,89,95,105]
141
x=int(input("Enter search value"))
if b_search(A,x):
print("Found")
else:
print("Not Found")
13. Ans:
P
YYYY
TTTTT
14. Ans:
S
SC
SCH
SCHO
SCHOO
SCHOOL
SCHOOLbb
SCHOOLbbbb
SCHOOLbbbbC
SCHOOLbbbbCO
SCHOOLbbbbCOM
15. Ans :
6000 * 0
6000 $ 30
600 * 0
6000 $ 600
120000 * 0
120000 $ 600
16. Ans:
def showlarge(s):
l = [Link]()
for x in l:
if len(x)>4:
print(x)
s=" My life is for serving my Country "
showlarge(s)
17. Ans :
Non-default argument follows default argument.
142
4. (a) [Link](n)
5. (b) [Link]( )
6. (c) pickle
7. (c) dump
8. (c) load( )
9. (d) The column names of the data 10.
(c) [Link](my_data, delimiter='\t')
2 / 3 Mark questions
1. Ans:
sr1 =[Link]() # to read first line of file str2 =
[Link](10) # to read next line of file
str3 = [Link]() # to read remaining lines of file
2. Ans:
count =0
f=open ("[Link]","r")
data=[Link]() # data will be list of string
print(data)
for line in data:
if line[-2] == 'a':
count=count+1
print("Number of lines having 'a' as last character is/are : " ,count) [Link]()
3. Ans:
def count():
f=open ("[Link]" ,"r")
count=0
x= [Link]() word
=[Link] () for i
in word:
if (len(i) == 4):
count =count + 1
print ("[Link] words having 4 characters is" ,count) [Link]()
4. Ans:
def count():
f=open ("[Link]" ,"r")
count=0
lines= [Link]() for
line in lines:
count+=1
if line[0] in [„g‟,‟G‟] :
print(count,line)
[Link]()
5. Ans:
F= open(“[Link]”,”r”) for
line in F:
words=[Link]( ) for
i in words:
for letter in i:
if([Link]( )):
print(letter)
143
6. Ans:
def remove_lowercase(infile, outfile):
output=file(outfile,”w”)
for line in file(infile):
if not line[0] in “abcdefghijklmnopqrstuvwxyz”:
[Link](line)
[Link]()
7. Ans:
d1=[Link](f2)
8. Ans:
[Link](dt,f1)
9. Ans:
a. import pickle
def
CreateFile():
f=open(“[Link]”,”ab”)
bookno=int(input(“Enter Book Number:”))
bookname=input(“Enter Book Name:”)
Author=input(“Enter Author Name:”)
Price=int(input(“Enter Book price:”))
Rec=[bookno,bookname,Author,Price]
[Link](rec,f)
[Link]()
CreateFile()
b. def countrec(Author):
f=open(“[Link]”,”rb”)
num=0
try:
while True:
rec=[Link](f)
if
Author==rec[2]:
num=num+1
print(rec[0],rec[1],rec[2],rec[3])
except:
[Link]()
return
num
n=countrec(“ABC”)
print(“total records”,n)
11. Ans:
import pickle
import os
def delrec(e):
num=0
f1=open(“[Link]”,”rb”)
f2=open(“[Link]”,”wb”)
try:
while True:
rec=[Link](f1)
if rec[0]==e:
print(“record found and deleted”)
e xcept:
144
else:
[Link]
mp(rec,f
[Link]() 2)
[Link]()
145
[Link](“[Link]”)
[Link](“[Link]”,”[Link]”)
12. Ans:
import csv
f=open(“[Link]”,”r”) // with open (“[Link]”,”r”) as f
d=[Link](f)
for row in d:
print(row)
[Link]()
14. Ans:
import csv
f=open("[Link]","r")
d=[Link](f)
next(f)
print(" recod of student whose score more then 70% marks")
for i in d:
try:
if int(i[3])>70:
print("roll no;",i[0])
print("name: ",i[1])
print("class :",i[2])
print("marks :",i[3])
except:
print()
[Link]()
15. Ans:
i) pickle
ii)fout=open("[Link]",”wb”)
iii) rec=[Link](fin)
iv) [Link](rec,fout)
146
2/3/4 Marks Questions
1. Ans:
cobol 7
['java', 'c++', 'python', 'basic', 'vb', 'vc++', 'php', 'c#']
['basic', 'c#', 'c++', 'java', 'php', 'python', 'vb', 'vc++'] 4
(i) Index 4 is out of range, because List1 contains 4 items (Index 0 to 3 only)
2. Ans (ii) String is immutable type so we can‟t change any character of string in place.
(i) [10,20,30,40,70]
3. Ans (ii) [10,20,30,40,70,100]
(iii) [10,20,30,40,70]
(iv) 70
4. Ans:
def sumAlternate(MYLIST):
sum=0
for i in range(0,len(MYLIST),2):
sum+=MYLIST[i]
print("Total = ",sum)
5. Ans
def EvenOdd(MYLIST):
for i in range(len(MYLIST)):
if MYLIST[i]%2==0:
MYLIST[i]//=2
else:
MYLIST[i]*=2
6. Ans:
(i) print(len(MYLIST))
(ii) print([Link](30))
(iii) import bisect
[Link](MYLIST,45)
print(MYLIST)
(iv) [Link](17)
print(MYLIST)
7. Ans
def Push(Employee):
name=input('Enter Employee name ')
[Link](name)
def Pop(Employee):
if len(Employee)==0: # or if Employee==[ ]:
print('Underflow')
else:
name = [Link]()
print('Popped Name was
',name)
8. Ans
def SwapMiddle(Codes):
i=0
147
mid = len(Codes)//2
while i<mid:
Codes[i],Codes[mid+i]=Codes[mid+i],Codes[i]
i+=1
9. Ans:
def Push(Package):
Empid=int(input(“Enter Id of Employee: "))
Ename=input(“Enter Name of employee”)
Salary= int(input(“Enter Salary of an
employee”)) T=(Empid, Ename ,Salary)
[Link](T)
def Pop(Package):
if (Package==[]):
print( "Stack empty")
else:
print ("Deleted element:",[Link]())
10. Ans
def selection_sort(DATA_LIST):
for i in range(0, len (DATA_LIST)):
min = i
for j in range(i + 1, len(DATA_LIST)):
if DATA_LIST[j] < DATA_LIST[min]:
min = j
# swapping
temp= DATA_LIST[min]
DATA_LIST[min] = DATA_LIST[i]
DATA_LIST [i]=temp
print(DATA_LIST)
DATA_LIST = [99 78 25 48 51 11]
print “LIST BEFOR SORTING”,DATA_LIST
selection_sort(DATA_LIST)
**********************************************************************************************
Exam preparation tips
THANK YOU.
148