XII_COMPUTER SCIENCE_MLL
XII_COMPUTER SCIENCE_MLL
AV
IN
ST
IT
U
CLASS: XII
W
&
T
BE
1 / 137
Flow of Control in Python
Python supports sequential flow of control.
Python supports branching flow of control using if, elif and else blocks.
Python supports iteration control using for loop and while loop.
Python if, elif and else blocks:
Python uses the relational and logical operators along with if and elif to create
D
conditional blocks that executes a set of python statements depending on the truth value
of the condition.
AV
The beginning of a block starts from the next line just after the : symbol and the block is
indented.
IN
if block
ST
elif block
block
IT
else block
U
Nested if block
block
S,
W
ES
With respect to the CBSE examination the students should thoroughly understand the construct
of if, elif, else and often a question comes where you need to identify the errors in each
program.
T
Q. Re-write the following program after removing errors, if any, and underline all the
BE
corrections made.
a = input("Enter a number:")
b = int(input("Enter a number:"))
N
if a = b:
G
a+b=a
else
AL
b=b+a
print(a,b)
Hint: There are four errors in the program
ZO
N
E
2 / 137
Python for loop:
Python for loop is used to iterate a set of python statements till a counter reaches its
limit.
D
AV
Python for loop can also be used to iterate over a collection object (List, tuple)/ iterable
(string, dictionary) using membership operators.
IN
ST
IT
Python while loop is used in situations where we have no idea as when the loop is going
U
starting from 0 by default, and increments by 1 (by default), and stops before a specified
number.
T
BE
range(1,11) 1 2 3 4 5 6 7 8 9 10
range(1,11,2) 13579
range(10,0,-1) 10 9 8 7 6 5 4 3 2 1
3 / 137
break statement in a loop: The break statement stops the loop iteration and exits from
the loop.
next iteration.
ST
else block in loop: The else block in a loop is executed when the break statement is not
O
Students are advised to go through the above content since various operations involving the
BE
python data structures, user defined functions, data file handling and database interaction will
require a thorough understanding of iteration. In CBSE examination you may not get a direct
question from this topic except for a few MCQ or Assertion-Reasoning based question.
N
Q. ASSERTION: In python loop else block will be executed if the loop successfully
terminates after complete iteration.
N
REASON: A python loop else block will not execute if a break statement is encountered
in a loop.
E
4 / 137
Python Strings
Python strings are a set of characters enclosed in single quotes, double quotes, or triple
quotes.
Python strings are immutable - Once a string is created, it cannot be changed. You can
create a new string with the desired modifications, but the original string remains
unchanged.
Python Strings are ordered: Strings maintain the order of characters in the sequence.
D
This means that the characters in a string have a definite order, and this order will not
change.
AV
Python Strings are iterable: You can iterate over the characters in a string using loops
like for loops or comprehensions.
Characters in a String are indexable: Each character in a string can be accessed using an
IN
index. Indexing starts from 0, so the first character of a string has an index of 0, the
second character has an index of 1, and so on.
ST
String examples:
IT
U
TI
an input() method
is a prompt
ES
String operations:
T
Concatenation: More than one string can be joined using the (+) operator to create a
BE
new string.
N
G
AL
5 / 137
Indexing: Each character of a string can be accessed using two types of indexing.
o Forward indexing: First character of a string has an index 0 and next has 1
and so on.
o Reverse indexing: Last character of the string is having an index of -1 and
last but one has -2 and so on.
D
AV
Slicing: A substring can be acquired from an existing string using the slicing
U
operation.
TI
Str[start:stop:step]
O
N
Stop is not
reached.
S,
W
ES
T
BE
Traversal: We can traverse a string using iteration and specifically using for loop.
o Iterate
N
using membership:
G
AL
ZO
6 / 137
String Methods: Python has a few built-in and string library methods (also built-in)
to manipulate strings. Some of them as elaborated below with examples.
o Global Methods: These methods accept string as a parameter –
methodName(string)
D
AV
IN
ST
digits
O
N
S,
7 / 137
islower() – Returns True if all the characters are lowercase alphabets
included since
the start index is
2
N
G
2 and stop is 10
N
8 / 137
and stop are optional.
D
included since
the start index is
2 and hence the
index value of the
IN
next M is 6
ST
The start is 7
IT
included.
TI
O
N
index(substr, start, stop) where stop index is not included. Both start
and stop are optional. This is same as index()
W
index(substr) find(substr)
ES
case.
AL
ZO
9 / 137
upper(): Converts all the lowercase alphabets in a string to upper case
D
10 / 137
Observe that all the A are removed because of the above method call
and since there is no character after the last A, an empty string is
introduced.
Questions:
Q.1 What will be the output of the following python statement?
s = "HOME ALONE"
p = s.split("O")
print(p[1][:2]+p[-1])
D
a) ALNE
AV
b) MENE
c) MEONE
d) MEAL
Q.2 What will be the output of the following python code?
IN
s="finaL eXam"
print(s.title())
ST
a) FinaL Exam
b) Final Exam
IT
c) FinaL exam
d) Error
U
b) 2
O
c) -1
d) Error
N
"MALAYALAM".partition("MA")
a) ("MA","LAYAL", "AM")
b) ("","MA","LAYALAM")
T
c) ("MA","LAYALA","AM")
BE
d) ("MALAYAL","AM","")
Q.6 Which of the following statements will generate an error?
st = "PYTHON"
N
t = st*5 Statement(1)
u = st[0] + "M" Statement(2)
G
st = st + st Statement(4)
a) Statement(1)
b) Statement(2)
ZO
c) Statement(3)
d) Statement(4)
Q.7 What will be the output of the following python statement?
N
s = "MONGO"
print(sorted(s))
E
a) "GMNOO"
b) ["GMNOO"]
c) ["G","M","N","O","O"]
d) Error
Q.8 What will be the output of the following string operations:
11 / 137
s="Python is osome good"
i) print(s.index('o',13,20))
ii) print(s[2:4]+s[14])
Python List
Ordered collection of objects - Lists maintain the order of elements as they are inserted.
Lists are mutable - Lists can be modified after creation. You can add, remove, or modify
D
elements freely.
AV
Heterogenous - Lists can contain elements of different data types. For example, a list can
contain integers, strings, floats, and even other lists.
Dynamic - Lists in Python can grow or shrink in size dynamically. You can append new
IN
Built-in Methods - Python lists come with built-in methods for various operations like
U
sorting, reversing, searching, etc., making them versatile for a wide range of tasks.
Iterable - Lists can be used in iterations using loops (e.g., for loop)
TI
Slicing - Lists support slicing operations, allowing you to extract sublists by specifying a
O
range of indices.
N
List Examples:
S,
W
ES
T
BE
N
G
Accepting a list from User: eval() method can be used along with input() method to acquire a
AL
List Operations: Like a String, python lists also support operations like Concatenation,
Replication, indexing, slicing and iteration. The only difference is that we can modify the
elements of a list using indexing, slicing and index-based iteration. In this study material we
shall see this component of python list that makes it unique mutable data structure.
Indexing of nested lists:
12 / 137
Changing list elements using indexing: We can change the elements of a list using indexing
and assignment operation.
D
AV
Changing the list elements using slicing: We can change the replace the contents of a
list using slicing too. Given below are some interesting examples.
IN
ST
Changing list elements using index-based iteration: We can modify the elements of a
W
Deleting elements of a list using del command: del command may be used to delete
N
one or more than one element of a list either using indexing or using slicing.
G
AL
ZO
N
E
13 / 137
List Methods: Python has a few built-in and list library methods (also built-in) to
manipulate lists. Some of them as elaborated below with examples:
o Global Methods: These methods accept string as a parameter –
D
AV
IN
ST
methodName(list)
o List member methods: These methods have the format
listName.methodName()
IT
clear() – Removes all the elements from a list and makes the list empty.
U
TI
O
N
copy() – Creates a copy of the existing list and both list occupy different memory
S,
locations.
W
ES
T
14 / 137
D
pop() – Removes and returns the last element from the existing list.
AV
IN
ST
pop(index) – Removes and returns the element from the given index.
IT
U
TI
remove(element): Removes the element from the given list without returning the
O
element.
T
BE
Note: Unlike count() in String there is only one parameter to count() in list.
N
index(element, start) – Returns the index of the first occurrence of the given
G
If the start index is not given, the index() returns the index of first occurrence
N
only.
sort() – Sorts the list in ascending order. Unlike sorted() this method sorts the
E
15 / 137
D
AV
IN
Questions:
O
a) print(data[3]+data[-1])
S,
print(data[-2][-2])
Q.2 What will be the output of the following python program:
data = [10,20,30, 60,70]
W
data[3:3]=[40,50]
print(data)
ES
data.pop(3)
print(data)
data.extend([10,20])
T
print(len(data))
BE
Q.3 Ganga is learning to use python Lists. Help her to get the answers of the following
operations based on the given list:
data = [10,20,30]
N
data[1:3]=[5,10]
print(data)
G
data.extend([3,4])
AL
x =data.count(10)
print(data[x:])
data.sort()
ZO
print(data)
print(data.pop(2))
Q.4 Write a python program that accepts a list of integers from user and creates a new list
N
from the existing list containing all the numbers that have three or more digits.
E
Eg: for existing list [10,100, 99,200,1000] the new list should be [100,200,1000]
Q.5 Write a python program that accepts a list of countries from user and prints all the
countries whose number of alphabets is more than 5.
Q.6 Write a python program that accepts a list of integers from user and prints all the
integers that have 8 as the last digit.
Eg: for the list [10, 28, 8, 86, 98] the program should print 28 8 98
16 / 137
Q.7 For the given list
d=[10,30,20,15,45,50,80,90]
what will be the output of the following slicing operation:
d[2:7:2]
a) [20,15,45] b) [20, 45, 80] c) [30, 15, 50] d) [20, 45]
D
AV
Python Dictionary
Python dictionaries are collection of key value pairs enclosed in {}
Python dictionaries are un-ordered.
IN
Dictionary Operations:
Displaying Values for a given Key: We can use dictName[key] to get the value.
T
BE
N
using the syntax dictName[key]=value. In case we are trying to add an existing key, then
AL
the latest value will replace the old value of the existing key without adding a new key-
value pair.
ZO
N
E
17 / 137
Dictionary Methods: Like Strings and lists, dictionaries too have global and member
functions.
o Global functions: The global functions include len(), max(), min(), sum() and
D
AV
IN
ST
sorted()
o Dictionary Member Methods: These methods are called using the syntax
IT
dictName.methodName()
clear() – Removes all the elements from the dictionary and makes it empty.
U
keys() – Returns a view object containing the keys of the dictionary, that can be
W
values() - Returns a view object containing the values of the dictionary, that can
be converted to list using a list() method.
N
G
AL
items() - Returns a view object containing the key-value pairs as tuples of the
dictionary, that can be converted to list of tuples using a list() method.
ZO
N
E
18 / 137
update() – Used to add the contents of one dictionary as key-value pairs in
another dictionary.
D
pop(key) – Removes a key-value pair from a dictionary and returns only the
AV
value.
IN
ST
popitem() – Reoves the last added key-value pair from the dictionary and returns
IT
setdefault(key, value) – Returns the value for the key if the key is in the
BE
19 / 137
Questions:
Q.1 Which of the following statements is False for a python dictionary?
a) Dictionary Keys can be created using another dictionary.
b) Dictionary values can be a dictionary.
c) Dictionary Values are mutable.
d) dict() function can be used to create a dictionary.
Q.2 What will be the output of the following program?
d={'A':10,'B':20,'C':30,'D':40}
D
del d['C']
AV
print(d)
x = d.popitem()
print(x)
Questions 3 is an ASSERTION AND REASONING based Questions. Mark the correct
IN
choice as:
i) Both A and R are true, and R is the correct explanation for A
ST
ii) Both A and R are true, and R is not the correct explanation for A
iii) A is True but R is False
IT
of key-value pairs.
REASONING: Dictionaries are un-ordered collection of key-value pairs.
TI
Q.5 Sapna wants to understand the concept of methods in a dictionary. Help her to find the
answers of the following operations on a python dictionary:
ES
x = d.pop('N')
BE
print(x)
print(list(d.keys()))
d.setdefault('X',60)
N
print(d)
Q.6 Write a python program that increases the values by 10 for the dictionary alphabets as
G
20 / 137
Python Tuples
Python tuples are a collection of objects enclosed in ().
Python tuples are immutable.
Python tuples are ordered.
Python tuples are indexed like lists and strings.
Python tuples may contain heterogenous elements.
Python tuples can be nested.
D
Tuple examples:
AV
IN
ST
IT
Tuple operations: Like string and lists tuples too have concatenations, replication, indexing,
slicing and iteration operation. We are not going to discuss them here since you can follow the
U
Tuple methods: Tuples have a few global methods and only two member methods.
O
o Global Methods – tuple(), min(), max(), len(), sum() and sorted(). We shall
discuss here only the sorted() method.
N
S,
W
ES
T
index(element) – Like lists tuple too returns the index of the first occurrence of
the element.
N
Python Functions
Python Function:- Functions is a block of code that is identified by its name. A function
ZO
can be executed by calling it. Writing the name of the function will call a function.
Functions are internally declared in a separate memory area. So a function can declare
N
variables with the same as declared in the outer part of the program.
E
Type of function :- Build in function ( all functions defined by python min() max() , lent()
etc, User-defined functions ( defined by the user )
Advantage of function :- (i) Reduces the size of the program (ii) improves reusability of
code
21 / 137
def keyword:- def keyword declares a user defined function followed by parameters
and terminated with a colon.
return keyword :- whenever the return keyword is executed inside a function it returns
the control back to its caller along with some value if passed explicitly. Writing return is
not compulsory and we can write as many return keywords as needed but only one return
keyword is executed.
Actual parameters :- When we call a function and pass some values to the function.
D
Formal parameters :- The parameters declared in the header part of the function is
called formal parameters or the values received by the functions from its caller is called
formal parameters.
IN
values are used if the caller does not provide value to that parameter. Remember default
parameters are written after not default parameters.
IT
def << name of the >> (formal parameters ) : function body is always writer in
tab indentation
U
code hare
TI
code here
O
out of scope of function. The function call can be placed after this part.
N
S,
Example :-
def myfunction(a,b,c=10) : a,b and c is formal parameter and c is with default values
W
print(a,b,c)
return (a+b+c)
ES
Q. Write a function findbig that take 2 integers as parameters and returns the largest
T
value.
def findbig(a,b):
BE
if a>b:
return a
N
else:
return b
G
x,y=5,10
bigvalue=findbig(x,y)
AL
Practice questions:
ZO
22 / 137
(iii) def fun2(list1):
for x in list1:
print(x.upper(),end=”#”)
fun2([‘Rajesh’,’Kumar’]) Ans:- RAJESH # KUMAR
(iv) def fun2(num1,num2):
for x in range(num1,num2):if
x%4==0:
print(x,end=’ ‘)
fun2(10,20) Ans:- 10 12 16 18
D
for x in email.split(“.”):
if x.isalpha():
print(“alphabet”)
IN
elif x.isdigit():
print(“digit”)
ST
elif x.isupper():
print(“upper”)
else:
IT
prog(“rajesh.123.yahoo”)
TI
Ans :- AlphabetDigit
Alphabet
O
if x != y:
return x+5
S,
else:
return y+10
W
print(check(10,5)) Ans :- 15
ES
T
BE
N
G
AL
ZO
N
E
23 / 137
D
AV
IN
ST
IT
Data Structure: A data structure is a group of data which can be processed as a single unit. This group of
TI
data may be of similar or dissimilar data types. Data Structures are very useful while programming because
they allow processing of the entire group of data as a single Unit.
O
Non-Linear data structures: The elements are not stored in sequential order.
Example: Graph, Tree, linked lists.
W
Stack: It is a data structure that allows adding and removing elements in a particular order. Every time an
element is added, it goes on the top of the stack; the only element that can be removed is the element that
ES
Operations possible in the data structure: Major operations are Traversal, Insertion, Deletion and
BE
Searching.
Major operations on Stack:
N
1. PUSH: The addition of elements is known as PUSH operation. It is done using the TOP position.
G
2. POP: Removal of elements is known as POP operation. Removal of object is always done from TOP
position.
AL
3. PEEK: To show/ display the element placed at TOP position in the stack. Few applications of stack:
1. Expression evaluation
2. Backtracking (game playing, finding paths, exhaustive searching).
ZO
3. Memory management, run-time environment for nested language features.Stack implementation using
List:
N
1. PUSH: The addition of elements is known as PUSH operation. It is done on the TOP position.
S= [ ‘element1’, ‘element2’, ‘element3’, ‘element4’]
E
24 / 137
S.pop() # removes element at top
S= [ ‘element1’, ‘element2’, ‘element3’, ‘element4’] #List after deletion
3. PEEK: To show/ display the element placed at TOP position in the stack.
return S[-1] # shows element at top but do not remove it from the stack.
Questions
1. Consider a list named Nums which contains random integers.
D
Write the following user defined functions in Python and perform the specified
AV
(ii) PopBig(): It pops the numbers from the stack, BigNums and displays
them. The function should also display “Stack Empty” when there are
ST
92765
31498
O
1297653
254923
N
10025
S,
Stack Empty
def PushBig(Nums,BigNums):
W
BigNums.append(N)
def PopBig(BigNums):
while BigNums:
T
print(BigNums.pop())
else:
BE
print(“Stack Empty”)
2. A list, NList contains following record as list elements:
[City, Country, distance from Delhi]
N
Each of these records are nested together to form a nested list. Write the
G
from Delhi.
(ii) Pop_element(): It pops the objects from the stack and displays
them. Also, the function should display “Stack Empty” when there
N
25 / 137
["Gangtok", "India", 1580],
["Columbo", "Sri Lanka", 3405]]
The stack should contain:
['Naypyidaw', 'Myanmar'],
['Dubai', 'UAE'],
['Columbo', 'Sri Lanka']
The output should be:
['Columbo', 'Sri Lanka']
['Dubai', 'UAE']
D
['Naypyidaw', 'Myanmar']
AV
Stack Empty
ANS
IN
ST
IT
U
TI
O
N
Write the following user-defined functions to perform given operations on the stack
named ' Hotel':
W
ii) Pop_Cust ()- To Pop the names of customers from the stack and display them.
Also, display "Underflow" when there are no customers in the stack.
For example: If the lists with customer details are as follows:
T
Siddharth
AL
Underflow
For example:
If the dictionary contains the following data:
E
26 / 137
a) customer=[["Siddarth", "Delux"], ["Rahul", "Standard"], ["Jerry", "Delux"]]
ANS hotel=[]
def push_cust():
for i in customer:
if i[1]=='Delux':
hotel.append(i[0])
return hotel
def pop_cust():
D
if hotel==[]:
AV
return "Underflow"
else:
return hotel.pop()
IN
push_cust()
ST
while True:
if hotel==[]:
print(pop_cust())
IT
break
else:
U
print(pop_cust())
TI
O
def push(vehicle):
S,
for i in vehicle:
if vehicle[i].lower()=='tata':
stk.append(i)
W
return stk
ES
push(Vehicle)
for i in range(-1,-len(stk)-1,-1):
T
print(stk[i])
BE
For example:
N
[“Gurdas”, “99999999999”,”Goa”]
[“Julee”, “8888888888”,”Mumbai”]
[“Murugan”,”77777777777”,”Cochin”]
[“Ashmit”, “1010101010”,”Goa”]
27 / 137
The stack should contain
[“Ashmit”,”1010101010”]
[“Gurdas”,”9999999999”]
ANS status=[]
AV
def Push_element(cust):
if cust[2]=="Goa":
L1=[cust[0],cust[1]]
IN
status.append(L1)
ST
dele=status.pop()
print(dele)
U
num=num-1
TI
else:
print("Stack Empty")
O
The function should push the names of those items in the stack who
S,
have price greater than 75. Also display the count of elements pushed
into the stack.
For example:
W
Notebook
Pen
BE
ANS stackItem=[]
G
def Push(SItem):
count=0
AL
for k in SItem:
if (SItem[k]>=75):
stackItem.append(k)
ZO
count=count+1
print("The count of elements in the stack is : ", count)
6. Julie has created a dictionary containing names and marks as key
N
28 / 137
● Pop and display the content of the stack.
For example:
If the sample content of the dictionary is as follows:
R={"OM":76, "JAI":45, "BOB":89, "ALI":65, "ANU":90, "TOM":82}
S.append(N)
AV
def POP(S):
if S!=[]:
return S.pop()
IN
else:
return None
ST
ST=[]
for k in R:
if R[k]>=75:
IT
PUSH(ST,k)
while True:
U
if ST!=[]:
TI
print(POP(ST),end=" ")
else:
O
break
7. Alam has a list containing 10 integers. You need to help him create a
N
For Example:
ES
38 22 98 56 34 12
ANS N=[12, 13, 34, 56, 21, 79, 98, 22, 35, 38]
def PUSH(S,N):
N
S.append(N)
G
def POP(S):
if S!=[]:
AL
return S.pop()
else:
return None
ZO
ST=[]
for k in N:
if k%2==0:
N
PUSH(ST,k)
E
while True:
if ST!=[]:
print(POP(ST),end=" ")
else:
break
29 / 137
TEXT FILE HANDLING
Key points:
Data File- A file is a sequence of bytes on the disk/permanent storage where a group of related data is
stored. File handling in Python enables us to create, update, read, and delete the files stored on the file
system through our python program.
Data File handling takes place in the following order.
D
1- Opening a file.
AV
2- Binary file
U
3- CSV file
TI
Text file: A text file is simply a sequence of ASCII or Unicode characters.A line is a sequence of
O
characters, stored on permanent storage. In a text file, each line is terminated by a special character, known
as End Of Line (EOL). Text file can be created using any text editor. Ex. Myfile.txt.
N
S,
Binary file: A binary file stores the data in the same way as stored in the memory. The .exe files, mp3 file,
image files, word documents are some of the examples of binary files. We can’t read a binary file using a
text editor.
W
CSV file: CSV (Comma Separated Values) is a file format for data storage which looks like a text file. The
ES
information is organized with one record on each line and each field is separated by comma
CSV File (Comma-
T
Character
ASCII, UTF-8 Not applicable ASCII, UTF-8
G
Encoding
Data is stored as lines of Data is stored as sequences Data is organized into rows
AL
Structure
text of binary bytes and columns
Suitable for storing textual Suitable for storing non- Ideal for storing structured
Usage
data textual data tabular data
ZO
Example File
.txt .jpg, .mp3, .exe .csv
Extensions
1. Opening a Text File
N
30 / 137
'r': Read mode. Opens a file for reading only. Raises an error if the file does not exist.
'r+': Read and Write mode. Opens a file for both reading and writing.
'w': Write mode. Opens a file for writing only. Creates a new file if it does not exist. Truncates the
file if it exists.
'w+': Write and Read mode. Opens a file for reading and writing. Creates a new file if it does not
exist. Truncates the file if it exists.
'a': Append mode. Opens a file for appending data. Creates a new file if it does not exist.
'a+': Append and Read mode. Opens a file for appending data and reading. Creates a new file if it
D
Syntax:
U
The write() function will write the content in the file without adding any extra characters.
file_name.write(content)
W
If the file is opened in write mode ('w' or 'w+'), it will overwrite existing content.
If the file is opened in append mode ('a' or 'a+'), new data will be added to the end of the file.
T
Use the read() method to read the entire contents of a file as a single string if value of n is not given
else it will read n characters from the current position.
File_object.read([n])
N
Use the readline() method to read a single line from the file.
G
File_object.readlines()
Note: ‘\n’ is treated as a special character of two bytes.
AL
Use the readlines() method to read all lines from the file into a list.
7. seek() and tell() Methods
ZO
seek() method is used to position the file object at a particular position in a file. The syntax of
seek() is:
N
file_object.seek(offset [, reference_point])
E
In the above syntax, offset is the number of bytes by which the file object is to be moved.
reference_point indicates the starting position of the file object. That is, with reference to which
position, the offset has to be counted. It can have any of the following values:
31 / 137
0 - beginning of the file
1 - current position of the file
2 - end of file
By default, the value of reference_point is 0, i.e. the offset is counted from the beginning of the file.
For example, the statement fileObject.seek(5,0) will position the file object at 5th byte position
from the beginning of the file.
D
tell() method returns the current file position. This function returns an integer that specifies the
AV
current position of the file object in the file. The position so specified is the byte position from the
beginning of the file till the current position of the file object. The syntax of using tell() is:
IN
file_object.tell()
Questions:
ST
a).txt b).dat
U
c).ppt d) .doc
2. Which files can be opened in human readable form? B
TI
a)write b)read
c)append d)None
S,
b)f=open(r”c:\data.txt”,”r”)
c)Both a and b
ES
d)None
5. Which of the following mode cannot be used for opening the text file? D
a)’r’ b)’w+’
T
c)’a’ d)’rb+’
6. Which is correct way of closing the text file? A
BE
a)f.close() b)close(f)
c) Both a and b d)None
N
7. Which statement is correct to read n bytes from text file using f as file A
object?
G
a)f.read(n) b)f.readline(n)
AL
a)readline() b)read()
c)readlines() d)readit()
9. What is the return datatype of read () function? A
N
a)string b)List
c)Tuple d)Dictionary
E
32 / 137
a)writegroup() b)write()
c)writechar() d)writeall()
12. Which function is used to write List of strings on to the text file? C
a)writelist() b)writeline()
c)writelines() d)writeall()
13. In which mode text file should be opened to add the data at the end to the C
text file?
a)’r’ b)’w’
c)’a’ d)’b’
D
14. Which of the following command can be used to open the text file in C
AV
15. hich of the following statements is true regarding the opening modes of a A
file?
ST
a) While opening a file for reading, if the file does not exist, an error
occurs.
b) While opening a file for writing ,if the file does not exist, an error
IT
occurs.
c) While opening a file for reading, if the file does not exist, a new file is
U
created.
TI
characters”
18. Assertion(A): File opened in’ w’ mode always places the cursor at the A
beginning of the file and never generates an error.
W
Reason(R): ‘w’ mode creates the file even if the file doesn’t exist.
ES
Reasoning(R): readlines() function is used to read all lines from the file
in the form of a List.
N
33 / 137
2 Mark questions
1. What is the difference between read() and readline() function of text files?
Ans The read() function read specified number of n bytes. If n is not specified, read the entire
file.
e.g. s=f.read(10) #read 10 bytes
s= f.read() # read the entire file
The readline() function read a single line. If n is specified , read n bytes from the file.
e.g. p=f.readline() # read single line
D
2. What is the difference between readlines() and readline() function used with the text file?
Ans The function readlines() read all the lines of the text file and store them as elements of the
IN
List.
e.g. s= f.readlines() # all lines of text file will be read and store in list s
ST
The function readline() will read a single line from the text file and if n is specified as the
argument, read n bytes from the file.
IT
3. Name the functions used to write data on the text files. Explain
Ans The two functions write() and writelines() are used to write data on the text files.
O
4. What is the difference between ‘w’ and ‘a’ mode used while opening a text file?
Ans When ‘w’ mode is used while opening the text file , it opens the file in write mode and
T
places the cursor at the beginning of the file and truncates the data of the file. And if file
doesn’t exist ,it creates the file.
BE
Whereas when ‘a’ mode is used while opening the file, it opens the file in append mode and
places the cursor at the end of the file for adding the data at the end. Here also file is created
N
5. What is the difference between ‘r+’ mode and ‘w+’ mode used while opening the text file?
Ans With both the modes reading and writing operations can take place, but difference is that if
AL
file is opened using ‘w+’ mode, file is created if file doesn’t exist, whereas if file is opened
using ‘r+’ mode, error is raised if file doesn’t exist.
6. If the focus.txt file contains the following text:
ZO
Mindfulness, cognitive training, and a healthy lifestyle may help sharpen your focus.
N
F=open(“focus.txt”,’r’)
S=F.read(11)
print(S)
F.close()
34 / 137
Mindfulness
Ans
7. Find the output of the following code:
F=open(“focus.txt”,’r’)
S= F.readline()
print(S)
T=F.readline()
D
print(T)
AV
F.close()
F=open(“focus.txt”,’r’)
IT
L= F.readlines()
for a in L:
U
print(a.upper())
TI
F.close()
O
F=open(“focus.txt”,’a+’)
S= “ sleep reduces stress hormones that can be harmful to the brain”
ES
F.write(S)
F.seek(0) # bring cursor to the beginning of the file
L=F.readlines()
T
print(L)
BE
F.close()
Ans ['Mindfulness, cognitive training, and a healthy lifestyle may help\n', 'sharpen your focus
N
F=open(“wish.txt”, ’w’)
F.write(“Day”)
ZO
F.close()
If the file contains “Good” before execution, what will be the contents of the file after
N
Ans After execution, file will contain “Day” only as previous data will be truncated by write
operation over the file.
35 / 137
3 Marks questions
1. Write a program to read text file story.txt and count number of lines starting with
letter ‘A’ or ‘a’.
Ans F=open("story.txt",'r')
count=0
L=F.readlines()
for i in L:
if i[0]=='A' or i[0]=='a':
D
count=count+1
AV
2. Write a program to read the file data.txt and count number of uppercase, lowercase
in it.
ST
Ans F=open("data.txt",'r')
u=0
IT
l=0
s=F.read()
U
for i in s:
TI
if i.isupper():
u=u+1
O
if i.islower():
l=l+1
N
Ans F=open("data.txt",'r')
ES
space=0
s=F.read()
for i in s:
T
if i.isspace():
BE
space=space+1
print("Number of spaces=",space)
F.close()
N
4. Write a program to read the file hash.txt and display the number characters up to
first #.
G
AL
Ans F=open("hash.txt",'r')
count=0
s=F.read()
ZO
for i in s:
if i!='#':
count=count+1
N
else:
E
break
print("Number of characters up till # =",count)
F.close()
5. Write a program to read the file alphabet.txt and display all the lines in uppercase.
36 / 137
Ans F=open("alphabet.txt",'r')
L=F.readlines()
for i in L:
print(i.upper())
F.close()
6. Write a program to read the file data.txt and count number of lines present in it.
Ans F=open("data.txt",'r')
L=F.readlines()
D
F.close()
7. Write a program to read the file data.txt and display only the digits present in it.
IN
Ans F=open("data.txt",'r')
s=F.read()
for letter in s:
ST
if letter.isdigit():
print(letter)
IT
F.close()
8. Write a program to read the file story.txt and display second last line of the file.
U
TI
Ans F=open("story.txt",'r')
L=F.readlines()
O
print(L[-2])
F.close()
N
9. Write a program to read the file article.txt and count occurrences of words “the” in
S,
the file.
Ans F=open("article.txt",'r')
W
count=0
s=F.read()
ES
L=s.split()
for word in L:
T
if word=="the":
count=count+1
BE
Ans F=open("story.txt",'r')
AL
s=F.read()
L=s.split()
for word in L:
ZO
if len(word)<=4:
print(word)
F.close()
N
E
4 Marks questions
37 / 137
1 Write python statements for opening the following files. Also, write the Python
statements to open the following files:
a) a text file “example.txt” in both read and write mode
b) a text file “bfile.dat” in write mode
c) a text file “try.txt” in append and read mode
d) a text file “btry.dat” in read only mode.
P.read(10)
b) with open(“practice.txt”, “r”) as P:
ST
x = P.read()
IT
Set of statements (a) would read the file “practice.txt” and returns a string that
Ans contains first 10 characters of the text file.
U
Set of statements (b) will read the text file “practice.txt” and returns a string that
contains entire contents of the text file.
TI
(ii) Write a command(s) to write the following lines to the text file named hello.txt.
O
L = [“ Welcome my class” , “It is a fun place” , “You will learn and play”]
F.writelines(L)
ES
F.close()
3 Write a method/function COUNTLINES_ET() in python to read lines from a text
file REPORT.TXT, and COUNT those lines which are starting either with ‘E’ and
T
d=f.readlines()
le=0
G
lt=0
AL
for i in d:
if i[0]==’E:
le=le+1
ZO
elif i[0]==’T’:
lt=lt+1
print(“no of line start with”,le)
N
4 Write a function filter(oldfile, newfile) that copies all the lines of a text file
“source.txt” onto “target.txt” except those lines which starts with “@” sign.
38 / 137
f2 = open(“newfile”,”w”)
while True:
text= f1.readline()
if len(text) ==0:
break
if text[0] == ‘@’:
continue
f2.write(text)
f1.close()
D
f2.close()
AV
5 (i) Write a user defined function countwords() to display the total number of words
present in the file from a text file “Quotes.Txt”.
s = open("Quotes.txt","r")
f = s.read()
ST
z = f.split ()
print ("Total number of words:", len(z))
IT
(ii) Write a function COUNT_AND( ) in Python to read the text file “STORY.TXT”
and count the number of times “AND” occurs in the file. (include AND/and/And in
U
the counting)
TI
count=0
file=open(‘STORY.TXT','r')
N
line = file.read()
S,
word = line.split()
for w in word:
if w.upper() ==’AND’:
W
count=count+1
print(count)
ES
file.close()
T
5 Marks questions
1 (i) Differentiate between Text files and Binary files.
BE
Ans Text file: A text file is simply a sequence of ASCII or Unicode characters.A line is a
sequence of characters, stored on permanent storage. In a text file, each line is
N
terminated by a special character, known as End Of Line (EOL). Text file can be
created using any text editor. Ex. Myfile.txt.
G
Binary file: A binary file stores the data in the same way as stored in the memory.
AL
The .exe files, mp3 file, image files, word documents are some of the examples of
binary files. We can’t read a binary file using a text editor.
(ii) Write a method COUNTWORDS() in Python to read data from text file
ZO
‘ARTICLE.TXT’ and display the count of words which ends with a vowel.
For example, if the file content is as follows:
N
39 / 137
words = data.split()
count = 0
for w in words:
if w[-1] in 'aeiouAEIOU':
count += 1
fil.close()
print('Total words which ends with vowel =',count)
2 (i) Explain seek() and tell() methods.
Ans seek() method is used to position the file object at a particular position in a file.
D
file_object.seek(offset [, reference_point])
For example, the statement fileObject.seek(5,0) will position the file object at 5th
byte position from the beginning of the file.
tell() method returns the current file position. This function returns an integer that
IN
specifies the current position of the file object in the file. The position so specified
is the byte position from the beginning of the file till the current position of the file
ST
(ii) Write a function COUNT() in Python to read from a text file ‘rhym.txt' and display
U
To enjoy
N
Line 2 : 4
Line 3 : 2
W
fil = open('rhym.txt')
lines = fil.readlines()
c=1
T
for l in lines:
words = l.split()
BE
print('Line',c,':',len(words))
c = c+1
N
fil.close()
3 (i) Differentiate between w+ and a+ file modes.
G
Ans
AL
40 / 137
Creates a new file if it does not
Creates a new file if it
Creation
exist. does not exist.
Useful for scenarios
Useful for scenarios where
where data needs to be
existing content needs to be
Usage appended to an existing
overwritten or a new file needs
file without losing the
to be created.
existing content.
(ii) Write a function WE_WORDS() in Python to read from a text file ‘TEXT.TXT’ and
display the count of words which starts with ‘WE’.
D
data = fil.read()
words = data.split()
IT
count = 0
for w in words:
U
if w.startswith('WE'):
TI
count = count + 1
print('TOTAL WORDS STARTING WITH WE=',count)
O
fil.close()
4 (i) What will be the return datatype of the following methods:
N
read()
S,
readlines()
readlines() – List
(ii) A pre-existing text file data.txt has some words written in it. Write a python
ES
function displaywords() that will print all the words that are having length greater
than 3.
T
Example:
For the fie content:
BE
s = f.read()
lst = s.split() for x in lst:
if len(x)>3:
ZO
Ans seek() method is used to position the file object at a particular position in a file.
The syntax of seek() is:
file_object.seek(offset [, reference_point])
In the above syntax, offset is the number of bytes by which the file object is to be
moved. reference_point indicates the starting position of the file object. That is,
41 / 137
with reference to which position, the offset has to be counted. It can have any of the
following values:
0 - beginning of the file
1 - current position of the file
2 - end of file
By default, the value of reference_point is 0, i.e. the offset is counted from the
beginning of the file.
(ii) A pre-existing text file info.txt has some text written in it. Write a python function
D
countvowel() that reads the contents of the file and counts the occurrence of
AV
s = f.read()
count = 0
ST
for x in s:
if x in 'AEIOU':
IT
count+=1
print(count) f.close()
U
TI
O
N
S,
W
ES
Binary files store data in the binary format (that is, in the form of 0’s and 1’s) which is understandable by
N
the machine. So when we open the binary file in our machine, it decodes the data and displays it in a
human-readable format. It is important to note that the binary file contents can be displayed correctly using
G
only specialized applications that can read binary data. If we open any binary file using a normal text
AL
relate now, these files can be opened correctly using specific applications only, that are different for each
file extension. Try opening any of these binary files using notepad, and observe the magic (file opens but
with unreadable contents). In this chapter of binary file handling, we'll learn to create such files (in their
N
simple forms), modify its contents and display its contents properly.
E
42 / 137
File mode governs the type of operations (read/write/append) that is possible in the opened file. It refers to
how the file will be used once it's opened.
ab: Append: Opens file in write mode. If a file exists, data will be appended at the end.
rb+: Read and Write: File should exist, Both read and write operations can be performed.
IN
wb+: Write and Read: File created if it does not exist, If file exists, file is truncated.
ST
ab+: Write and Read: File created if does not exist, If file exists data is truncated.
IT
Pickle is a special python package (module) that is used to generate data in binary format. Pickle comes
TI
with few methods like load() and dump( ) to read and write data in binary format.
O
N
Pickle Module: Python Pickle is used to serialize and deserialize a python object structure. Any object on
python can be pickled so that it can be saved on disk.
S,
W
Pickling: Pickling is the process whereby a Python object hierarchy is converted into a byte stream.
ES
To use the picking methods in a program, we have to import the pickle module using import keyword.
N
Example:
G
AL
In this module, we shall discuss two of its useful functions, which are:
i. dump( ) : To store/write the object data to the file.
N
ii. load( ) : To read the object data from a file and return the object data.
E
Syntax:
Write the object to the file:
43 / 137
pickle.dump(List_name, file-object ) #To write a list object into a binary file
Example:
D
AV
import pickle
IN
if(choice=='n'):
S,
break
file = open("student.dat","wb")#open file in binary & write mode
W
file.close( )
T
OUTPUT:
BE
To read the data from a binary file, we have to use the load( ) function of the pickle module.
44 / 137
Example:
import pickle
file = open("student.dat", "rb")
list = pickle.load(file)
print(list)
D
AV
file.close( )
IN
OUTPUT:
[{'roll': '1201', 'name': 'Anil'}, {'roll': '1202', 'name': 'Sunil'}]
ST
IT
Locate the record to be updated by searching for it. Make changes in the loaded record in memory. Write
back onto the file at the exact location of the record.
TI
O
import pickle
N
roll = input('Enter roll number whose name you want to update in binary file :')
S,
list = pickle.load(file)
ES
found = 0
lst = [ ]
T
for x in list:
BE
if roll in x['roll']:
found = 1
N
G
lst.append(x)
if found == 1:
ZO
file.seek(0)
pickle.dump(lst, file)
N
print("Record Updated")
E
else:
print('roll number does not exist')
file.close( )
45 / 137
OUTPUT:
Enter roll number whose name you want to update in binary file :1202
Enter new name: Harish
Record Updated
D
AV
import pickle
roll = input('Enter roll number whose record you want to delete:')
ST
list = pickle.load(file)
U
found = 0
TI
lst = []
O
for x in list:
N
lst.append(x)
else:
W
found = 1
ES
if found == 1:
T
file.seek(0)
pickle.dump(lst, file)
BE
else:
G
file.close( )
ZO
OUTPUT:
Enter roll number whose record you want to delete:1201
N
Record Deleted
E
46 / 137
import pickle
roll = input('Enter roll number that you want to search in binary file :')
file = open("student.dat", "rb")
list = pickle.load(file)
file.close( )
D
AV
for x in list:
if roll in x['roll']:
IN
else:
IT
OUTPUT:
O
Enter roll number that you want to search in binary file :1202
N
Example:
BE
fout=open("story.txt","w")
N
fout.write("Welcome Python")
G
print(fout.tell( ))
AL
fout.close( )
ZO
Output:
15
N
E
seek(offset, reference_point): Change the cursor position by bytes as specified by the offset, from the
reference point.
47 / 137
Example:
fout=open("story.txt","w")
fout.write("Welcome Python")
fout.seek(5)
print(fout.tell( ))
fout.close( )
D
AV
Output:
IN
5
ST
1 Mark Questions
IT
U
1. The process of converting byte stream back to the original structure is known as
TI
a. rb b. rw c. r d. w
W
a. Easy for carrying data into buffer b. Much faster than other file systems
T
c. Characters translation is not required d. Every line ends with new line character ‘\n’
BE
5. Which of the following file mode opens a file for append or read a binary file and moves the files
pointer at the end of the file if the file already exist otherwise create a new file?
ZO
a. a b. ab c. ab+ d. a+
N
6. Which of the following file mode opens a file for reading and writing both as well as overwrite the
E
48 / 137
7. Mr Sharma is working on a binary file and wants to write data from a list to a binary file. Consider list
object as l1, binary file sharma_list.dat, and file object as f. Which of the following can be the correct
statement for him?
a. f = open(‘sum_list’,’wb’); pickle.dump(l1,f)
b. f = open(‘sum_list’,’rb’); l1=pickle.dump(f)
c. f = open(‘sum_list’,’wb’); pickle.load(l1,f)
D
d. f = open(‘sum_list’,’rb’); l1=pickle.load(f)
AV
8. Every file has its own identity associated with it. This is known as:
IN
10. Which of the following file types allows you to store large data files in the computer memory?
O
2 Marks Questions
ES
1. Write a program in python to write and read structure, dictionary to the binary file.
T
BE
2. BINARY file is unreadable and open and close through a function only so what are the advantages of
using binary file
N
G
3. Write a statement to open a binary file name sample.dat in read mode and the file sample.dat is placed in
AL
4. When do you think text files should be preferred over binary files?
N
5. Consider a binary file employee.dat containing details such as empno:ename:salary (separator ':') write a
E
python function to display details of those employees who are earning between 20000 and 30000(both
values inclusive)
49 / 137
6. Differentiate between pickle.load() and pickle.dump() methods with suitable examples.
7. A binary file “Book.dat” has structure [BookNo, Book_Name, Author, Price].Write a user defined
function CreateFile() to input data for a record and add to Book.dat
8. A binary file “STUDENT.DAT” has structure (admission_number, Name, Percentage). Write a function
D
countrec() in Python that would read contents of the file “STUDENT.DAT” and display the details of those
AV
9. A binary file “Store.dat” has structure [ItemNo, Item_Name, Company, Price]. Write a function
CountRec(Company) in Python which accepts the Company name as parameter and count and return
ST
number of Items by the given Company are stored in the binary file “Store.dat”.
IT
10. A binary file “Store.dat” has structure [ItemNo, Item_Name, Company, Price]. Write a function
U
AddRecord() which accepts a List of the record [ItemNo, Item_Name, Company, Price] and appends in the
binary file “Store.Dat”.
TI
O
3 Marks Questions
N
S,
i. Write a user defined function CreateFile() to input data for a record and add to “Book.dat” .
ES
ii. Write a function CountRec(Author) in Python which accepts the Author name as parameter and count
and return number of books by the given Author are stored in the binary file “Book.dat”
T
BE
ii) Write a function Disp_Rec(alphabet) in Python that would read contents of the file “SCHOOL.DAT”
AL
and display the details of those students whose name begins with the alphabet as passed as parameter to the
function.
ZO
3. A binary file “STOCK.DAT” has structure [ITEMID, ITEMNAME, QUANTITY, PRICE]. Write a user
defined function MakeFile( )to input data for a record and add to Book.dat.
N
E
4. Write a function GetPrice(ITEMID) in Python which accepts the ITEMID as parameter and returns
PRICE of the Item stored in Binary file STOCK.DAT.
50 / 137
5. A binary file “EMPLOYEE.DAT” has structure (EMPID, EMPNAME, SALARY). Write a function
CountRec( ) in Python that would read contents of the file “EMPLOYEE.DAT” and display the details of
those Employees whose Salary is above 20000.
6. A binary file “EMPLOYEE.DAT” has structure (EMPID, EMPNAME, SALARY). Write a function to
display number of employees having Salary more than 20000.
D
AV
7. A binary file named “EMP.dat” has some records of the structure [EmpNo, EName, Post, Salary], Write
a user-defined function named NewEmp() to input the details of a new employee from the user and store it
in EMP.dat.
IN
ST
8. Write a user-defined function named SumSalary(Post) that will accept an argument the post of
employees & read the contents of EMP.dat and calculate the SUM of salary of all employees of that Post.
IT
U
9. A binary file named “TEST.dat” has some records of the structure [TestId, Subject, MaxMarks,
ScoredMarks] Write a function in Python named DisplayAvgMarks(Sub) that will accept a subject as an
TI
10. Write a python program to search and display the record of the student from a binary file “Student.dat”
S,
containing students records (Rollno, Name and Marks). Roll number of the student to be searched will be
entered by the user.
W
5 Marks Questions
ES
ii. Write a function searchRollNo(r) in Python which accepts the student’s rollno as parameter and searches
BE
the record in the file “student.dat” and shows the details of student i.e. rollno, name and marks (if found)
otherwise shows the message as ‘No record found’.
N
G
2. Write a python program to create binary file dvd.dat and write 10 records in it:
AL
51 / 137
CSV FILES
A CSV (Comma-Separated Values) file is a plain text file format used to store tabular data, where each
line represents a row, and each value within a row is separated by a comma or other delimiter.
A CSV file (Comma Separated Values file) is a type of plain text file that uses specific structuring to
arrange tabular data.,
CSV File operations in Python Files in the CSV format can be imported to and exported from programs
D
But the problem arises as to how to handle and organize this large unstructured data?
ST
Thus, CSV organizes data into a structured form and, hence, the proper and systematic organization of this
large amount of data is done by CSV.
U
Since CSV file formats are of plain text format, it makes it very easy for website developers to create
TI
• The several advantages that are offered by CSV files are as follows:
N
– CSV is processed by almost all existing applications CSV stands for “comma separated values”.
Each line in a file is known as data/record. Each record consists of one or more fields, separated by
BE
commas (also known as delimiters), i.e., each of the records is also a part of this file. Tabular data is stored
as text in a CSV file. The use of comma as a field separator is the source of the name for this file format. It
N
• For working with CSV files in Python, there is an inbuilt module called CSV.
It is used to read and write tabular data in CSV format.
ZO
• To perform read and write operations with CSV file, we must import CSV module.
CSV module can handle CSV files correctly regardless of the operating system on which the files were
N
created.
E
• Along with this module, open() function is used to open a CSV file and return file object. We load the
module in the usual way using import:–
1)import csv
52 / 137
• Like other files (text and binary) in Python, there are two basic operations that can be carried out on a
CSV file:
– 1. Reading from a CSV file
– 2. Writing to a CSV file
2) Opening and closing of CSV File
# Open the CSV file in write mode
D
The CSV file is opened as a text file with Python’s built-in open()function, which returns a file object.
TI
This creates a special type of object to access the CSV file (reader object), using the reader() function.
O
•The reader object is an iterable that gives us access to each line of the CSV file as a list of fields. We can
N
also use next() directly on it to read the next line of the CSV file, or we can treat it like a list in a for loop
S,
• Let us enter the student details in spreadsheet and save this file as shown.
ES
• Next step is to open the Notepad and enter the data for student.csv, which will be the equivalent for
T
BE
N
G
AL
ZO
N
E
student.xls.
53 / 137
In student.csv (notepad) file, the first line is the header and remaining lines are the data/ records. The
fields are separated by comma. In general, the separator character is called a delimiter, and the comma is
D
AV
IN
not the only one used. Other popular delimiters include the tab (\t), colon (:) and semi-colon (;) characters.
ST
Every record is stored in reader object in the form of a List. We first open the CSV file in READ mode.
U
The file object is named f. The file object is converted to csv.reader object. The reader object is used to
TI
read records as lists from a csv file. Iterate through all the rows using a for loop. row is nothing but a list
O
STEPS:
Writer Objects:
AL
csvwriter.writerow(row)
Write the row parameter to the writer’s file object
ZO
csvwriter.writerows(rows)
Example code to demonstrate use of writer objects:
N
import csv
E
54 / 137
# Writing data using writerow()
with open('students.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(data_single_row) # Write a single row
writer.writerow(['David', 23, 'B']) # Write another single row
# Writing data using writerows()
D
with open('students.csv', 'a', newline='') as file: # Use 'a' to append to the existing file
AV
writer = csv.writer(file)
writer.writerows(data_multiple_rows) # Write multiple rows at once
We first define the data to be written to the CSV file as a list of lists (data).
IN
Using writerow(), we write each row of data to the CSV file one by one.
ST
Then, using writerows(), we append additional rows of data to the CSV file at once.
PRACTICE QUESTIONS
IT
MCQ
U
A) csv
O
B) pandas
C) json
N
D) os
S,
3. To open a CSV file for writing, which mode should you use in the open() function?
BE
A) 'r'
B) 'w'
N
C) 'a'
G
D) 'rb'
AL
4. Which method is used to write a single row into a CSV file using the csv.writer() object?
A) write()
ZO
B) writerows()
C) writerow()
N
D) row()
E
5. How do you close a CSV file after you finish working with it in Python?
A) close_file()
B) close()
55 / 137
C) end()
D) stop()
6. Which method is used to write multiple rows into a CSV file using the csv.writer() object?
A) write()
B) writerows()
C) writerow()
D
D) row()
AV
7. What parameter should be used in the open() function to ensure correct newline handling when
working with CSV files?
A) newline='ignore'
IN
B) newline=''
ST
C) newline='skip'
D) newline=None
IT
8. To read data from a CSV file in Python, which method of the csv.reader() object is used to iterate
U
A) readline()
O
B) next()
C) readrows()
N
D) for loop
S,
9. What does the newline='' parameter in the open() function ensure when working with CSV files?
W
10. Which of the following is NOT a valid mode for opening a CSV file in Python?
BE
B) Text-based
C) Image
N
D) Executable
E
12. Which method is used to read the entire contents of a CSV file into a list of lists using the
csv.reader() object?
A) read()
56 / 137
B) readline()
C) next()
D) list()
13.When using the csv.writer() object, which method is used to write a list of data into a CSV file as a
single row?
A) write()
D
B) writerow()
AV
C) writeall()
D) row()
14,In Python's CSV module, which of the following is true about delimiter characters?
IN
15. How does the csv.writerows() method differ from the csv.writerow() method?
TI
B) writerows() writes multiple rows at once, while writerow() writes one row at a time.
C) writerows() converts data to CSV format, while writerow() writes data as-is.
N
16.Which of the following is a benefit of using the csv module in Python for CSV file operations?
W
17.What does the newline='' parameter in the open() function prevent when writing to CSV files?
BE
18. When using the csv.reader() object to read from a CSV file, what type of data structure is each row
of data represented as?
ZO
A) String
B) Dictionary
N
C) List
E
D) Tuple
19. How does the csv.DictReader() class differ from the csv.reader() class in Python?
A) DictReader() reads data as lists, while reader() reads data as dictionaries.
57 / 137
B) DictReader() reads data with column headers, while reader() does not.
C) DictReader() reads data as tuples, while reader() reads data as dictionaries.
D) DictReader() reads data as dictionaries, while reader() reads data as lists.
20. What is the purpose of using the newline='' parameter when opening a CSV file in Python?
A) To convert newlines to spaces.
B) To ensure cross-platform compatibility for newline characters.
D
2. Discuss the importance of newline handling when working with CSV files.
ST
6. Write a Python code snippet to open a CSV file named "data.csv" in write mode and write a single
TI
row of data into it using the csv.writer() object.Include the necessary import statement and ensure
O
object and prints each row of data to the console.Handle any exceptions that may occur during file
S,
handling.
W
8. Write a Python program that generates a CSV file named "output.csv" and writes multiple rows of
data into it using the csv.writer() object.The data can be generated randomly or from predefined
ES
lists.
9. Modify the previous code to append additional rows of data to the "output.csv" file using the
T
csv.writer() object.
BE
10.Implement a Python function that takes a CSV file path as input and returns the total number of
rows in the CSV file using the csv.reader() object.
N
3 marks questions
G
AL
Finally, prints the list low_stock_items containing the names of items with low stock.
58 / 137
2. Fill in the blanks in the following code snippet to open a CSV file named "sales.csv" in read mode
using the csv.reader() object and calculate the total revenue by summing up the values in the third
column (Price) of each row.
import csv
total_revenue = 0 with open('sales.csv', 'r') as file:
reader = csv.reader(file) next(reader) # Skip header row
D
total_revenue += _______
print('Total revenue:', total_revenue)
3. Given the CSV file "employees.csv":
IN
Identify and correct any errors in the following Python code snippet, then determine the output of the
corrected code:
IT
import csv
U
total_salary = 0
TI
reader = csv.reader(file)
for row in reader:
N
total_salary += row[2]
S,
4. Write a Python program that opens a CSV file named "students.csv" in write mode using the
csv.writer() object. The program should prompt the user to enter student names and their respective
ES
grades, and then write this data into the CSV file. Ensure appropriate error handling for incorrect
input.
T
5. Explain the concept of delimiter characters in CSV files and discuss their significance when
BE
working with the csv module in Python. Provide examples of different delimiter characters and
explain how they affect the organization and interpretation of data within a CSV file.
N
6. Write a Python program that reads data from a CSV file named "data.csv" using the csv.reader()
G
object. For each row, if the value in the second column (index 1) is greater than 50, write that row
AL
into a new CSV file named "high_scores.csv" using the csv.writer() object.
7. Fill in the blanks in the following code snippet to open a CSV file named "output.csv" in append
ZO
mode and add a new row containing the student's name, age, and grade using the csv.writer()
object.
N
import csv
E
59 / 137
writer._____(student_data)
Output and Error Handling:
8. Given the following CSV file named "inventory.csv":
What will be the output of the following Python program? If there is any error, identify and correct it.
total_cost = 0
with open('inventory.csv', 'r') as file:
D
reader = csv.reader(file)
AV
price = float(row[2])
ST
9. Write a Python program that reads data from a CSV file named "students.csv" using the csv.reader()
U
object. Create a dictionary where the keys are the student names and the values are lists containing
TI
10. Fill in the blanks in the following code snippet to read data from a CSV file named "sales.csv"
using the csv.reader() object and calculate the total sales amount. Print the total sales amount.
N
import csv
S,
total_sales = 0
W
sales_amount = float(_____[2])
BE
total_sales += sales_amount
print('Total sales amount:', total_sales)
N
5 mark questions
G
AL
1. Write a Python program that reads data from a CSV file named "inventory.csv" using the
csv.DictReader() class. The CSV file contains columns for "Product", "Quantity", and "Price".
ZO
Your program should calculate the total value of each product in inventory (quantity * price) and
print a summary report showing each product's name and total value.
N
2. Identify and correct the error in the following Python code that attempts to open a CSV file named
E
60 / 137
with open('data.csv', 'r') as file:
writer = csv.writer(file) writer.writerows(data)
3. Fill in the blanks in the following code snippet to open a CSV file named "output.csv" in write
mode and write multiple rows of data into it using the csv.writer() object. The data to be written
includes product information (name, quantity, price) stored in a list of dictionaries.
import csv
D
product_data = [ {'Name': 'Laptop', 'Quantity': 10, 'Price': 1200}, {'Name': 'Mouse', 'Quantity': 50, 'Price':
AV
writer.writeheader()
writer.writerows(_____)
IT
4. Write a Python program that reads data from a CSV file named "sales.csv" using the csv.reader()
U
object. The CSV file contains columns for "Date", "Product", and "Revenue". Your program should
TI
calculate and print the total revenue earned for each product across all dates.
O
5. Write a Python program that reads data from two CSV files, "sales.csv" and "inventory.csv", using
appropriate methods like csv.reader() or csv.DictReader().
N
The "sales.csv" file contains columns for "Date", "Product", and "Revenue", while the
S,
"inventory.csv" file contains columns for "Product" and "Quantity". Your program should combine
W
these datasets to create a new CSV file named "combined_data.csv" that includes the columns
"Date", "Product", "Revenue", and "Available Quantity". Ensure to handle missing or mismatched
ES
data appropriately.
Case study based questions-4 marks each
T
1. Imagine you work for a retail company that stores its daily sales data in a CSV file named
BE
"sales_data.csv". Develop a Python script using the csv module to read this file and generate a daily
sales report. The report should include total sales revenue, the number of items sold, and a
N
2. You are managing a student gradebook for a school, and the grade data is stored in a CSV file
AL
named "gradebook.csv". Design a Python program using the csv module to read and update student
grades. Implement functionalities such as adding new grades, calculating average grades for each
ZO
details like name, quantity, and reorder level. Create a Python application using the csv module to
E
track inventory levels, identify low-stock items (below reorder level), and generate a restocking list
with recommended quantities.
61 / 137
4. A company receives customer feedback through an online survey, and the feedback data is stored in
a CSV file named "feedback_data.csv". Develop a Python script using the csv module to read and
analyze the feedback. Implement sentiment analysis to categorize feedback as positive, neutral, or
negative and generate a summary report highlighting key customer sentiments.
5. You are responsible for managing personal finances and have a CSV file named "expenses.csv"
D
containing daily expense records. Build a Python application using the csv module to read and
AV
analyze the expense data. Implement functionalities such as calculating total expenses, categorizing
expenses (e.g., food, transportation), and generating a budget overview with spending trends.
IN
ANSWERS
ST
1.A) csv
2.B) To write data into a CSV file
IT
3.B) 'w'
U
4. C) writerow()
TI
5. B) close()
6. B) writerows()
O
7. D) newline=None
N
8. D) for loop
S,
11.B) Text-based
ES
12.D) list()
13. B) writerow()
T
15. B) writerows() writes multiple rows at once, while writerow() writes one row at a time.
16.A) It requires less memory compared to other modules.
N
18.C) List
AL
19.D) DictReader() reads data as dictionaries, while reader() reads data as lists.
20. B) To ensure cross-platform compatibility for newline characters.
2 marks questions
ZO
1.The csv module in Python is used to work with CSV (Comma Separated Values) files. It provides
functions to read, write, and manipulate data in CSV format, making it easier to handle tabular data.
N
2.
E
Newline handling is crucial when working with CSV files because different operating systems use
different newline characters (such as '\n' for Unix/Linux and '\r\n' for Windows). If newline
62 / 137
handling is not done correctly, it can lead to issues like extra blank lines or improper row parsing.
Using newline='' in the open() function ensures universal newline support, preventing such issues.
3.
writerow(): Writes a single row of data into the CSV file.
writerows(): Writes multiple rows of data into the CSV file. It takes an iterable of rows (e.g., a list
of lists) and writes each row as a separate line in the CSV file.
D
4.
AV
A CSV file is a text-based file format used to store tabular data. Each line in a CSV file represents a
row, and values within each row are separated by a delimiter character, commonly a comma (','),
although other characters like tabs or semicolons can also be used.
IN
5.
ST
The delimiter character is used to separate values within a CSV file. It signifies where one value
ends and the next one begins within a row. Common delimiter characters include commas (','), tabs
IT
('\t'), semicolons (';'), and pipes ('|'). The choice of delimiter depends on the data and the
U
6.
O
import csv
data = ['Name', 'Age', 'City']
N
writer = csv.writer(file)
W
writer.writerow(data)
7.
ES
import csv
try:
T
reader = csv.reader(file)
for row in reader:
N
print(row)
G
except FileNotFoundError:
AL
print("Error:", e)
8.
N
import csv
E
import random
data = [['Name', 'Age', 'City'],
['Alice', 25, 'New York'],
63 / 137
['Bob', 30, 'San Francisco'],
['Charlie', 28, 'Los Angeles']]
with open('output.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerows(data)
9
D
import csv
AV
writer = csv.writer(file)
ST
writer.writerows(new_data)
10.
IT
import csv
U
def count_rows(csv_file):
TI
try:
O
return row_count
W
except FileNotFoundError:
return 0
ES
except Exception as e:
print("Error:", e)
T
return 0
BE
file_path = 'data.csv'
total_rows = count_rows(file_path)
N
import csv
AL
low_stock_items = []
ZO
64 / 137
print("Low stock items:", low_stock_items)
3 MARKS QUESTIONS ANSWERS
1.
import csv
low_stock_items = []
with open('inventory.csv', 'r') as file:
D
reader = csv.reader(file)
AV
import csv
U
total_revenue = 0
TI
reader = csv.reader(file)
next(reader) # Skip header row
N
import csv
total_salary = 0
T
reader = csv.reader(file)
next(reader) # Skip header row
N
import csv
def write_student_data(file_name):
N
try:
E
65 / 137
while True:
name = input("Enter student name (or type 'exit' to quit): ")
if name.lower() == 'exit':
break
grade = input("Enter student grade: ")
writer.writerow([name, grade])
D
except Exception as e:
AV
print("Error:", e)
write_student_data('students.csv')
5.
IN
Delimiter characters in CSV files are used to separate individual fields (data values) within a row.
ST
The most common delimiter character is a comma (,), but other characters like tabs (\t), semicolons
(;), and pipes (|) can also be used.
IT
The significance of delimiter characters when working with the csv module in Python is that they
U
determine how data is organized and interpreted within a CSV file. When reading a CSV file,
TI
Python uses the specified delimiter character to split each row into individual fields, making it
O
possible to access and process the data accordingly. Similarly, when writing data to a CSV file, the
delimiter character is used to separate different values within each row. Using the correct delimiter
N
ensures that the data is correctly formatted and can be read or written without errors.
S,
6.
W
import csv
# Define the input and output file names
ES
input_file = 'data.csv'
output_file = 'high_scores.csv'
T
header = next(reader)
writer.writerow(header)
ZO
66 / 137
7.import csv
student_data = ['Alice', 25, 'A']
with open('output.csv', 'a', newline='') as file:
writer = csv.writer(file)
writer.writerow(student_data)
D
8.Correct code:
AV
import csv
student_data = ['Alice', 25, 'A']
with open('output.csv', 'a', newline='') as file:
IN
writer = csv.writer(file)
ST
writer.writerow(student_data)
IT
output:
U
9.
import csv
N
student_dict = {}
S,
reader = csv.reader(file)
next(reader) # Skip header row
ES
print(student_dict)
10.
N
G
import csv
AL
total_sales = 0
with open('sales.csv', 'r') as file:
ZO
reader = csv.reader(file)
next(reader) # Skip header row
N
67 / 137
5 MARKS QUESTIONS ANSWERS
1. import csv
product_values = {}
with open('inventory.csv', 'r') as file:
D
reader = csv.DictReader(file)
AV
price = float(row['Price'])
ST
product_values[product] += total_value
U
else:
TI
product_values[product] = total_value
O
print(f"{product}: ${total_value:.2f}")
S,
2.
W
import csv
data = [['Name', 'Age', 'City'], ['Alice', 25, 'New York'], ['Bob', 30, 'San Francisco']]
ES
writer.writerows(data)
BE
3
import csv
N
product_data = [
G
]
fieldnames = ['Name', 'Quantity', 'Price']
N
68 / 137
4.
import csv
product_revenue = {}
with open('sales.csv', 'r') as file:
reader = csv.reader(file)
next(reader) # Skip header row
D
product_revenue[product] += revenue
ST
else:
product_revenue[product] = revenue
IT
print(f"{product}: ${total_revenue:.2f}")
O
5.
import csv
N
sales_data = {}
W
product = row['Product']
BE
revenue = float(row['Revenue'])
if product not in sales_data:
N
else:
AL
sales_data[product]['Revenue'] += revenue
# Read data from inventory.csv
ZO
inventory_data = {}
with open('inventory.csv', 'r') as inventory_file:
N
reader = csv.DictReader(inventory_file)
E
69 / 137
inventory_data[product] = quantity
writer.writeheader()
AV
writer.writerow(data)
ST
4 marks questions
1,
IT
import csv
U
def generate_sales_report(csv_file):
TI
total_revenue = 0
O
total_items_sold = 0
sales_by_category = {}
N
reader = csv.DictReader(file)
W
total_revenue += revenue
items_sold = int(row['Items Sold'])
T
total_items_sold += items_sold
BE
sales_by_category[category] += revenue
G
else:
AL
sales_by_category[category] = revenue
print("Daily Sales Report:")
ZO
print("Sales by Category:")
E
70 / 137
2.
import csv
def update_student_grades(csv_file, student_name, subject, grade):
# Read existing grades
grades = {}
with open(csv_file, 'r') as file:
D
reader = csv.DictReader(file)
AV
grades[name] = {}
ST
grades[name][row['Subject']] = float(row['Grade'])
# Update or add new grade
IT
if student_name in grades:
U
grades[student_name][subject] = grade
TI
else:
O
total_students = 0
G
reader = csv.DictReader(file)
for row in reader:
ZO
if row['Subject'] == subject:
total_grade += float(row['Grade'])
N
total_students += 1
E
if total_students > 0:
average_grade = total_grade / total_students
print(f"Average Grade in {subject}: {average_grade:.2f}")
71 / 137
else:
print("No data for this subject.")
def generate_progress_report(csv_file, student_name):
with open(csv_file, 'r') as file:
reader = csv.DictReader(file)
for row in reader:
D
if row['Name'] == student_name:
AV
print(f"{subject}: {grade}")
ST
# Example usage:
update_student_grades('gradebook.csv', 'Alice', 'Math', 85)
IT
calculate_average_grade('gradebook.csv', 'Math')
U
generate_progress_report('gradebook.csv', 'Alice')
TI
3.
O
import csv
def track_inventory(csv_file, reorder_level):
N
low_stock_items = []
S,
restocking_list = {}
W
quantity = int(row['Quantity'])
BE
print(item)
print("Restocking List:")
N
print(f"{item}: {quantity}")
# Example usage:
track_inventory('inventory.csv', 10)
72 / 137
4.
import csv
from textblob import TextBlob
def categorize_feedback(csv_file):
positive_feedback = []
neutral_feedback = []
D
negative_feedback = []
AV
feedback = row['Feedback']
ST
analysis = TextBlob(feedback)
if analysis.sentiment.polarity > 0:
IT
positive_feedback.append(feedback)
U
elif analysis.sentiment.polarity == 0:
TI
neutral_feedback.append(feedback)
O
else:
negative_feedback.append(feedback)
N
print(feedback)
BE
print(feedback)
AL
# Example usage:
categorize_feedback('feedback_data.csv')
ZO
5.
import csv
N
def analyze_expenses(csv_file):
E
total_expenses = 0
expense_categories = {}
with open(csv_file, 'r') as file:
73 / 137
reader = csv.DictReader(file)
for row in reader:
amount = float(row['Amount'])
total_expenses += amount
category = row['Category']
if category in expense_categories:
D
expense_categories[category] += amount
AV
else:
expense_categories[category] = amount
print("Expense Analysis:")
IN
74 / 137
Unit : 2 introduction to Computer Networks
Network:-
The collection of interconnected computing devices is called a network. Two computing
devices are said to be interconnected if they are capable of sharing and exchanging
information.
D
AV
IN
ST
IT
U
TI
O
N
S,
Benefits of Network: -
(1) Resource Sharing: Resource Sharing means to make the
applications/programs, data(files) and peripherals available to anyone on the
W
network irrespective of the physical location of the resources and the user.
(2) Reliability: Reliability means to keep the copy of a file on two or more different
ES
(3) Cost Factor: Cost factor means it greatly reduces the cost since the resources can
be shared. For example a Printer or a Scanner can be shared among many
BE
computers in an office/Lab.
(4) Communication Medium: Communication Medium means one can send and
receive messages. Whatever the changes at one end are done, can be
N
EVOLUTION OF NETWORKING
AL
75 / 137
Data communication terminologies:
Concept of communication: Communication is the act of sending and receiving data from
one device to another device or vice-versa. Data can be of any form i.e. text, image, audio,
video and multimedia files.
Components of Data communication:
Sender: A device that can send data over a network i.e. computer, laptop, smart phone etc.
Receiver: A device can receive data over a network i.e. computer, laptop, smart phone etc.
The sender and receivers are basically called nodes.
Message: It is the data/information that needs to be shared between the sender and
D
receiver.
AV
Protocols: A network protocol is an established set of rules that determine how data is
transmitted between different devices in the same network. Essentially, it allows connected
ST
devices to communicate with each other, regardless of any differencesin their internal
processes, structure or design.
Measuring Capacity of Communication Media: In data communication, the transmission
IT
medium is also known as channel. The capacity of a channel is the maximum amount of signals
or traffic that a channel can carry. It is measured in terms of bandwidth and data transfer rate
U
as described below:
TI
Bandwidth
Bandwidth of a channel is the range of frequencies available for transmission of data
O
Normally, bandwidth is the difference of maximum and minimum frequency contained in the
S,
composite signals.
Bandwidth is measured in Hertz (Hz). 1
W
Data travels in the form of signals over a channel. One signal carries one or more bits over the
channel. Data transfer rate is the number of bits transmitted between source and destination
in one second. It is also known as bit rate. It is measured in terms of bits per second (bps).
T
1 Mbps=1024 Kbps
1 Gbps=1024 Mbps
N
IP Address:
An IP address is a unique address that identifies a device on the internet or a local network.
G
IP stands for "Internet Protocol," which is the set of rules governing the format of data sent
AL
There are two popular switching techniques – circuit switching and packet switching.
Circuit switching: Circuit switching is a type of network configuration in which a physical
N
path is obtained and dedicated to a single connection between two endpoints in the network
for the duration of a dedicated connection. Ordinary landline telephone service uses
E
circuit switching.
Packet switching: Packet switching is the method by which the internet works; it features
delivery of packets of data between devices over a shared network. For example the school
web server is sending you a webpage over the internet or you sending an email to a friend.
76 / 137
Transmission Media: Transmission media is a communication channel that carries the
information from the sender to the receiver. All the computers or communicating devices in
the network must be connected to each other by a Transmission Media or channel.
A Transmission medium is a medium of data transfer over a network.
The selection of Media depends on the cost, data transfer speed, bandwidth and
distance. Transmission media may be classified as
D
AV
IN
Twisted Pair Cable: Twisted pair or Ethernet cable is most common type of media which
consists four insulated pairs of wires twisted around each other. It is low-cost, low-weight and
easy to install flexible cables. It can transfer data up to 1Gbps speed covering 100 meters
IT
distance. It uses RJ-45 Connector for connecting computers and network devices. Co-axial
Cable: This type of cable consists a solid insulated wire surrounded by wire mesh, each
U
separated by some kind of foil or insulator. The inner core carries the signal and mesh
TI
provides the ground. Co-axial Cable or Coax, is most common in Cable TV transmission. It
can carry data up to 500 meters.
O
Fiber Optic Cable: Optical fiber consists of thin glass or glass like material and carries light
N
signals instead of electric current. Signal are modulated and transmitted in the form of light
pulses from source using Light Emitting Diode (LED) or LASER beam. Optical fibers offer
S,
Infrared Wave: It used for short-range (approx. 5 meters) communication using wireless
signals. It is mostly used in Remote operated devices like TV, Toys, Cordless phones etc.
ES
Radio waves: Radio wave uses Radio frequencies (3KHz-3 GHz) to make broadcast
network like AM/FM network within city. Radio wave propagates in Omni direction
(surrounding) and penetrate solid walls/buildings.
T
Microwaves: Microwave are high energy radio waves, used for line of sight communication
using Parabolic antenna aligned with each other. It is high speed wave and can cover
BE
machines and other electronic devices to a network are called network device. There are
many types of network devices used in networking and some of them are described below:
G
signal (modulator) at the sender’s site and converts back analog signal to digital signal
(demodulator) at the receiver’s end, in order to make communication possible via telephone
lines. It enables a computer to transmit data over telephone or cable lines.
ZO
Ethernet card: An Ethernet card in your computer serves one basic function: to transmit data
E
from the network to your computer. Ethernet cards are physical expansion cards that insert
into a PCI expansion slot on a computer.
RJ45: RJ45 connectors are commonly seen with Ethernet network cables. Ethernet cables
with RJ45 connectors are also called RJ45 cables. These RJ45 cables feature a small plastic plug
on each end, and the plugs are inserted into RJ45 jacks of Ethernet devices.
77 / 137
Hub: A Hub is a connecting device which connects multiple computers together to form a
Local Area Network (LAN). Hubs make broadcast type Network and do not manage traffic
over the network channel. Signal entering any port is broadcast out on all other ports. It
broadcast the signals to all computers connected in the network. It provides various RJ-45
ports to connect Twisted Pair cable in STAR topology, making them act as a single network
segment. Now days, Switch is used in place of Hubs.
Types of Hub:
Active Hub: Amplifies the signal when required and works as a Repeater.
Passive Hub: It simply passes the signal without any change.
D
Switch: A switch is a hardware device, which is used to connect several nodes to form a
AV
Network. It redirects the received signals only to the intended Node i.e. controls Network
traffic.It is also used to segment a big network into different Sub networks (Subnet) to
control the network traffic and security. It can also use to combine various small network
IN
incoming packet (data) to all the hub ports, while a switch forwards each incoming packet to
the specified recipient.
Repeater: Repeater is a hardware device, which is used to amplify the signals when they are
IT
transported over a long distance. The basic function of a repeater is to amplify the incoming
U
(shortest path) for the data packets to be transmitted. In a large network (WAN),
N
Network Topologies:
Topology: Topology refers to the way in which the
G
are interconnected.
The layout of interconnection of devices in a network is
called Topology.
ZO
task of sending messages without the help of the central server. However, only one
workstation can transmit a message at a particular time in the bus topology.
E
Advantages:
(i) Easy to connect and install.
(ii) Involves a low cost of installation time.
(iii) Can be easily extended.
78 / 137
Disadvantages:-
(i) The entire network shuts down if there is a failure in the central cable.
(ii) Only a single message can travel at a particular time.
(iii) Difficult to troubleshoot an error.
STAR Topology: -In Star topology, each node is directly connected to a central device like Hub
or Switch. It is most popular topology to form Local Area Networks (LAN).
Advantages:
(i) Easy to troubleshoot
D
(ii) A single node failure does not affects the entire network.
AV
(iii) The cost of the hub and the longer cables makes it expensive
over others.
(iv) All nodes are dependent on central node. if the central device (Switch) goes down
IT
TREE Topology: - The tree topology combines the characteristics of the linear bus and the
TI
Advantages:
(i) Eliminates network congestion.
N
(iii) Faulty nodes can easily be isolated from the rest of the
network.
W
Disadvantages:
Uses large cable length.
ES
devices linked together. A computer network may contain devices ranging from handheld
devices (like mobile phones, tablets, laptops) connected through Wi-Fi or Bluetooth within a
N
single room to the millions of computers spread across the globe. Based on the size, coverage
area, data transfer speed and complexity, a computer network may be classified as:
G
LAN (Local Area Network): A Local Area Network (LAN) is a network that is limited to a
AL
small area. It is generally limited to a geographic area such as within lab, school or building.
It is generally privately-owned networks over a distance up to a few kilometers. Now-a-days,
we also have WLAN (Wireless LAN) which is based on wireless network.
MAN (Metropolitan Area Network): MAN is the networks cover a group of nearby
ZO
corporate offices or a city and might be either private or public. Cable TV network or cable
based broadband internet services are examples of MAN.
N
WAN (Wide Area Network):These are the networks spread over large distances, say across
E
countries or even continents through cabling or satellite uplinks are called WAN. Typically, a
WAN combines multiple LANs that are geographically separated. It is a network of network.
The world’s most popular WAN is the Internet.
79 / 137
PAN (Personal Area Network): A Personal Area Network is computer network organized
around an individual person. It generally covers a range of less than 10 meters. Personal Area
Networks can be constructed with cables or wirelessly.
1 km) Globe
AV
speed
Error Rate Lowest Lowest Moderate Highest
ST
Modem
U
Microwave
O
Network Protocols:
N
The Hyper Text Transfer Protocol is a set of rules which is used to access/retrieve
linked web pages across the web using web browser program.
W
The more secure and advanced version is HTTP is HTTPS (HTTP Secure), which
controls the transfer of information in encrypted form to provide more security
ES
and privacy.
Other protocols like File Transfer Protocol (FTP) and Telnet can also be used with
URL. FTP is used to transfer files from web server to web client or vice-versa.
T
BE
N
G
AL
ZO
N
E
80 / 137
Telnet is protocol which used for login on remote computer to access/transfer
files or trouble shooting.
FTP (File Transfer Protocol) is a network protocol for transmitting files between
computers over Transmission Control Protocol/Internet Protocol (TCP/IP) connections.
Point-to-Point Protocol (PPP) is a TCP/IP protocol that is used to connect one computer
system to another. Computers use PPP to communicate over the telephone network or the
Internet. A PPP connection exists when two systems physically connect through a telephone
line.
D
remote host. However, TELNET can also be used for terminal-to-terminal communication
and interprocess communication. TELNET is also used by other protocols (for example, FTP)
ST
message(s) using the Internet. An email can be sent anytime to any number of recipients at
U
anywhere. The message can be either text entered directly onto the email application or an
attached file (text, image, audio, video, etc.) stored on a secondary storage. An existing file
TI
Email are handled and exchanged through various mail servers in order to deliver email to
N
mail client. The mail client and mail servers exchange information with each other using
some protocols. The followings are commonly used protocols for email handling-
S,
SMTP (Simple Mail Transfer Protocol): This protocol is used to send emails from
sender to recipient’s mail server.
W
IMAP (Internet Message Access Protocol): This is a standard client/server protocol for accessing e-
mails from local e-mail server.
ES
POP3 (Post Office Protocol 3): This protocol facilitates users to access mailboxes and
download messages to their computer.
Voice over Internet Protocol (VoIP):
T
Voice over Internet Protocol or VoIP, allows voice call (telephone service) over the
BE
Internet. VoIP offers voice transmission over a computer network (IP) rather than
through the regular telephone network. It is also known as Internet Telephony or
Broadband Telephony. Examples of VoIP:- WhatsApp, Skype, Google Chat etc.
N
VoIP works on the principle of converting the analogue voice signals into digital
and then transmitting them over the broadband line.
G
These services are either free or very economical. That is why these days
AL
Overview of Internet:
ZO
The Internet is a global system of interconnected computer networks that use the
E
81 / 137
The modern Internet is an extension of ARPANET (Advance Research Project
Agency Network), created in1969 by the American Department of Defense.
In 1990 the British Programmer Tim Berners-Lee developed Hypertext and HTML
to create World Wide Web (WWW).
The Internet carries an extensive range of information resources and services,
such as the inter-linked hypertext documents of the World Wide Web (WWW), the
communicational infrastructure to support mail, chat and transfer of Text, Images,
Audio, Video etc.
D
stored in web servers and connected to local computers through the internet. These
websites contain text pages, digital images, audios, videos, etc. Users can access the content of
ST
these sites from any part of the world over the internet using their devices such as computers,
laptops, cell phones, etc. The WWW, along with internet, enables the retrieval and display of
text and media to your device.
IT
There sources of the Web (HTML pages) are transferred via the Hypertext Transfer Protocol
U
(HTTP), may be accessed by users by a software application called a web browser, and are
published by a software application called a web server.
TI
Tim Berners-Lee—a British computer scientist invented the revolutionary World Wide Web
in 1990 by defining three fundamental technologies that lead to creation of www: HTML
O
,URL, HTTP.
N
Hyper Text Markup Language (HTML) is a language which is used to design standardized
Web Pages, so that the Web contents can be read and under stood from any computer using
W
web browser.
Basic structure of every web page is designed using HTML. HTML uses tags to define the way
ES
page content should be displayed by the web browser. Web pages are stored as .html or .htm
files.
Extensible Markup Language (XML): Extensible Markup Language is a markup language
T
and file format for storing, transmitting, and reconstructing arbitrary data. It defines a set of
BE
rules for encoding documents in a format that is both human-readable and machine-
readable.
N
In the above URL, http is the protocol name, it can be https, http, FTP, Telnet, etc. www is a
sub domain. ncert.nic.in is the domain name. Textbook is directory and textbook.htm is
webpage.
82 / 137
The complete unique address of the page on a website is called URL (Uniform Resource
Locator) e.g. http://www.cbse.nic.in/welcome.html
Since computers on the network are identified by its IP addresses, so it is required to convert
a Domain name or URL typed in the Browser, in to its corresponding IP address. This
process is called Domain Name Resolution. This resolution is done by the designated servers
called DNS servers, provided by the Internet Service Providers (ISP) like BSNL, Airtel, Jio etc.
Website:
Website is a collection of related web pages that may contain text, images, audio
D
and video. The first page of a website is called home page. Each website has
specific internet address (URL) that you need to enter in your browser to access a
AV
website.
A website is a collection of web pages related through hyperlinks, and saved on a
web server. A visitor can navigate pages by clicking on hyperlinks.
IN
browser. The main page of website (Home page) will be open when it is opened
U
on the browser.
Web Page:
TI
A web page is a document on the WWW that is viewed in a web browser. Basic
structure of a web page is created using HTML (Hyper Text Markup Language).
O
To make web pages more attractive, various styling CSS (Cascading Style Sheets)
N
define different actions and behavior. JavaScript, PHP and Python are commonly
used script language.
W
The first page of the website is called a home page which contains Menus and
Hyperlinks for other web pages.
ES
A web page is usually a part of a website and may contain information in different
forms, such as: text, images, audio & video, Hyperlinks, interactive contents (chat
etc.)
T
A web page can be of two types: Static Web Page and Dynamic Web Page
BE
Web Browsers:
A web browser or simply ‘browser’ is a software application used to access
N
information on the World Wide Web. When a user requests some information, the
G
web browser fetches the data from a web server and then displays the webpage
on the user’s screen.
AL
The popular web browsers are Google Chrome, Mozilla Firefox, Internet Explorer,
Opera, Safari, Lynx and Netscape Navigator, Microsoft Edge etc.
ZO
A web browser essentially displays the HTML documents which may include text,
images, audio, video and hyperlinks that help to navigate from one web page to
another. The modern browsers allow a wide range of visual effects, use encryption
N
for advanced security and also have cookies that can store the browser settings
and data.
E
83 / 137
Web Server:
A web server is used to store and deliver the contents of a website to web clients
such as a browser.
A Computer stores web server software and a website's contents (HTML pages,
images, CSS style sheets, and JavaScript files). The server needs to be connected to the
Internet so that its contents can be made accessible to others.
Web server as a software, is a specialized program that understands URLs or web
addresses coming as requests from browsers, and responds to those requests.
D
The server is assigned a unique domain name so that it can be accessed from
anywhere using Internet. The web browser from the client computer sends a HTTP
AV
request for a page containing the desired data or service. The web server then accepts
request, interprets, searches and responds (HTTP response) against request of the
web browser. The requested web page is then displayed in the browser of the client. If
IN
the requested web page is not found, web server generates “Error: 404 Not found” as
a response.
ST
Web Hosting:
A web hosting service is a type of Internet hosting service that allows individuals and
organisations to make their website accessible via the World Wide Web. In Simple,
IT
need some web space on server to upload website. This space is available on some
TI
nominal charges.
All web servers are assigned a unique numeric address called IP address when
O
(Textual name) of the website using DNS (Domain Name Service). Thus, user can access
website by providing domain name through a browser (URL). The domain name has to
S,
84 / 137
QUESTIONS ON COMPUTER NETWORKING
MULTIPLE CHOICE QUESTIONS(1 MARK EACH)
1. ______ is a communication methodology designed to deliver both voice and multimedia
communications over Internet protocol.
(A) SMTP (B) VoIP (C) PPP (D) HTTP
D
the internet.
TI
7. Network in which every computer is capable of playing the role of a client, or a server or
both at same time
W
is called
a) local area network b) peer-to-peer network c) dedicated server network d) wide
ES
area network
T
9. Identify the device on the network which is responsible for forwarding data from one
device to another
G
10. Which of the following device send data to every connected node?
a)Switch b)Repeater c)Router d) Hub
ZO
11. In which type of switching first the connection is established between sender
N
12. Identify the cable which consists of an inner copper core and a second
conducting outer sheath:
(i)Twisted Pair (ii) Co-axial (iii) Fiber Optical (iv) Shielded Twisted Pair
13. In fiber optic transmission, data is travelled in the form of:
85 / 137
(i) Light (ii) Radio link (iii) Microwave Link (iv) Very low frequency
14. Which of the following devices modulates digital signals into analog signals
that can be sent over traditional telephone lines?
(i) Router (ii) Gateway (iii) Bridge (iv) Modem
external interference?
(i) Twisted Pair (ii) Co-axial Cable (iii) Fiber Optical (iv) Electric Wire
AV
16. Which of the following device is used for sorting and distribution of data packet
IN
18. Which type of Network is generally privately owned and links the devices in a
O
20. Raj is looking for some information about How Router works, for this he
opens the browser and typed the URL of requested site. In few moments he
received the requested page on his browser screen. Identify the type of
T
protocol, used between Browser (Client) and Web Server for the
BE
communication?
a. TCP/IP b.HTTP c,SMTP d.POP3
N
2 MARKS QUESTIONS
1. Write two points of difference between Bus topology and star topology.
G
7. Classify each of the following Web Scripting as Client Side Scripting and
E
86 / 137
of frequencies a channel can pass?
9. (a) Write the full forms ithe following:
(i) FTP (ii) HTTPS
b)Name the protocols which are used for sending and receiving emails?
10. Write two differences between Coaxial and Fiber transmission media.
5 MARKS QUESTIONS
D
1. A professional consultancy company is planning to set up their new offices in India with its
AV
hub at
Hyderabad. As a network adviser, you have to understand their requirement and suggest them
the best
IN
a) Which will be the most appropriate block, where TTC should plan to install their server?
T
b) Draw a block to block cable layout to connect all the buildings in the most appropriate
manner for efficient communication.
BE
c) What will be the best possible connectivity out of the following, you will suggest to
connect the new setup of offices in Bengalore with its London based office.
N
● Satellite Link
● Infrared
G
● Ethernet
AL
d) Which of the following device will be suggested by you to connect each computer in each
of the buildings?
● Switch
ZO
● Modem
● Gateway
N
e) Company is planning to connect its offices in Hyderabad which is less than1 km. Which
type of network will be formed?
E
Sol: (i) The company should install its server in finance block as it is having maximum
number of computers.
(ii) The layout is based on minimum cable length required, which is 120 metres in the
above case.
87 / 137
(iii) Satellite Link.
(iv) Switch.
(v) LAN
which are required to be connected in a network for communication, data and resource
sharing. As a network consultant of this company,you have to suggest the best network related
AV
solutions for them for issues/problems raised in question nos. (i) to (v), keeping in mind the
distances between variousblocks/locations and other given parameters.
IN
ST
IT
U
TI
O
N
S,
W
ES
(i) Suggest the most appropriate block/location to house the SERVER in the Surajpur
T
center (out of the 3 blocks) to get the best and effective connectivity. Justify your answer.
BE
(iii) Suggest the best wired medium and draw the cable layout (Block to Block) to
most efficiently connect various blocks within the Surajpur Center.
G
AL
(iv) Suggest the placement of the following devices with appropriate reasons:
a) Switch/Hub b) Router
ZO
(v) Suggest the best possible way to provide wireless connectivity between Surajpur Center
and Raipur Center.
N
ii) Surajpur centre has multiple blocks and firewall ensures security. So it is required. It
allows or block unwanted attacks.
88 / 137
iii)
D
AV
iv) a) Switch/Hub – In every block to interconnect the devices within every block
b) Router -In development block because server is going to be placed here
v) Satellite
IN
training
centers in various cities in next 2 years. Their first campus is coming up in Kodagu district.
IT
At Kodagu campus, they are planning to have 3 different blocks, one for AI, IoT and
DS (Data Sciences) each. Each block has number of computers, which are required to
U
consultant of this company, you have to suggest the best network related solutions for them
for issues/problems raised in question nos. (i) to (v), keeping in mind the distances between
O
(i) Suggest the most appropriate block/location to house the SERVER in the Kodagu
campus (out of the 3 blocks) to get the best and effective connectivity. Justify your answer.
ZO
(ii) Suggest a device/software to be installed in the Kodagu Campus to take care of data
N
security.
E
Ans:Firewall
(iii) Suggest the best wired medium and draw the cable layout (Block toBlock) to most
efficiently connect various blocks within the Kodagu Campus.
Ans:Optical fiber
89 / 137
(iv) Suggest the placement of the following devices with appropriate reasons:
D
a) Switch/Hub b) Router
AV
(v) Suggest a protocol that shall be needed to provide Video Conferencing solution between
Kodagu Campus and Coimbatore Campus.
ST
Sol:VoIP
IT
4. Aryan Infotech Solutions has set up its new center at Kamla Nagar for its office and web
U
based activities. The company compound has 4 buildings as shown in the diagram below:
TI
O
N
S,
W
ES
T
BE
N
G
AL
ZO
N
E
90 / 137
ii) Suggest the most suitable place (i.e. building) to house the server of this organisation
with a
suitable reason
iv) The organisation is planning to link its sale counter situated in various parts of the
same city,
which type of network out of LAN, MAN or WAN will be formed? Justify your answer.
IN
Sol: i)
IT
U
TI
O
N
S,
W
ES
iv) MAN, it is formed to connect various locations of the city via various
communication media.
v) PAN is “Personal Area Network”, basically configured at home area.
N
G
5. Magnolia Infotech wants to set up their computer network in the Bangalorebased campus
having four
AL
buildings. Each block has a number of computers that are required to be connected for ease of
communication, resource sharing and data security. You are required to suggest the best
ZO
answers to
the questions i) to v) keeping in mind the building layout on the campus.
N
E
91 / 137
D
AV
IN
ST
IT
U
TI
i) Suggest the most appropriate block to host the Server. Also justify your choice.
O
Suggest the device that should should be placed in the Server building so that they can
N
ii)
connect to Internet Service Provider to avail Internet Services.
S,
iii) Suggest the wired medium and draw the cable block to block layout to economically
W
iv) Suggest the placement of Switches and Repeaters in the network with justification.
T
v) Suggest the high-speed wired communication medium between Bangalore Campus and
Mysore campus to
BE
iv) Switches in all the blocks since the computers need to be connected to the network.
E
Repeaters between Admin and HR block& Admin and Logistics block. The reason
being the distance is more than 100m.
v) Optical Fiber cable connection.
92 / 137
Unit : 3 Database Management and Mysql
Relational
Database
Model
Introductory
D
Database
Concepts of
Constraints
AV
Database
Database
Management
IN
Common Database
ST
Database Languages
Operations & SQL
IT
Database
Keys
U
TI
O
SQL
ES
T
Operations in SQL
AL
93 / 137
Database Management System (DBMS)
Control inconsistency
Facilitates sharing of data
ES
Enforce standards
Ensure data security
Maintain integrity
T
Complex system
AL
Types of DBMS:
Hierarchical DBMS
ZO
94 / 137
Common Terminologies related to Relational Data Model:
Relation: Collection of data organized in rows and columns where each cell has atomic
value. (same as Table)
Tuple: Row of a table (same as Record)
Attribute: Column of a table (same as Field)
Domain: Range of values (data types) allowed for an attribute
Degree: No. of attributes/columns/fields in a table
D
View: Virtual table (no physical existence) derived from one or more base table for ease of
query only.
Referential Integrity: Property of database that requires every value of one attribute of a
IN
Relation must be present in another attribute (same datatype) in a different (or the same)
relation.
ST
Example:
IT
U
TI
O
N
S,
Database Key
Key in a database is defined as a set of attributes to identify each record uniquely in a table. A Key
T
Classification of Keys:
N
Key
G
AL
ZO
Primary Key: The one candidate key chosen by Database Administrator for a table to
uniquely identify a record in a table is said to be Primary Key of that table. A table can have
exactly one Primary Key.
Alternate Key: Candidate key(s) not chosen by Database Administrator in a table is/are
defined as alternate key(s). A table can have 0 or more alternate keys.
95 / 137
Foreign Key: Foreign Key is a non-key attribute derived from primary key of some other
table. A table can have 0 or more foreign keys.
D
AV
IN
ST
IT
U
TI
O
N
S,
W
ES
T
m-d.
ZO
Date & Time data types: Used to represent date, time, or both in a column. Data is enclosed
with quotes ‘ ’ or “ “.
e.g. - date, datetime, time
N
E
String / Text data types: Used to represent text in a column. Data is enclosed with quotes ‘ ’
or “ “.
e.g. –
char(m) – Fixed length character of length m where 1 character takes 1 Byte in memory.
Memory space is wasted if text size is less than m.
96 / 137
varchar(m) – Variable length character allowing maximum number of characters m. It
saves memory allocation for text having lesser size than m.
Data Definition Language (DDL) defines the different structures in a database like table, view,
index etc.
T
DDL statements are used to create structure of a table, modify the existing structure of the table
BE
97 / 137
The manipulation includes inserting data into tables, deleting data from the tables and modifying
the existing data.
e.g. – INSERT, UPDATE, DELETE
DELETE record
IT
Database ensures that a database transaction i.e. complete set of records involved in a transaction
N
either fully completed or not taken place at all to maintain data consistency. Transaction Control
Language (TCL) statements allows to save or revert database transactions.
S,
e.g. –
W
Query:
BE
Query is a type of SQL commands which accepts tables (relations), columns (fields or attributes)
and conditions or specifications if any and display the output by means of a temporary table which
N
Structure of Query:
AL
HAVING < condition on aggregate function on a column only if group by exists >
E
98 / 137
II. SELECT statement contains one or more columns. * should be used to display all columns.
Functions or expressions on columns can also be done.
III. FROM statement contains multiple tables only if columns from more than one tables are
displayed through SELECT statement in case of product or join operations. Here records
can be fetched from multiple tables.
IV. WHERE clause may contain multiple conditions related with logical OR / AND operators.
Logical NOT operator can be used on a condition also.
GROUP BY clause is used if statistical records are to be displayed based on a field/column.
D
V.
In this case SELECT statements should contain GROUP BY field and aggregate function
AV
on another column at least. Once a group is formed individual records cannot be accessed
in the same query.
VI. ORDER BY clause can be used to arrange the output records in ascending (by default) or
IN
Step 5: Arrange the output records in ascending or descending order using ORDER BY
N
Database Constraints
Rules imposed on the values of one or more columns in the tables are called database constraints.
ES
UNIQUE Ensures that all values in a column are different. No two records have
same values in that column.
BE
NOT NULL Ensures that a column can never have NULL values.
PRIMARY KEY Uniquely identify a record. It is a combination of UNIQUE and NOT
NULL.
N
CHECK Specify the domain of values with certain criteria for a column.
G
FOREIGN KEY referencing table and primary key of independent / referenced table.
ZO
99 / 137
D
AV
IN
ST
In DEPT table:
1. DEPT_ID is primary key
IT
In EMPL table:
O
6.
A. Write DDL statement to create a database OFFICE and define two tables mentioned as above
ES
USE OFFICE;
G
Note: By default, TEST database is used which is in-built database in MySQL. So no need to
create test. Only ‘use test;’ statement can be written to enter test.
AL
100 / 137
Schema or structure of table DEPT is as follows:
DESC DEPT;
D
AV
DOJ DATE,
HOMETOWN VARCHAR(20) DEFAULT 'BANGALORE',
U
);
N
or,
S,
EID VARCHAR(6),
ENAME VARCHAR(30) NOT NULL,
ES
GEN CHAR,
DOJ DATE,
HOMETOWN VARCHAR(20) DEFAULT 'BANGALORE',
T
SALARY DECIMAL(8, 2) ,
MGR_ID VARCHAR(6) ,
BE
DEPT_ID VARCHAR(4) ,
PRIMARY KEY(EID),
CHECK (GEN IN ('M', 'F', 'T')),
N
);
DESC EMPL;
N
E
101 / 137
Name of tables defined in current database so far.
SHOW TABLES;
D
AV
INSERT INTO EMPL VALUES ('E0001', 'RITU SEN', 'F', '2002-06-20', 'KOLKATA',
N
INSERT INTO EMPL VALUES ('E0004', 'ANISHA RAWAT', 'F', '2019-09-04', 'DELHI',
20000.00, 'E0001', 'D03' );
BE
INSERT INTO EMPL VALUES ('E0005', 'SANA KHAN', 'F', '2017-08-31', 'DELHI',
30000.00, 'E0003', 'D01');
N
G
C. Write SQL statements for the following queries and display their outputs.
AL
2. Display name and salary of all the employeEs from table EMPL.
SELECT ENAME, SALARY
FROM EMPL;
102 / 137
D
Note:
U
order. Hence ASC is default keyword and need not be used in ORDER BY statement.
O
In case of arranging the output of query in descending order of values DESC keyword must
be used in ORDER BY statement.
N
S,
Comparison operators
W
SOLUTION OUTPUT
SELECT ENAME, GEN
BE
FROM EMPL
WHERE HOMETOWN =
N
'BANGALORE';
G
6. Display name of employees and salary in descending order of names where DEPT_ID is
not 'D03'.
SOLUTION OUTPUT
103 / 137
SELECT ENAME,
SALARY
FROM EMPL
WHERE DEPT_ID !=
'D03'
ORDER BY ENAME
DESC;
D
SOLUTION OUTPUT
SELECT EID, ENAME
IN
FROM EMPL
WHERE DOJ > '2015-01-31' ;
ST
IT
Logical Operators
TI
OR AND NOT
O
Logical operators are used in where clause. AND, OR are binary operations which require 2
N
AND : c1 and c2 → If both c1 and c2 are true the overall condition is true.
OR : c1 or c2 → If at least one between c1 or c2 are true the overall condition is true.
W
NOT : not c1 → If c1 is true the overall condition is false and vice versa.
ES
BETWEEN: BETWEEN operator can be used as a substitute of and operation where the minimum
and maximum value is to be checked for a single column.
T
BE
8. Display the records of those employees whose salary is between 35000 and 45000.
SOLUTION1 SOLUTION2
N
104 / 137
Checking a list of values
IN: IN operator is a substitute of OR operation(s) among equality checking of a single column with
multiple values.
NOT IN: NOT IN operator is used for non-equality checking of a column with multiple values.
D
AV
9. Display name and hometown of employees who belong to departments 'D01' or 'D02'.
SOLUTION 1 SOLUTION 2 OUTPUT
SELECT ENAME, SELECT ENAME,
IN
HOMETOWN HOMETOWN
FROM EMPL FROM EMPL WHERE
ST
10. Display EID and SALARY of employees whose half of salary is neither 10000 nor 20000.
U
20000);
S,
Wildcard Characters
W
ES
A string constant to be checked with a value stored in a column may have one or more characters
missing in case of sub string checking. Such placeholder can be of two types:
T
(underscore)
% → Replacement or placeholder of 0 or more characters in the string constant value.
N
G
LIKE: A string constant containing one or more wildcard characters can be checked for equality
AL
containing one or more wildcard characters. It cannot be done using <> or !=.
N
11. List the name of employees whose name starts with 'S' and have length at least 5.
E
SOLUTION OUTPUT
SELECT ENAME
FROM EMPL
WHERE ENAME LIKE 'S____%';
105 / 137
12. List the name of employees whose name ends with 'N' or does not contain 'M' in it.
SOLUTION OUTPUT
SELECT ENAME
FROM EMPL
D
NULL checking
ST
IS: IS is a special operator which is used to check absence of value i.e. NULL in a column as no
other comparison operator can be used on NULL values.
IT
IS NOT: Likewise, IS NOT is used to check the presence of values i.e. NOT NULL in a column.
U
13. Print ENAME and DEPT_ID of employees who do not have manager i.e. MGR_ID is blank.
TI
SOLUTION OUTPUT
O
14. Print ENAME and DEPT_ID of employees who have manager i.e. MGR_ID is not empty.
SOLUTION OUTPUT
T
output. SQL allows duplicate values in output. ALL is by default used in SQL, so need not be used
explicitly.
N
DISTINCT: By default, SQL does not remove any duplicate values in the output on its own.
E
Hence DISTINCT keyword is used along with a column where redundant values need to be
removed before displayed.
106 / 137
15. List the hometowns of all the employee (Including duplicate values).
SOLUTION 1 SOLUTION 2 OUTPUT
SELECT SELECT ALL
HOMETOWN HOMETOWN
FROM EMPL; FROM EMPL;
D
AV
16. List the name of places which are hometown of any employee. (No duplicate values)
SOLUTION OUTPUT
SELECT DISTINCT
IN
HOMETOWN
FROM EMPL;
ST
IT
U
Aggregate functions
TI
O
Without using GROUP BY clause: Display output corresponding to the overall table may or may
ES
GROUP BY: GROUP BY clause is used if statistical records of a table are to be displayed based
on a field. Once the group is formed individual records cannot be accessed in that query. Several
clusters or groups are formed based on the number of different values in the GROUP BY column
present in the table.
107 / 137
For example, if GROUP BY is applied on TYPE field of ITEM table 3 groups are formed – Crops
have 2 records, Leaves and Pulses have one record each.
Renaming field and table
AS is an optional keyword to rename a column a table in FROM clause or an expression on
column(s) in SELECT clause. If there is blank space in alias then it must be surrounded by ' ' or '' ''.
Column renaming is done for customized display of query output.
D
Table renaming is done for giving convenient names to the tables in join operations for
AV
SOLUTION OUTPUT
SELECT COUNT(DISTINCT DLOC) as 'NO. OF
ST
LOCATIONS'
FROM DEPT;
IT
U
18. Display the earliest and latest DOJ of employees as per EMPL.
TI
SOLUTION OUTPUT
SELECT MIN(DOJ) 'EARLIEST', MAX(DOJ)
O
'LATEST'
N
FROM EMPL;
S,
SOLUTION OUTPUT
ES
SOLUTION OUTPUT
SELECT DEPT_ID, SUM(SALARY) 'TOTAL
AL
SALARY'
FROM EMPL
GROUP BY DEPT_ID;
ZO
N
HAVING: It is a conditional statement used along with group by clause only. It compares the
E
values with the outcome of aggregate functions belonging to each group already formed by
GROUP BY clause.
108 / 137
Difference between WHERE and HAVING:
21. Display the hometowns and no. of employees belonging to them if the headcount per
D
hometown is at least 2.
AV
SOLUTION OUTPUT
SELECT HOMETOWN, COUNT(EID) 'NO
OF EMPLOYEE'
IN
FROM EMPL
GROUP BY HOMETOWN
ST
22. Display the number of employees working in each DEPT_ID excepting 'D01' where no. of
U
SOLUTION OUTPUT
SELECT DEPT_ID, COUNT(*) AS 'NO OF
O
EMPLOYEE'
N
FROM EMPL
WHERE DEPT_ID != 'D01'
S,
GROUP BY DEPT_ID
HAVING COUNT(*) > 1;
W
Cartesian Product
ES
Cartesian product is performed on two tables and it produces all the combination of records in both
tables. It does not require any common column.
T
If tables A, B have m, n columns and p, q records respectively then resultant table A x B has m+n
BE
FROM EMPL, DEPT; FROM EMPL INNER JOIN FROM EMPL JOIN
DEPT; DEPT;
[RECOMMENDED
ZO
STATEMENT]
N
E
109 / 137
JOIN
NATURAL JOIN: Natural join is a binary operator which works on two tables. They should have
one column which have same name and domain. It a combination of Cartesian product and a where
clause with equality checking on the common columns.
Other conditions in that query are ANDed with the join condition.
Natural join is mostly done on Foreign key field of one table and Primary key field of
D
another table.
If tables A, B have m, n columns and p, q records respectively then resultant table has m+n
AV
EQUI JOIN: Equi join is a join operation which works on the equality condition of values in two
columns from two tables having similar data type. NATURAL JOIN, EQUI JOIN are said to be
ST
INNER JOIN.
24. Perform Natural Join between these two tables.
IT
SOLUTION 1 SOLUTION 2
U
SELECT * SELECT *
FROM EMPL NATURAL JOIN FROM EMPL, DEPT
TI
DEPT.DEPT_ID;
[RECOMMENDED STATEMENT]
N
S,
W
ES
SOLUTION OUTPUT
SELECT ENAME, DNAME
BE
SOLUTION OUTPUT
SELECT ENAME
N
27. Display no. of employees working in those departments whose DLOC is CHENNAI.
SOLUTION OUTPUT
110 / 137
SELECT COUNT(*) 'NO. OF EMPLOYEES'
FROM EMPL AS E, DEPT AS D
WHERE E.DEPT_ID = D.DEPT_ID
AND DLOC = 'CHENNAI';
28. Display ENAME of employees who have manager along with that display ENAME of their
corresponding manager as well.
D
SOLUTION OUTPUT
AV
29. Display ENAME and the amount of bonus to be paid to that employee where bonus = 5000 +
5% of SALARY.
IT
SOLUTION OUTPUT
U
FROM EMPL;
O
N
S,
1. Assign DEPT_ID 'D03' to those employees who are presently working at 'D02'.
ES
SOLUTION OUTPUT
UPDATE EMPL
SET DEPT_ID = 'D03'
T
SOLUTION OUTPUT
AL
UPDATE EMPL
SET SALARY = 1.1 *
SALARY;
ZO
SOLUTION OUTPUT
DELETE FROM DEPT
WHERE DEPT_ID = 'D02';
111 / 137
E. Write DDL statements for the following purpose:
1. Add DPHONE field to table DEPT which should be a number of 10 digits and unique for each
department.
SOLUTION OUTPUT
ALTER TABLE DEPT
D
DESC DEPT;
IN
SOLUTION OUTPUT
ALTER TABLE DEPT
DROP MAX_STRENGTH;
IT
3. Modify the datatype of SALARY in table EMPL to an integer of length 6 and drop the existing
O
check constraint.
N
SOLUTION OUTPUT
S,
DESC EMPL;
ES
T
BE
Questions ;
Q. No. 1 to 20 are MCQs of 1 mark each
N
G
3.
a. CHECK b. DEFAULT c. UNIQUE d. NULL
E
4. The data types CHAR (n) and VARCHAR (n) are used to create _______ and
_______ types of string/text fields respectively in a database.
a) Fixed, equal b) Equal, variable c) Fixed, variable d) Variable, equal
5. Which of the following is a DDL command?
A. UPDATE B. INSERT C. DELETE D. ALTER
6. Which command is used to open the database “SCHOOL”?
a. USE SCHOOL b. OPEN SCHOOL
112 / 137
c. USE DATABASE SCHOOL d. SHOW SCHOOL
7. In the given query which keyword has to be inserted?
INSERT INTO employee______(1002, “Kausar”, 2000);
a) Value b) Values c) Values into d) Into Values
8. Which SQL statement is used to display all the data from PRODUCT table in the
decreasing order of PRICE?
a. SELECT * FROM PRODUCT ORDER PRICE BY DESC ;
b. SELECT * FROM PRODUCT PRICE ORDER BY DESC;
D
9. Which of the following function is used to FIND the largest value from the given
data in MYSQL?
a) MAX () b) MAXIMUM () c) LARGEST () d) BIG ()
IN
11. __________ aggregate function does not ignore NULL values in a column.
a) Min() b) Sum() c) Avg () d) Count ()
IT
a) = b) LIKE c) IS d) <>
Which SQL statement is used to display all the data from ITEMS table where
TI
13.
INAME is ending with ‘L’?
O
14. Which join combines each row from the first table with every row from the
second table to make the result set?
W
16. Where and Having clauses can be used interchangeably in SQL queries.
BE
18. Assertion(A): DBMS is an application package which arranges the data in orderly
E
19. Assertion(A): Aggregate function AVG() calculates the average of a set of values
and produces a single value as result.
Reason(R): The aggregate functions are used to perform some basic calculations
113 / 137
like sum, max, min, etc on a set of numbers.
20. Assertion(A): While inserting records in EMP table, value of DateOfBirth field
must be enclosed withing quotes ‘ ‘.
Reasoning(R): Date is represented as char / varchar always.
22. What do you mean by referential integrity? Explain with suitable example.
N
23. Write MySQL statement to create a table named REMEDIAL based on the
S,
following specification:
Table: REMEDIAL
Attribute Data type Constraints
W
FEES FLOAT
ADMN INT PRIMARY KEY
T
BE
ND
B002 SINDHU BADMINTON INDIA 59
a. Suggest the most suitable Primary Key. Justify your answer.
N
114 / 137
27. Categorize the following commands as DDL or DML:
INSERT, UPDATE, ALTER, DROP
28. A MySQL table, sales have 10 rows. The following queries were executed on
the sales table.
SELECT COUNT(*) FROM sales;
COUNT(*)
D
10
AV
(ii) select name, salary from employee where doj like '2015%';
(iii) select min(doj), max(dob) from employee;
T
32. Write output of the SQL queries based on the following tables Projects and
Employee:
BE
N
G
AL
ZO
N
E
115 / 137
33. Write SQL statements to do the following:
D
i. Define CID in CUSTOMER table as Foreign Key that refers to CID i.e.
AV
ii. Display the ‘CUSTOMER NAME’, ‘PRODUCT NAME’ who have purchased
IN
iii. Increase the QTY by 15 for the products with PRICE below 40,000.
34. Consider the GAMES table and answer the following questions:
IT
U
TI
O
ii. Suggest the most suitable column for Primary key of the above table. Give
S,
Quantity – numeric
BE
Abhay wants to do the following operations on the STORE table. Please help him
to do by writing appropriate SQL statements.
i. Insert the following record in the STORE table:
N
36. What do you mean b y CHECK constraint and DEFAULT constraint? Explain
ZO
116 / 137
D
AV
IN
ST
i. What will be the degree and cardinality of the resultant table after performing
Cartesian Product between PRODUCT and CLIENT?
IT
ii. What will be the degree and cardinality of the resultant table after performing
U
ii. Name the operator that can check for NULL value in a column.
iii. Name the SQL command to permanently save the changes caused by DML
W
40. i. Name the aggregate functions valid on a column of DATE data type.
ii. Suggest a keyword for renaming an attribute or a table in MySql.
iii. Write down the syntax of representing the common column CODE while
T
appropriate example.
G
ii. Consider the following table and find the output of the following queries:
AL
ZO
N
E
117 / 137
where TNAME not like ‘%Kumar’ group by SUBJECT;
42. i. Differentiate between DELETE and DROP in MySQL. Cite suitable examples.
CAR
U
show ___________ ;
W
ii. Display the values in TYPE column of the table CAR after removing the
duplicate values from the output.
ES
iii. Display MODEL, PRICE, COLOUR from CAR whose COLOUR is neither
T
118 / 137
CREATE _____(a)_____ DRESS
(
DCODE INT PRIMARY KEY,
DNAME VARCHAR(15),
COLOR VARCHAR(10) ____(b)____ ‘BLACK’,
PRICE DECIMAL(6, 2) _____(c)____ PRICE BETWEEN 0 and 8000
);
D
following queries:
IN
ST
IT
U
TI
O
N
GROUP BY ITEM_NAME;
WHERE ITEM.ID=CUSTOMER.ID;
ES
47. Consider the tables ITEM and CUSTOMER and write the queries:
N
G
AL
ZO
N
E
(i) Display the total PERIODS for each SUBJECT from SCHOOL table.
119 / 137
(ii) Display TEACHERNAME, GENDER from the tables SCHOOL and ADMIN
whose DESIGNATION is ‘COORDINATOR’.
Fee – Numeric
PayDate – Date
Primary Key – (Rollno, Class)
IT
(ii) Write the SQL statement to create Fees table in School database with the
above-mentioned specifications.
O
(iii) Write SQL statement to display all the table names in School database.
N
49. Consider the table Fees mentioned in Q. No. 48 and answer the following
S,
questions:
W
ii. Increase the second quarter fee of class 12th students by 50.
iii. Delete the record of student with Rollno-1212
T
iv. Aman wants to display the schema (structure) of Fees table. Which command
will he use from the following:
BE
50. Sagar, a cloth merchant creates a table CLIENT with a set of records to maintain
the client’s order volume in Qtr1, Qtr2, Qtr3 and their total. After creation of the
G
i. Write the statements to Update a record present in the table with data for
Qtr2 = 200, Qtr3 = 600 , total = sum of all Qtrs where the Client_ID is C660.
ii. Delete all records where total is between 500 to 900.
120 / 137
iii. Make changes in ClientName with data type varchar(20) and not null
constraint.
iv. Remove the column Total from the CLIENT table.
_________
SOLUTIONS
1. B 2. a 3. d 4. c 5. d
6. a 7. b 8. d 9. a 10. b
D
22. Foreign key of one table refers to the Primary key of another table.
23. CREATE TABLE REMEDIAL
ST
(
SNAME VARCHAR(20) NOT NULL,
ROLL INT(5) UNIQUE,
IT
FEES FLOAT(7,2),
ADMN INT(5) PRIMARY KEY
U
);
TI
return the number of records having not null values in the discount field of sales
table.
29. GROUP BY clause is used if statistical records of a table are to be displayed based
T
on a field. Groups are formed based on the number of different values in the
GROUP BY column present in the table.
BE
30. In Natural Join the common attribute between two tables appears only once. Where
as in Equi Join the common attribute appears as it is i.e. twice. Hence these
N
31. i.
AL
Name Project
Ranjan P01
Muneera P01
ZO
Alex P02
Akhtar P04
Satyansh P04
N
ii.
Name Salary
E
Ranjan 150000
Akhtar 125000
iii.
min(DOJ) max(DOB)
2015-01-21 1996-11-15
121 / 137
32. i.
Project count(*)
P01 2
P04 2
P02 1
ii.
D
iii.
avg(Salary)
IT
135000
U
TI
36. CHECK – Ensure that the attribute contains only permissible set of values.
G
SNAME VARCHAR(20),
LOCATION VARCHAR(15) DEFAULT ‘BANGALORE’,
PRICE FLOAT(7,2) CHECK (PRICE BETWEEN 0.00 AND 10000.00)
N
)
E
38. i. Aggregate functions perform calculation on a set of values, and returns a single
122 / 137
value. If used with GROUP BY clause, it returns one value for each group.
SUM() - returns the total sum of a numerical column
MAX() - returns the largest value within the selected column
ii. Yes. Then it returns a single value for the selected attribute by considering all the
records in that table.
39. i. NULL is said to be absence of any value in an attribute. NULL cannot participate
in any operation.
D
ii. IS
iii. COMMIT
AV
41. i. WHERE clause allows to filter data from individual rows of a table based on
ST
certain conditions. In contrast, the HAVING clause allows to filter data from a
group of rows in a query based on conditions involving aggregate functions.
IT
ii.
a)
U
SEX AVG(SALARY)
M 68666
TI
F 65000
O
b)
N
SUBJECT COUNT(*)
S,
Computer Science 2
c)
W
SUBJECT MIN(SALARY)
Computer Science 75000
ES
English 55000
Economics 71000
T
BE
42. i. DELETE is used for deleting records from a table. DROP is used to delete the
entire schema of any database object like table.
e.g. –
N
iii. not in
E
iv. count
v. as
44. i. Data integrity, data security
ii. Char data type stores data of fixed length, whereas the Varchar data type stores
variable length data. Varchar is preferable as it is more flexible for data of any size.
iii. It can represent 7 digit real number with 3 digits in the right of decimal point.
45. i. A self-join is a regular join, but the table is joined with itself.
123 / 137
SELECT * FROM EMP A, EMP B where A.ID = B.ID;
ii.
(a) TABLE
(b) DEFAULT
(c) CHECK
46. i.
ITEM_NAME MAX(PRICE) COUNT(*)
Personal Computer 37000 3
D
Laptop 57000 2
AV
ii.
CNAME MANUFACTURER
N Roy PQR
IN
R Singh XYZ
R Pandey COMP
ST
C Sharma PQR
K Agarwal ABC
IT
iii.
U
ITEM_NAME PRICE*100
TI
iv.
N
City
S,
Delhi
Mumbai
Bangalore
W
ES
DESC;
G
(
Rollno numeric(5),
Name varchar(20),
N
Class varchar(20),
E
Fee Numeric(7,2),
PayDate Date,
Primary Key(Rollno, Class)
);
iii. SHOW TABLES
49. i. INSERT INTO FEES VALUES(1201, ‘Akshay’, ‘12th', 350, ‘2019-06-24’);
ii. UPDATE TABLE FEES SET FEE = FEE+50 WHERE CLASS=’12th’;
124 / 137
iii. DELETE FROM FEES WHERE ROLLNO =1212;
iv. d) DESCRIBE
50. i. UPDATE CLIENT SET Qtr2 = 200, Qtr3 = 600, Total = Qtr1+Qtr2+Qtr3
WHERE Client_ID = ‘C660’;
ii. DELETE FROM CLIENT WHERE Total between 500 AND 900;
iii. ALTER TABLE CLIENT MODIFY ClientName VARCHAR(20) NOT NULL;
iv. ALTER TABLE CLIENT MODIFY DROP Total;
D
AV
A Python library - mysql connector is required which provides connectivity from Python to Mysql.
There are mainly six steps that must be followed in Python environment to create a database
connectivity application. Steps for Creating Database Connectivity Applications:-
W
4.
5. Extract data from result set or make the changes permanent.
BE
import mysql.connector
AL
2. connect() statement to create a connection to the Mysql server and returns a Mysql connection
object mydb and pass three parameters, if required then also pass database parameter.
ZO
mydb=mysql.connector.connect(host='localhost',user='root',passwd='password')
3. Creating cursor object of a class cursor which allows python code to execute sql commands.
N
mycursor=mydb.cursor()
E
4. execute() statement with sql query to execute SQL query from python.
mycursor.execute(“sql query”)
5. To read the data from the table of database using fetchone()/ fetchmany()/ fetchall() methods
as per requirement and store in a resulset.
125 / 137
myresult = mycursor.fetchall()
To save the current transactions of inserting, updating and deleting data we use:
mydb.commit()
6. close() to close the connection and clean up the environment
mydb.close()
D
AV
mycursor = mydb.cursor()
mycursor.execute("CREATE DATABASE mydatabase")
IT
U
import mysql.connector
O
mydb = mysql.connector.connect(host="localhost",user="john",password="john",
N
database="mydatabase")
S,
mycursor = mydb.cursor()
mycursor.execute("CREATE TABLE customers (name VARCHAR(255), address
W
VARCHAR(255))")
ES
import mysql.connector
BE
mycursor = mydb.cursor()
G
mydb.commit()
N
import mysql.connector
mydb = mysql.connector.connect(host="localhost",user="john", password="john",
database="mydatabase”)
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM customers")
126 / 137
myresult = mycursor.fetchall()
for x in myresult:
print(x)
mydb =
AV
mycursor = mydb.cursor()
ST
mydb.commit()
U
TI
import mysql.connector
N
database="mydatabase")
mycursor = mydb.cursor()
W
sql = "UPDATE customers SET address = 'Canyon 123' WHERE address = 'Valley 123'"
ES
mycursor.execute(sql)
mydb.commit()
T
BE
127 / 137
Mind Map – Python MySql Connectivity
D
AV
IN
ST
IT
U
TI
O
N
S,
1. To establish a connection with MySQL from Python which of the following functions is used?
(a) connection()
ES
(b) connect()
(c) open()
(d) cursor()
T
BE
3. To establish a connection between Python and sql database, connect() is used. Which of the
following arguments may not necessarily be given while calling connect()?
(a) host
ZO
(b) database
(c) user
(d) password
N
128 / 137
5. Which method is used to retrieve N number of records
(a) fetchone()
(b) fetchall()
(c) fetchmany()
(d) fetchN()
6. To make the changes made by any SQL Queries permanently in database, which function is used
after execution of the query?
D
(a) save()
AV
(b) commit()
(c) execute()
(d) dump()
IN
8. _______ it is a pointer or iterator which points towards the resultset of the SQL query.
TI
(a) cursor
(b) rset
O
(c) temp
N
9. To get all the records from result set, you may use ___________.
(a) cursor.fetchmany()
W
(b) cursor.fetchall()
(c) cursor.fetchone()
ES
(d) cursor.execute()
T
10. Which of the following is not a valid method to fetch records from database in python.
(a) fetchmany()
BE
(b) fetchone()
(c) fetchmulti()
N
(d) fetchall()
G
11. Which attribute of cursor is used to get number of records stored in cursor (Assumeg cursor
name is mycursor)?
AL
(a) mycursor.count
(b) mycursor.row_count
(c) mycursor.records
ZO
(d) mycursor.rowcount
12. Which of the following package must be imported in Python to create a database connectivity
N
application?
E
(a) mysql.connector
(b) mysql.connect
(c) sql.connector
(d) sql.execute
13. Which of the following method reflects the changes made in database permanently?
(a) <connection>.done()
129 / 137
(b) <connection>.final()
(c) <connection>.reflect()
(d) <connection>.commit()
14. Which method of cursor class is used to fetch limited rows from the table?
(a) cursor.fetchsize(SIZE)
(b) cursor.fetchmany(SIZE)
(c) cursor.fetchall(SIZE)
D
(d) cursor.fetchonly(SIZE)
AV
15. Which method of cursor class is used to get the number of rows affected after any of
the Insert/update/delete database operation executed from Python?
(a) cursor.rowcount
IN
(b) cursor.getaffectedcount
(c) cursor.rowscount
ST
(d) cursor.rcount
16. Which of the following component acts as a container to hold the data returned from the query:
IT
(a) table
U
(b) cursor
(c) resultset
TI
(d) container
O
17. To get the next record from the result set, we may use .
N
(a) cursor.fetch(next)
(b) cursor.fetchmany()
S,
(c) cursor.fetchall()
(d) cursor.fetchone()
W
18. SQL command is passed to which function to run after establishment of the connection
ES
(c) connection()
(d) fetchall()
BE
19. Which of the following function is used to close the connection between python and database?
(a) cursor.close()
N
(b) is.close()
G
(c) connection.close()
(d) execute.close()
AL
(a) Fetch the next row of a query result set, returning a single tuple, or None when no more data is
available
(b) Fetch the First row of a query result set, returning a single tuple, or None when no more data is
N
available
E
(c) Fetch the current row of a query result set, returning a single tuple, or None when no more data
is available
(d) None of the above
Ans:
1 (b)
2 (c)
130 / 137
3 (b)
4 (a)
5 (c)
6 (b)
7 (c)
8 (a)
9 (b)
(c)
D
10
11 (d)
AV
12 (a)
13 (d)
14 (b)
IN
15 (a)
16 (c)
ST
17 (d)
18 (b)
IT
19 (c)
20 (a)
U
TI
2 Marks Questions
O
1. Which method we use to establish the connection and clear the connection?
N
Ans: fetchone(): It will return one record from the result set.
fetchmany(n): It will return number of records as per value of n and by-default only one record.
T
python library, which is a MySQL driver written in Python. This library can be used to connect to a
MySQL database and perform various operations, such as creating and executing SQL queries.
N
Ans: A cursor is a pointer that points to a specific location in a database table. In MySQL,
cursors are used to iterate through the rows of a table and retrieve data from them.
AL
as they are made. This means that changes are immediately visible to other users and there is no
need to explicitly call the commit() method. Commit, on the other hand, is a database feature that
allows changes to be made to the database and then explicitly committed by the user. This allows
N
the user to control when changes are made visible to other users.
E
131 / 137
Ans: Use the close() method. db.close() closes the connection from the database, where db is
connection object.
Ans:A Connection (represented through a connection object) is the session between the application
program and the database. To do anything with database, one must have a connection object.
AV
3 Marks Questions
IN
Ans: A result set refers to a logical set of records that are fetched from the database by executing a
query and made available to the application-program.
IT
2. Which package must be imported in Python to create a database connectivity application? Give
TI
Ans:There are multiple packages available through which database connectivity applications
can be created in Python. One such package is mysql.connector.PyMySQL, mysqlclient, etc. can
N
(a) fetchone()
(b) rowcount
ES
(c) fetchall ()
Ans: (a) fetchone() :- The fetchone() method will return only one row from the result set in the
form of tuple containing a record.
T
(b) rowcount() :- cursor.rowcount that always return how many records have been retrieved
so for using any of the fetch..() methods.
BE
(c) fetchall() :- The fetchall() method return all the rows from the result set in the form of a
tuple congaing the records.
N
G
4. Write the python script to read the whole data from the table emp and display all the records.
AL
mycursor=mydb.cursor()
numrow=mycursor.execute("select * from student")
print(mycursor.fetchall())
N
mydb.close()
E
132 / 137
fetchall() fetches all the records or rows at a time from the table.
EMPNO – Integer
AV
ENAME – string
SALARY - Integer
BONUS - Integer
IN
DEPTID – string
ST
Help your friend Sonia in writing the following missing statements to complete the code:-
mydb=mysql.connector.connect(host="localhost",user="root",passwd='root',database="class12")
mycursor= _____________ # Statement 2
U
___________________ # Statement 3
print(mycursor.rowcount, "Record inserted")
O
___________________ # Statement 4
N
S,
Ans:
W
Statement 1: mysql.connector
Statement 2: mydb.cursor()
ES
Statement 3: mydb.commit()
Statement 4: mydb.close()
T
2. Avni is trying to connect Python with MySQL for her project. Help her to write the python
BE
Ans:
i. mysql.connector
ii. execute()
ZO
iii. commit()
iv. close()
N
E
3. 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 to write complete code:
import __________ as m # Statement-1
object1 = m.connect(host="localhost", user="root", password="root", database="Shop")
object2 = object1._________ # Statement-2
query = '''SELECT * FROM Products WHERE NAME LIKE "A%";'''
133 / 137
object2._________(query) # Statement-3
__________.close() # Statement-4
Ans:
Statement 1: mysql.connector
Statement 2: cursor()
Statement 3: execute()
D
Statement 4: object1
AV
4. The code given below reads the following record from Table named Employee and display those
record salary >= 30000 and <= 90000:
IN
Empno – integer
EName – string
ST
Desig – integer
Salary – integer
Note the following to establish connectivity between Python and MYSQL:
IT
Username is root
Password is Password
U
Write the following missing statements to complete the code on behalf of your friend Sandeep:
O
Statement 3 - to execute the query that extracts records of those Employees whose salary >=30000
S,
and <=90000.
Statement 4 - to close the connection.
import mysql.connector
W
mydb=mysql.connector.connect(host='localhost',user='root',passwd='Password',database='bank')
mycursor=_________________ # statement1
ES
mycursor.________________ #statement 2
data= __________________ # statement 3
T
for x in data:
print(x)
BE
______________ # statement 4
N
Ans:
G
Statement 1: mydb.cursor()
Statement 2: execute('''SELECT * FROM Employee WHERE salary >= 30000 and salary <=
AL
90000;''')
Statement 3: mycursor.fetchall()
Statement 4: mydb.close()
ZO
N
5. The code given below inserts the following record in the table Emp:
E
Empno – integer
EName – string
Designation – integer
Salary – integer
Bonus - Integer
Note the following to establish connectivity between Python and MYSQL:
134 / 137
Username is root
Password is tiger
The table exists in a MYSQL database named Employee.
The details (Empno, EName, Designation, Salary and Bonus) are to be accepted
from the user.
Help your friend in writing the following missing statements to complete the code:
Statement 1 – to create a connection
Statement 2 – to form the cursor object
D
Statement 3 – to execute the command that inserts the record in the table Emp.
Statement 4 - to add the record permanently in the database
AV
______________________ #Statement 2
______________________ # Statement 3
TI
Ans:
N
database="Employee")
Statement 2: con1.cursor()
W
Statement 3: mycursor.execute(querry)
Statement 4: con1.commit()
ES
5 Marks Questions
T
BE
1. Write the steps to perform an Insert query in database connectivity application. Table Student
values are rollno, name, age (10,’Ashok’,26).
N
G
135 / 137
mycursor.execute(" CREATE TABLE studentinfo (name VARCHAR (30), age INT(3)")
sql = """INSERT INTO studentinfo( name, age) VALUES ('Ashok',17) """
_____________________ #Statement 3
_____________________ #Statement 4
_____________________ #Statement 5
D
AV
iii) Write the python statement to insert the row into the table as statement 3 by using the string
‘sql’ given above.
ST
Ans:
TI
Statement 1: c
O
Statement 2: con.cursor()
Statement 3: mycursor.execute(sql)
N
Statement 3: mycursor.commit()
Statement 3: con.close()
S,
3. Write the python function to accept the name as parameter and find out whether record present
W
in the table or not. Table Student columns are rollno, name, age.
ES
database="school")
cur=mydb.cursor()
BE
if((k[1]==name)):
G
print("Record Found",k)
AL
break
_________________________________# statement 1
mydb = mycon.connect( host="localhost", user="yourusername", password="yourpassword",
N
database="mydatabase" )
mycursor = mydb.cursor()
E
136 / 137
for x in myresult:
print(x)
________.close() #statement 5
Ans:
Statement 1: import mysql.connector as mycon
Statement 2: mycursor.commit()
Statement 3: execute
D
Statement 4: mycursor.fetchall()
AV
Statement 5: mydb
mydb=_________(host="localhost",user="root",passwd='root',database="class12") #statement 1
mycursor=_____________ #statement 2
__________________("DELETE FROM EMPLOYEE WHERE EMPNO=114") # statement 3
IT
_______________ # statement 4
_______________ # statement 5
U
Ans:
TI
Statement 1: mysql.connector.connect
O
Statement 2 mydb.cursor()
Statement 3: mycursor.execute
N
Statement 4: mydb.commit()
S,
Statement 5: mydb.close()
W
ES
T
BE
N
G
AL
ZO
N
E
137 / 137