0% found this document useful (0 votes)
99 views162 pages

Class 12th_StudyMaterial 2023-24

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
99 views162 pages

Class 12th_StudyMaterial 2023-24

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 162

Revision Tour of python class XI

Basics of Python
Observe the program first then memorize the definitions:

Python keyword/ reserve words


Keywords are reserve words. Each keyword has a specific meaning to the Python interpreter, and we can use
a keyword in our program only for the purpose for which it has been defined. As Python is case sensitive,
keywords must be written exactly.

Identifiers
In programming languages, identifiers are names used to identify (Name) a variable, function, or other entities
in a program. The rules for naming an identifier in Python are as follows:
➔ The name should begin with an uppercase or a lowercase alphabet or an underscore sign (_).
➔ This may be followed by any combination of characters a–z, A–Z, 0–9 or underscore (_) Thus, an identifier
cannot start with a digit.
➔ It can be of any length. (However, it is preferred to keep it short and meaningful).
➔ It should not be a keyword or reserve word.
➔ We cannot use special symbols like !, @, #, $, %, etc., in identifiers.
Variables
A variable in a program is uniquely identified by a name (identifier). Variable in Python refers to an object —
an item or element that is stored in the memory. Value of a variable can be a string (e.g., ‘b’, ‘Global Citizen’),
numeric (e.g., 345) or any combination of alphanumeric characters (CD67). In Python we can use an
assignment statement to create new variables and assign specific values to them.

Comments
Comments are used to add a remark or a note in the source code. Comments are not executed by interpreter.
Comments in python can be created as:
➔ for single line comment use # (hash symbol)
➔ for multi line comment use ‘‘‘ text ’’’ (in triple quotes)
Data Types
Every value belongs to a specific data type in Python. Data type identifies the type of data values a variable
can hold and the operations that can be performed on that data.

Number
Number data type stores numerical values only. It is further classified into three different types: int,
float and complex.
Try the following statements on system in shell mode and observe the output:
num1 = 10 #(integer positive value )
type(num1)

num2 = -1210 #(integer negative value)


type(num2)

float1 = -1921.9 #(float1 variable contain decimal value so it contains float value)
type(float1)

float2 = -9.8*10**2 #(float2 variable contain decimal value so it contains float value)
print(float2, type(float2))

var2 = -3+7.2j #(var2 variable contain complex value)


print(var2, type(var2))

Boolean
var3= True # (var3 variable contain Boolean Value)
print(type(var3)) # print type Bool
Variables of simple data types like int, float, boolean, etc. hold single values. But such variables are not useful
to hold a long list of information, for example, names of the months in a year, names of students in a class,
names and numbers in a phone book or the list of artefacts in a museum. For this, Python provides data types
like tuples, lists, dictionaries and sets.
Sequences can used as datatype in python
A Python sequence is an ordered collection of items, where each item is indexed by an integer. The three
types of sequence data types available in Python are Strings, Lists and Tuples. A brief introduction to these
data types is as follows:
(A) String
String is a group of characters. These characters may be alphabets, digits or special characters including
spaces. String values are enclosed either in single quotation marks (e.g., ‘KV’) or in double quotation marks
(e.g., “Vidyalaya”). The quotes are not a part of the string, they are used to mark the beginning and end of the
string for the interpreter. For example:
Write your examples here:

Prove this statement using proper example: We cannot perform numerical operations on strings, even
when the string contains a numeric value.

(B) List
List is a sequence of items separated by commas and the items are enclosed in square brackets [ ]. In list we
can change the items so we can say it’s a mutable datatype
#To create a list
list1 = [5, 3.4, "New Delhi", "20C", 45]
print(list1) # printing the elements of list1
Output: [5, 3.4, 'New Delhi', '20C', 45]
(C) Tuple
Tuple is a sequence of items separated by commas and items are enclosed in parenthesis ( ).Once created,
we cannot change the tuple (Records cannot be changed) – i.e. we can say immutable datatype.
Tuple can be defined as
T=5,
T=(5,)
T=5,6,7,8
T= ‘a’,’b’,’c’,5,6,7
T=(5,6,’r’,’s’,’wel’)

#create a tuple tuple1


tuple1 = (10, 20, "KV", 5.5, 'a')
print(tuple1) #printing the elements of the tuple tuple1
Output: (10, 20, "KV", 5.5, 'a')

(D) Dictionary
Dictionary in Python holds data items in key : value pairs. Items in a dictionary are enclosed in curly braces {
}. Every key is separated from its value using a colon (:) sign. The key : value pairs of a dictionary can be
accessed using the key. The keys are usually strings and their values can be any data type. In order to access
any value in the dictionary, we have to specify its key in square brackets [ ].
#create a dictionary
dict1 = {'Fruit':'Apple', 1:'Monday', 'Price Rs':120}
print(dict1)
output: {'Fruit': 'Apple', 1: ‘Monday’,'Price Rs': 120}
print(dict1['Price Rs'])
output: 120
print(dict1[1])
output:’Monday’
(E) None
None is a special data type with a single value. It is used to signify the absence of value in a situation. None
supports no special operations, and it is neither False nor 0 (zero).
myVar = None
print(type(myVar))
<class 'NoneType'>
print(myVar)

Mutable and Immutable Data Types


Variables whose values can be changed after they are created and assigned without changing their memory
location are called mutable. Variables whose values cannot be changed after they are created and assigned
or upon changing values their memory location is changed, are called immutable. When an attempt is made
to update the value of an immutable variable, the old variable is destroyed and a new variable is created by
the same name in new memory location.
Exercise: Define a variable by assigning a value, find and note its ID, change the value and again find its ID,
now observe the difference and do it for different data types.
Precedence of Operators
Evaluation of the expression is based on precedence of operators. When an expression contains different
kinds of operators, precedence determines which operator should be applied first. Higher precedence
operator is evaluated before the lower precedence operator. (Simply apply BODMAS rules)
Order of Precedence (higher to lower)
1 ** Exponentiation (raised to the power)
2 ~ ,+, - Complement, unary plus and unary minus
3 * ,/, %, // Multiply, divide, modulo and floor division
4 +, - Addition and subtraction
5 <= ,< ,> ,>= Relational operators
6 == ,!= Equality operators
7 =, %=, /=, //=, -=, +=, *=, **= Assignment operators
8 is is not Identity operators
9 in, not in Membership operators
10 not, and, or Logical operators

* For operators with equal precedence, the expression is evaluated from left to right except ** which is executed from right to
left.
Flow of Control
Selection

The if statement has following syntaxes:


1)
if condition:
statement(s)

2)
if condition:
statement(s)
else:
statement(s)

3)
if condition:
statement(s)
elif condition:
statement(s)
elif condition:
statement(s)
else:
statement(s)

NOTE
Indentation
Python uses indentation for block as well as for nested block structures. Leading whitespace (spaces and tabs)
at the beginning of a statement is called indentation. In Python, the same level of indentation associates
statements into a single block of code. The interpreter checks indentation levels very strictly and throws up
syntax errors if indentation is not correct. It is a common practice to use a single tab for each level of
indentation.
Repetition
Repetition of a set of statements in a program is made possible using looping constructs.
The ‘for’ Loop
The for statement is used to iterate over a range of values or a sequence. The for loop is executed for each of
the items in the range. These values can be either numeric, or they can be elements of a data type like a string,
list, tuple or even dictionary.
Syntax of the for Loop
for <control-variable> in <sequence/ items in range>:
<statements inside body of the loop>
The ‘while’ Loop
The while statement executes a block of code repeatedly as long as the control condition of the loop is true.
The control condition of the while loop is executed before any statement inside the loop is executed. After
each iteration, the control condition is tested again and the loop continues as long as the condition remains
true. When this condition becomes false, the statements in the body of loop are not executed and the control
is transferred to the statement immediately following the body of while loop. If the condition of the while
loop is initially false, the body is not executed even once.
Syntax of while Loop
while test_condition:
body of while

Break and Continue Statement


In certain situations, when some particular condition occurs, we may want to exit from a loop (come out of
the loop forever) or skip some statements of the loop before continuing further in the loop. These
requirements can be achieved by using break and continue statements, respectively.

while <condition>: for <var> in <sequence>:


statement 1 statement 1
if <condition>: if <condition>:
break break
statement 2 statement 2
statement 3 statement 3
statement 4 statement 4
statement 5 statement 5

STRINGS IN PYTHON
Python strings are characters enclosed in quotes of any type – single quotation marks, double quotation marks and
triple quotation marks. An empty string is a string that has 0 characters. Python strings are immutable.
Strings are sequence of characters, where each character has a unique position-id/index. The indexes of a string
begin from 0 to (length -1) in forward direction and -1,-2,-3,….,-length in backward direction.
STRING SLICES
In Python, the term ‘string slice’ refers to a part of the string, where strings are sliced using a range of indices. That
is, for a string say name, if we give name[n:m] where n and m are integers and legal indices, Python will return a
slice of the string by returning the characters falling between indices n and m starting at n, n+1, n+2, … till m-1.
0 1 2 3 4 5 6
word a m a z i n g
-7 -6 -5 -4 -3 -2 -1
Then,
word[0:7] will give ‘amazing’
word[0:3] will give ‘ama’
word[2:5] will give ‘azi’
word[-7:-3] will give ‘amaz’
word[-5:-1] will give ‘azin’
In a string slice, you give the slicing range in the form [<begin-index>:<last>]. If, however, you skip of the begin-
index or last, Python will consider the limits of the string, i.e., for missing begin index, it will consider 0 (the first
index) and for mission last value, it will consider length of the string. Consider the following examples to understand
this:
word[:7] will give ‘amazing’
word[:5] will give ‘amazi’
word[3:] will give ‘zing’
word[5:] will give ‘ng’
Note: Using the same string slicing technique, you will find that for any index n, s[:n]+s[n:] will give you original
string s.
STRING FUNCTIONS AND METHODS
Every string object that you create in Python is actually an instance of String class. The string manipulation methods
that are being discussed below can be applied to string as per following syntax:
<stringObject>.<methodname>()
1. string.capitalize(): Returns a copy of the string with its first character capitalized
Exmple: ‘true’.capitalize() will return ‘True’
‘i love my India’.capitalize() will return ‘I love my India’
2. string.title(): Returns a copy of the string with first character of each work capitalized.
Example: ‘true’.title() will return ‘True’
‘i love my india’.capitalize() will return ‘I Love My India’
3. string.upper(): Returns a copy of the string converted to uppercase. Examples:
string.upper() will return ‘HELLO’
string2.upper() will return ‘THERE’
string3.upper() will return ‘GOLDY’
4. string.lower(): Returns a copy of the string converted to lowercase. Examples:
string.lower() will return ‘hello’
string2.lower() will return ‘there’
string3.lower() will return ‘goldy’
5. string.count(str): Returns the count of an string in the given string. Examples:
‘I love my india’.count(‘i’) will return 2
‘it goes as – ringa ringa roses’.count(‘ringa’) will return 2
6. string.find(sub[,start,end]): Returns the lowest index in the string where the substring sub is found within the
slice range of start and end. Returns -1 if sub is not found. Example:
string = ‘it goes as – ringa ringa roses’
sub = ‘ringa’
string.find(sub) will return 13
string.find(sub,15,22) will return -1
string.find(sub,15,25) will return 19
7. string.index(str): Returns the lowest index in the sting where the substring is found. Example:
‘I love my India’.index(‘o) will return 3
‘I love my India’.index(‘my’) will return 7
8. string.isalnum(): Returns True if the characters in the string are alphanumeric (alphabets or numbers) and
there is at least one character, False otherwise. Example:
string =”abc123”
string2 = ‘hello’
string3 = ‘12345’
string4 = ‘ ’
string.isalnum() will return True
string2.isalnum() will return True
string3.isalnum() will return True
string4.isalnum() will return False
9. string.islower(): Returns True if all cased characters in the string are lowercase. Examples:
string = ‘hello’
string2 = ‘THERE’
string3 = ‘Goldy’
string.islower() will return True
string2.islower() will return False
string3.islower() will return False
10. string.isupper(): Returns True if all cased characters in the string are uppercase. Examples:
string.isupper() will return False
string2.isupper() will return True
string3.isupper() will return False
11. string.isspace(): Returns True if there are only whitespace characters in the string. Examples:
string = “ “
string2 = “”
string.isspace() will return True
string2.isspace() will return False
12. string.isalpha(): Returns True if all characters in the string are alphabetic and there is at least one character,
False otherwise. Example:
string.isalpha() will return False
string2.isalpha() will return True
string3.isalpha() will return False
13. string.isdigit(): Returns True if all the characters in the string are digits. There must be at least one character,
otherwise it returns False. Example:
string.isdigit() will return False
string2.isdigit() will return False
string3.isdigit() will return True
14. string.split([<sep>]): This function splits the string to form a list of strings.
If we do not provide any argument to split then by default it will split the given string considering whitespace as
a separator, e.g.,
“I Love Python”.split() will give [‘I’, ‘Love’, ‘Python’]
If we provide a string or a character as an argument to split(), then the given string is divided into parts
considering the given string/character as separator and separator character is not included in the split strings,
e.g.,
“I Love Python”.split(‘o’) will give [‘I L’, ’ve Pyth’, ’n’]
15. string.partition(<sep>): The partition() method searches for a specified string, and splits the string into a tuple
containing three elements. The first element contains the part before the specified string. The second element
contains the specified string. The third element contains the part after the string.
Example: ‘I Love my India’.partition(‘my’) will give (‘I Love ’, ‘my’, ‘ India’)
16. string.lstrip([chars]): Returns a copy of the string with leading characters removed.
If used without any argument, it removes the leading whitespaces.
One can use optional chars argument to specify a set of characters to be removed.
The chars argument is not a prefix; rather, all combinations of its values (all possible substrings from the given
string argument chars) are stripped when they lead the string.
Examples:
string = “hello”
string.lstrip() will return ‘hello’
string2 = ‘There’
string2.lstrip(‘the’) will return ‘There’
string2.lstrip(‘The’) will return ‘re’
string2.lstrip(‘he’) will return ‘There’
string2.lstirp(‘Te’) will return ‘here’
string2.lstrip(‘Teh’) will return ‘re’
string2.lstrip(‘heT’) will return ‘re’
“saregamapadhanisa”.lstrip(“tears”) will return ‘gamapadhanisa’
“saregamapadhanisa”.lstrip(“races”) will return ‘gamapadhanisa’
17. string.rstrip([chars]): Returns a copy of the string with trailing characters removed.
If used without any argument, it removes the trailing whitespaces.
The chars argument is a string specifying the set of characters to be removed.
The chars argument is not a suffix; rather, all combinations of its values are stripped.
Examples:
string = ‘hello’
string.rstrip() will return ‘hello’
string2 = ‘There’
string2.rstripe(‘ere’) will return ‘Th’
string2.rstrip(‘care’) will return ‘Th’

string2.rstrip(‘car’) will return ‘there’


“saregamapadhanisa”.rstrip(“tears”) will return “saregamapadhani”
“saregamapadhanisa”.rstrip(“races”) will return “saregamapadhani”
18. string.strip([chars]): Returns a copy of the string with both leading and trailing characters removed.
If used without any argument, it removes leading and trailing whitespaces.
The chars argument is a string specifying the set of characters to be removed.
The chars argument is not a suffix; rather, all combinations of its values are stripped.
Examples:
string = ‘ hello ‘
string.strip() will return ‘hello’
string2=’xxThis is a stringxx’
string2.strip(‘x’) will return ‘This is a string’
19. <str>.replace(<old string>,<new string>): This functions replaces all occurrences of <old string> with <new
string> in the given string, e.g.,
“I Love Python”.replace(“Python”,”Programming”) will give ‘I Love Programming’
20. len(string): One more function that you have used with string is len() function which gives you the length of
the string as the count of characters contained in it. Recall that you use it as: len(<string>)
For example,
string=’hello’
len(string) will return 5
LISTS IN PYTHON
The Python lists are containers that are used to store a list of values of any type. Python lists are mutable i.e., you
can change the elements of a list in place. Which means Python will not create a fresh list when you make changes
to an element of a list. List is a type of sequence like strings and tuples.
Difference from Strings
You cannot change individual elements of a string in place, but Lists allow you to do so. That is, following statement
is fully valid for Lists:
L[i] = <element>
For example, consider the same vowels list crated above. Now if you want to change some of these vowels, you may
write something as show below:
vowels[0] = ‘A’
print(vowels)
[‘A’,’e’,’i',’o’,’u’]
List Functions
1. len() function
This function returns the length of a list i.e. this function returns number of elements present in the list. It is
used as per following format:
len(<list>)
For example for a list L1 = [13,18,11,16,18,14]
len(L1) will return 6
2. list() function
This function converts the passed argument to a list. The passed argument could be a string, a list or even a
tuple. It is used as per following format:
list(<argument>)
For example for a string s = “Computer”
list(s) will return [‘C’, ‘o’, ‘m’, ‘p’, ‘u’, ‘t’, ‘e’, ‘r’]
3. The append() function
The append() function adds an item to the end of the list. It works as per following syntax:
List.append(<item>)
For example, to add a new item “yellow” to a list containing colours, you may write:
colours =[“red”,”green”,”blue”]
colours.append(“yellow”)
print(colours)
[“red”,”green”,”blue”,”yellow”]
4. The extend() function
The extend() method is also used for adding multiple elements (given in the form of a list) to a list. The
extend() function works as per following format:
List.extend(<list>)
That is extend() takes a list as an argument and appends all of the elements of the argument list to the list
object on which extend() is applied. Consider following example:
t1=[‘a’,’b’,’c’]
t2=[‘d’,’e’]
t1.extend(t2)
print(t1)
[‘a’,’b’,’c’,’d’,’e’]
print(t2)
[‘d’,’e’]
5. The insert() function
If you want to insert an element somewhere in between or any position of your choice, both append() and
extend()are of no use. For such a requirement insert() is used.
The insert() function inserts an item at a given position. It is used as per following syntax:
List.insert(<pos>,<item>)
The first argument <pos> is the index of the element before which the second argument <item> to be added.
Consider the following example:
t1=[‘a’,’e’,’u’]
t1.insert(2,’i')
print(t1)
[‘a,’e’,’i',’u’]
For function insert(), we can say that:
list.insert(0,x) will insert element x at the front of the list i.e. at index 0.
list.insert(len(list),x) will insert element x at the end of the list i.e. index equal to length of the list
6. The count() function
This function returns the count of the item that you passed as argument. If the given item is not in the list, it
returns zero. It is used as per following format:
List.count(<item>)
For instance:
L1 = [13,18,20,10,18,23]
print(L1.count(18))
2
print(L1.count(28))
0
7. The Index() function
This function returns the index of first matched item from the list. It is used as per following format:
List.index(<item>)
For example, for a list L1 = [13,18,11,16,18,14]
print(L1.index(18))
1
However, if the given item is not in the list, it raises exception ValueError.
8. The remove() function
The remove() method removes the first occurrence of given item from the list. It is used as per following format:
List.remove(<value>)
The remove() will report an error if there is no such item in the list. Consider the example:
t1=[‘a’,’e’,’i',’p’,’q’,’a’,’q’,’p’]
t1.remove(‘a’)
print(t1)
[’e’,’i',’p’,’q’,’a’,’q’,’p’]
t1.remove(‘p’)
print(t1)
[’e’,’i',’q’,’a’,’q’,’p’]
print(t1.remove(‘k’))
ValueError
9. The pop() method
The pop() is used to remove the item from the list. It is used as per the following syntax:
List.pop(<index>)
Thus, pop() removes an element from the given position in the list, and return it. If no index is specified,
pop() removes and returns the last item in the list.
t1 = [‘k’,’a’,’i',’p’,’q’,’u’]
ele = t1.pop(0)
print(ele)
‘k’
10. The reverse() function
The reverse() reverses the item of the list. This is done “in place” i.e. id does not create a new list. The
syntax to use reverse method is:
List.reverse()
For example:
t1 = [‘e’,’i',’q’,’a’,’q’,’p’]
t1.reverse()
print(t1)
[‘p’,’q’,’a’,’q’,’i',’e’]
11. The sort() function
The sort() function sorts the items of the list, by default in increasing order. This is done “in place” i.e. it
does not create a new list. It is used as per following syntax:
List.sort()
For example:
t1 = [‘e’,’i',’q’,’a’,’q’,’p’]
t1.sort()
print(t1)
[‘a’,’e’,’i',’p’,’q’,’q’]
To sort a lit in decreasing order using sort(), you can write:
List.sort(reverse=True)
12. min() function
This function returns the minimum value present in the list. This function will work only if all elements of the list
are numbers or strings. This function gives the minimum value from a given list. Strings are compared using
its ordinal values/Unicode values. This function is used as per following format:
min(<list>)
For example L1 = [13,18,11,16,18,14] and L2 = [‘a’, ‘e’ ‘i', ‘o’ ,’U’] then
min(L1) will return 11 and min(L2) will return ‘U’
13. max() function
This function returns the maximum value present in the list. This function will work only if all elements of the list
are numbers or strings. This function gives the maximum value from a given list. Strings are compared using
its ordinal values/Unicode values. This function is used as per following format:
max(<list>)
For example L1 = [13,18,11,16,18,14] and L2 = [‘a’, ‘e’ ‘i', ‘o’ ,’U’] then
max(L1) will return 18 and max(L2) will return ‘o’
14. sum() function
This function returns the total of values present in the list. This function will work only if all elements of the list
are numbers. This function gives the total of all values from a given list. This function is used as per
following format:
sum(<list>)
For example L1=[13,18,11,16,18,14] then sum(L1) will return 90
15. The clear() function
This method removes all the items from the list and the list becomes empty list after this function. This function
returns nothing. It is used as per following format:
List.clear()
For instance:
L1=[2,3,4,5]
L1.clear()
print(L1)
[]

Introduction to Python Tuples


Python tuples are immutable i.e. you cannot change the elements of a tuple in place; Python will create a fresh tuple
when you make changes to an element of a tuple.
Unpacking Tuples
Creating a tuple from a set of values is called packing and its reverse i.e., creating individual values from a tuple’s
element is called unpacking.
Unpacking is done as per syntax:
<variable1>,<variable2>,<variable3>,…. = t
where the number of variables in the left side of assignment must match the number of elements in the tuple. For
example, if we have a tuple as:
t = (1, 2, ‘A’, ‘B’)
The length of above tuple t is 4 as there are four elements in it. Now to unpack it, we can write
w,x,y,z = t
Python will now assign each of the elements of tuple t to the variables on the left side of assignment operator. That
is, you can now individually print the values of these variables somewhat like:
print(w)
print(x)
print(y)
print(z)
The above code will yield the result as
1
2
‘A’
‘B’
Tuple functions
1. The len() funtion
This method returns length of tuple i.e. the count of elements in the tuple. Its syntax is:
len(<tuple>)
For example:
emp = (‘John’, 10000, 24, ‘Sales’)
print(len(emp))
4
2. The max() function
This method returns the element from the tuple having maximum value. Its syntax is:
max(<tuple>)
Example:
tp1 = (10,12,14,20,22,24,30,32,34,-2)
print(max(tp1))
34
tp2 = (“Karan”, “Zubin”, “Zara”, “Ana”)
print(max(tp2))
Zubin
Please note that max() applied on sequences like tuples/lists etc. will return a maximum value ONLY IF the
sequence contains values of same type.
3. The min() function
This method returns the element from the tuple having minimum value. Its syntax is:
min(<tuple>)
Example:
tp1 = (10,12,14,20,22,24,30,32,34,-2)
print(min(tp1))
-2
tp2 =(“Karan”, “Zubin”, “Zara”, “Ana”)
print(min(tp2))
Ana
Like max(), for min() to work, the element of tuple should be of same type.
4. The index() function
The index() works with tuples in the same way it works with lists. That is, it returns the index of an existing
element of a tuple. It is used as:
<tuplename>.index(<item>)
Example:
t1 =(3,4,5,6.0)
print(t1.index(5))
2
5. The count() function
The count() method returns the count of a member element/object in a given sequence (list/tuple). You can
use the count() function as per following syntax:
<sequence name>.count(<object>).
Example:
t1=(2,4,2,5,7,4,8,9,9,11,7,2)
print(t1.count(2))
3
t1.count(7)
2
For an element not in tuple, it returns 0.
6. The tuple() function
This method is actually constructor method that can be used to crate tuples from different types of values. Syntax:
tuple(<sequence>)
Example:
a. Creating empty tuple
>>>tuple()
()
b. Creating a tuple from a string
t = tuple(“abc”)
print(t)
(‘a’,’b’,’c’)
c. Creating a tuple from a list
t = tuple([1,2,3])
print(t)
(1,2,3)
d. Creating a tuple from keys of a dictionary
t1 = tuple({1:”1”, 2:”2”})
print(t1)
(1,2)
7. The sorted() function
This function is used to take a tuple as argument and converts this tuple to a sorted list. It has another argument
called reverse. If reverse is set to True then tuple is sorted in descending order otherwise tuple will be sorted
in ascending order. Syntax:
sorted(<tuple>[,reverse = True])
t1 =(3,4,5,6,0)
print(sorted(t1))
[0, 3, 4, 5, 6]
print(sorted(t1, reverse = True))
[6, 5, 4, 3, 0]
Indirectly Modifying Tuples
(a) Using Tuple Unpacking
Tuples are immutable. To change a tuple, we would need to first unpack it, change the values, and then
again repack it:
tp1 = (11,33,66,99)
1. First unpack the tuple
a,b,c,d = tp1
2. Redefine or change desired variable say, c
c=77
3. Now repack the tuple with changed value
tp1 = (a,b,c,d)
(b) Using the constructor functions of lists and tuples i.e., list() and tuple()
There is another way of doing the same as explained below:
tp1 = (“Anand”,35000,35,”Admin”)
1. Convert the tuple to list using list():
lst = list(tp1)
2. Make changes in the desired element in the list
lst[1] = 45000
3. Create a tuple from the modified list with tuple()
tp1 = tuple(lst)

Dictionary
Dictionaries are mutable unordered collections with elements in the form of a {key:value pairs that associate keys to
values.
Characteristics of a Dictionary
1. Unordered Set: A dictionary is a unordered set of key:value pairs. Its values can contain references to any
type of object.
2. Not a sequence: Unlike a string, list and tuple, a dictionary is not a sequence because it is unordered set of
elements.
3. Indexed by Keys, Not Numbers: Dictionaries are indexed by keys and not by any index like in sequences.
4. Keys must be unique: Each of the keys within a dictionary must be unique. Since keys are used to identify
values in a dictionary, there cannot be duplicate keys in a dictionary. However, two unique keys can have
same values, e.g. consider the BirdCount dictionary here:
BirdCount = {“Finch”:10, “Myna”:13, “Parakeet”:16, “Hornbill”:15, “Peacock”:15}
5. Mutuable: Like lists, dictionaries are also mutable. We can change the value of a certain key “in place” using
the assignment as per syntax:
<dictionary>[<key>] = <value>
For example,
>>>dict1[“3”]
“Yamuna”
>>>dict1[“3”] = “Ganga”
>>>dict1[“3”]
‘Ganga’
6. Internally stored as Mappings: Internally, the key:value pairs of a dictionary are associated with one another
with some internal function (called hash function).this way of linking is called mapping.
Dictionary functions
1. The len() function
This method returns length of the dictionary, i.e., the count of elements (key:value pairs) in the dictionary. The
syntax to use this method is given below:
len(<dictionary>)
For example:
Employee = {‘name’:’John’, ‘salary’:10000, ‘age’:24}
print(len(Employee))
3
2. The clear() function
This method removes all items from the dictionary and the dictionary becomes empty dictionary. The syntax to
use this method is given below:
<dictionary>.clear()
Example:
Employee = {‘name’:’John’, ‘salary’:10000, ‘age’:24}
Employee.clear()
print(Employee)
{}
3. The get() function
With this method, you can get the item with the given key, similar to dictionary[key], If the key is not present
Python by default gives error, but you can specify your own message through default argument as per following
syntax:
<dictionary>.get(<key>,[default])
Example:
Employee = {‘name’:’John’, ‘salary’:10000, ‘age’:24, ‘dept’:’Sales’}
print(Employee.get(‘dept’))
Sales
print(Employee.get(‘designation’))
NameError:name ‘designation’ is not defined
>>>Employee.get(‘designation’, “Error! Key not found”)
Error! Key not found
4. The items() function
This function returns all of the items in the dictionary as a sequence of (key, value) tuples. Note that these
are returned in no particular order
<dictionary>.items()
Example:
Employee = {‘name’:’John’, ‘salary’:10000, ‘age’:24}
myList = employee.items()
for x in myList:
print(x)
The output of the above code will be like:
(‘salary’, 10000)
(‘age’, 24)
(‘name’, ‘John’)
5. The keys() method
This method returns all of the keys in the dictionary as a sequence of keys in form of a list. Syntax to use this
method is:
<dictionary>.keys()
Example:
Employee = {‘name’:’John’, ‘salary’:10000, ‘age’:24}
print(Employee.keys())
[‘salary’,’age’,’name’]
6. The values() function
This method returns all the values from the dictionary as a list. The syntax to use this method is given below:
<dictionary>.values()
Example
Employee = {‘name’:’John’, ‘salary’:10000, ‘age’:24}
print(Employee.values())
[‘Jhon’,10000,24,]
7. The update() function
This function merges key:value pairs from the new dictionary into the original dictionary, adding or replacing as
needed. The items in the new dictionary are added to the old one and override(overwrite) any item already
there with the same keys. The syntax to use this method is given below:
<dictionary>.update(<other-dictionary>)
Example:
Employee1 = {‘name’:’John’, ‘salary’:10000, ‘age’:24}
Employee2 = {‘name’:’Diya’, ‘salary’:54000, ‘dept’:’Sales’}
Employee1.update(Employee2)
print(Employee1)
{‘salary’:54000, ‘dept’:’Sales’, ‘name’:’Diya’, ‘age’:24}
8. The fromkeys() function
This method creates a dictionary from the given sequence of keys and a value. It assigns same value for all
keys. If value is not given then it assigns None as the value of all keys. Its syntax is:
<dict-var> = dict.fromkeys(<key-sequence> [,<value>])
For example:
month = [‘Jan’, ‘Mar’, ‘May’]
d1 = dict.fromkeys(month, 31)
print(d1)
will give us:
{'Jan': 31, 'Mar': 31, 'May': 31}
and
d2 = dict.fromkeys(month)
print(d2)
will give us:
{'Jan': None, 'Mar': None, 'May': None}
9. The copy() function
This method creates a copy of the dictionary. This method does not make any change in the original dictionary.
It only makes a copy of this dictionary. Its syntax is:
<dict-var> = <original-dict>.copy()
For example:
d1 = {‘Jan’:31, ‘Feb’:28, ‘Mar’:31}
d2 = d1.copy()
print(d2)
will give us:
{‘Jan’:31, ‘Feb’:28, ‘Mar’:31}
10. The pop() function
Like lists pop() method removes an element from a dictionary. This method removes a key:value pair from the
dictionary and returns the value removed. For this a key need to be specified. This method also has an
optional argument for default value if the key is not present in the dictionary. Its syntax is:
<dict>.pop(<key>[,<default-value>])
d1 = {‘Jan’:31, ‘Feb’:28, ‘Mar’:31}
print(d1.pop(‘Jan’))
31
d1.pop(‘Jul’,”Element not present”)
Element not present
11. The popitem() function
In Python 3.7 and higher version this method of dictionary removes the last inserted key:value pair from the
dictionary and return it as a tuple. Its syntax is:
<dict>.popitem()
For example:
d1 = {‘Jan’:31, ‘Feb’:28, ‘Mar’:31}
print(d1.popitem())
(‘Mar’, 31)
12. The setdefault() method
This method of dictionary takes two arguments key and default-value. If key is found in the dictionary then it
returns its corresponding value. If key is not found in the dictionary then it inserts the default-value with key
in the dictionary and returns default-value. If default-value is not given then None is inserted as default-
value of the key and returns nothing. Its syntax is:
<dict>.setdefault(<key>[,<default-value>])
For example:
>>>d1={'Jan':31, 'Feb':28, 'Mar':31}
>>>d1.setdefault('Jan')
31
>>>d1.setdefault('Apr',30)
30
>>>d1.setdefault('May')
>>>d1
{'Jan': 31, 'Feb': 28, 'Mar': 31, 'Apr': 30, 'May': None}
13. The max() function
This function when applied with dictionary returns the maximum key value of all keys of dictionary.
For example:
d1={'Jan':31, 'Feb':28, 'Mar':31}
print(max(d1))
‘Mar’
14. The min() function
This function when applied with dictionary returns the smallest key value of all keys of dictionary.
For example:
d1={'Jan':31, 'Feb':28, 'Mar':31}
print(min(d1))
‘Feb’
15. The sorted() function
This function returns the keys of the dictionary in ascending order in the form of a list.
For example:
d1={'Jan':31, 'Feb':28, 'Mar':31}
sorted(d1)
['Feb', 'Jan', 'Mar']
For getting result in descending order use reverse=True with sorted() function.
sorted(d1,reverse=True)
['Mar', 'Jan', 'Feb']
Functions
Definition: Function is a named sequence of statements used to perform specific task when it is invoked.
Functions may or may not return value. It contains statements, which are sequentially executed from top to
bottom by python Interpreter. Once defined, a function can be called repeatedly from different places of the
program without writing same code of that function every time, or it can be called from inside another
function, by simply writing the name of the function and passing the required parameters, if any

Advantages of Using a Function


1) Use of functions enhances the readability of a program.
2) A big code is always difficult to read. Breaking the code in smaller parts called
Functions, keeps the program organized, easy to understand and makes it reusable.
3) Functions are used to achieve modularity and reusability.

Python Functions can be divided into three categories:


1. Functions in Modules
2. Build-in Functions
3. User Defined Functions
1) Fuynctions in Modules
Module is a file containing python functions and statements. Standard library of python is prolonged as
module(s). We can use these modules in our python code, for this, a programmer needs to import the
module.
There are 2 ways to import modules:-
i) By using import
It is simple & most commonly used way to use modules in python code.
Syntax:-
import modulename1 [, modulename2,…….]
Example:-
>>> import math
On execution of import math statement, python will-
a) Search ‘math.py’ file in library
b) Space is allocated for module definition & variable creation
c) Statements are executed in the module
Example:-Write python statements in Interactive mode to find square root of 25
>>> import math
>>>v=math.sqrt (25)
In above example 5.0 will be stored in v
ii) By using from
It is used to get a specific function instead of the complete module file. If we know beforehand which
function(s), we will need in code, then we may use from. For modules having large number of functions, it is
recommended to use from instead of import.
Syntax :-
>>> from modulename import functionname [, functionname…..]
Example
>>> from math import sqrt
>>> sqrt(25)
Output: 5.0
Here, we are importing sqrt() function only, instead of the complete math module.
We can also use
from modulename import *
will import everything from the file.
Python standard Library
1) math module
We can use following functions as it is in python code that are available in math module
Name of the function Description Example
math.ceil( x ) It returns the smallest math.ceil(4.6)
5
integer not less than x,
math.ceil(-3.1)
where x is a numeric -3
math.ceil(3.3)
expression.
4
Or in short it returns next higher
integer
math.floor( x ) It returns the largest math.floor(4.6)
4
integer not greater than x,
math. floor (3.1)
where x is a numeric -4
expression.
Or in short it returns previous
lower integer
math.fabs( x ) It returns the absolute math.fabs(- 5.17)
value of x, where x is a 5.17
numeric value. math.fabs(10.12)
10.12
math.fabs(1.72)
1.72
math.pow( x, y ) It returns the value of (x)y, math.pow(3, 2)
where x and y are numeric 9.0
expressions. math.pow(2, 0)
1.0
math.pow(2, 4)
16.0
math.sqrt (x ) It returns the square root math.sqrt(100)
of x for x > 0, where x is a 10.0
numeric expression. math.sqrt(36)
6.0
pi pi is a constant provided by math >>>math.pi
module. It gives the value of π in 3.141592653589793
float form with 15 digits after
decimal point.
e e is a constant provided by math >>>math.e
module. It gives the value of 2.718281828459045
Euler’s number in float form with
15 digits after decimal point.
sin(<radian>) This method returns the sine of >>>x=math.pi/3
value passed to it. Value to be >>>math.sin(x)
passed need to be given in radians 0.8660254037844386
and value returned will always be
in float.
cos(<radian>) This method returns the cosine of >>>x=math.pi/3
value passed to it. Value to be >>>math.cos(x)
passed need to be given in radians 0.5000000000000001
and value returned will always be
in float
tan(<radian>) This method returns the tangent >>>x=math.pi/3
of value passed to it. Value to be >>>math.tan(x)
passed need to be given in radians 1.7320508075688767
and value returned will always be
in float.

Some functions from random module:


Name of the function Description Example
random ( ) It returns a random float x, >>>random.random ( )
such that 0.281954791393
0 ≤ x<1 >>>random.random ( )
0.309090465205
randint (a, b) It returns a int x between a >>> random.randint (1,10)
& b such that 5
a≤x≤b >>> random.randint (-2,20)
-1
randrange(<start>,<stop>,<step>) This method generates a random >>>random.randrange(35)
integer in the range from <start> 10
and <stop>-1 in the gap of <step>. #This will generate a random integer
In other words, this method first between 0 and 35
generated a list of numbers from >>>random.randrange(15,35)
<start> to <stop>-1 with the gap of 28
<step>. After that a random number #This will generate a random integer
from that list is chosen. So, we can between 15 and 35
say that this function first performs >>>random.randrange(15,35,5)
the job of range() function then 30
random() function. #This will generate a random integer
from [15,20,25,30]

Some functions from statistics module:


Name of the Description Example
function
mean() This method is used to find the mean of the given >>>x=[5,15,20,25,30,40]
>>>statistics.mean(x)
data. It takes one argument in the form of
22.5
list/tuple containing numbers. This method
calculates mean and returns it in float form
median() This method is used to find the median of the given >>>x=[18, 46, 4, 1, 20, 21]
>>>statistics.median(x)
data. It takes one argument in the form of
19.0
list/tuple containing numbers. This method
calculates median and returns it in float form. The
advantage of using this method is that list/tuple
passed as argument need not to be sorted.
median() method will automatically sort it and
calculate the mean
mod() This method is used to find the mode of the given >>>x= [1, 2, 3, 4, 4, 4, 4, 5, 6, 7, 7, 7,
8]
data. It takes one argument in the form of
>>>statistics.mode(x)
list/tuple containing numbers. This method 4
calculates mode and returns it in float form

2) Built –in- These functions are built into Python and can be accessed by a programmer. We don’t have to
import any module (file) to these functions.
Following are some built-in functions in python:-
Name of the function Description Example
abs (x) It always gives positive numeric >>>abs(-4)
4
value in answer.
>>>abs(119L)
119
>>> abs(100)
100
max( x, y, z, .... ) It returns the largest of its >>>max(8, 10, 100)
100
arguments: where x, y and
>>>max(-80, -20, -10)
z are numeric variable -10
min( x, y, z, .... ) It returns the smallest of its >>> min(8, 10, 100)
arguments; where x, y, and 8
z are numeric variable >>> min(-80, -20, -10)
-80
len (s) Return the length (the >>> a= [1,2,3]
number of items) of an >>>len (a)
object. The argument may 3
be a sequence (string, tuple >>> b= „Hello‟
or list) or a mapping >>> len (b)
(dictionary). 5
round( x [, n] ) It returns float x rounded >>>round(80.23456, 2)
to n digits from the 80.23
decimal point, where x and >>>round(-100.000056, 3)
n are numeric expressions. -100.0
If n is not provided then x >>> round (80.23456)
is rounded to 0 decimal 80.0
digits.
range (start, stop[, step]) It generates a list of numbers. It is >>> range(10)
often used in for loops. The [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
arguments must be integers. >>> range(1, 11)
If the step argument is omitted, it [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
defaults to 1. >>> range(0, 30, 5)
If the start argument is omitted, it [0, 5, 10, 15, 20, 25]
defaults to 0. >>> range(0, 10, 3)
If step is positive, the last element [0, 3, 6, 9]
is the largest start + i * step less >>> range(0, -10, -1)
than stop; [0, -1, -2, -3, -4, -5, -6, -7,
if step is negative, the last element -8, -9]
is the smallest start + i * step >>> range(0)
greater than stop. Step must not [ ] empty list
be zero >>> range(1, 0)
[ ] empty list

3) User defined-
User defined functions are those functions which are defined by the programmer for their convenience.
To define a function def keyword is used.

Syntax-
def <Function name> ([parameter 1, parameter 2,…..]) : FUNCTION HEADER

Set of instructions to be executed


FUNCTION BODY (Should be
[return <value>]
intended within the function header)
Some Important points to remember:-
• The items enclosed in "()" are called parameters and they are optional. Hence, a function may or may
not have parameters.
• A function may or may not return a value.
• Function header always ends with a colon (:).
• Function name should be unique. Rules for naming identifiers also applies for function naming.
• The statements outside the function indentation are not considered as part of the function.
Parameters and Arguments
Parameters are the name(s) provided in the parenthesis when we write function header.
These are the values required by function to work.
Let’s understand this with the help of function written for calculating area of circle. radius is a parameter to
function area.
def area(radius):
return(3.14*radius**2)
If there is more than one value required by the function to work on, then, all of them will be listed in
parameter list separated by comma.
Arguments are the value(s) provided in function call/invoke statement. List of arguments should be supplied
in same way as parameters are listed. Bounding of parameters to arguments is done 1:1, and so there
should be same number and type of arguments as mentioned in parameter list and in the same sequence as
well.
Example of argument in function call
>>> area (5)
5 is an argument. An argument can be constant, variable, or expression.
Scope of Variables
Scope of variable refers to the part of the program, where it is visible, i.e., area where you can refer (use) it.
We can say that scope holds the current set of variables and their values. There are two types of scope of
variables- global scope(variable) or local scope(variable).
Difference between global variable and local variable
Global Variable Local variable
1) A variable that has global scope is known as 1) A variable that has local scope is known as
global variable local variable
2) a variable that is defined outside any 2) A variable that is defined inside any
function or any block is known as a global function or a block
variable is known as a local variable
3) It can be accessed throughout the python 3) It can be accessed only in
code the function or a block where it is defined.

4) Any change made to the global variable will 4) Any change made to the local variable will
impact all the functions in the program where not impact all the functions in the program
that variable can be accessed. where that variable can be accessed.
5) It exists throughout the program 5) It exists only till the function executes.

Example:
x=5 Global variable
def try(): Output is:
x = 10 Local variable local x : 10
print("local x:", x) global x : 5
print("global x:", x)

Default Parameter
A default value is a value that is predefined and assigned to the parameter when the function call does not
have its corresponding argument.
Example:
def simple_interest(p, n, r=2): Here r is default parameter
si = 0.0
si = float(p*n*r)/float(100)
return si
p = float(input("Enter p: "))
n = int(input("Enter n: "))
simple_interest = simple_interest (p,n)
print("Simple interest value: %.2f" % simple_interest)

Multiple Choice Questions


1) The place where a variable can be used is called its
a) area b) block
c) function d) Scope

2) What is the output of the following segment?


chr(ord(‘A’))

(A) A
(B) B
(C) a
(D) Error

Distinguish between Actual Parameter and Formal Parameter

Actual Parameter Formal Parameter


1.Used in function call statement 1. Used in function header of the called
function
2.Send value from calling function to called 2.Receives value from actual parameter
function

Programs using User defined Functions

1) Write a program with a user defined function to count the number of times a character (passed as
argument) occurs in the given string.
Source code:
def charCount(ch,st):
count = 0
for character in st:
if character == ch:
count += 1
return count
st = input("Enter a string: ")
ch = input("Enter the character to be searched: ")
count = charCount(ch,st)
print("Number of times character",ch,"occurs in the string is:",count)
Output:
Enter a string: Today is a Holiday
Enter the character to be searched: a
Number of times character a occurs in the string is: 3

2) Write a program with a user defined function with string as a parameter which replaces all vowels in the
string with '*'.
Source code:
def replaceVowel(st):
newstr = ''
for character in st:
if character in 'aeiouAEIOU':
newstr += '*'
else:
newstr += character
return newstr
st = input("Enter a String: ")
st1 = replaceVowel(st)
print("The original String is:",st)
print("The modified String is:",st1)

Output:
Enter a String: Hello World
The original String is: Hello World
The modified String is: H*ll* W*rld

3) Write a program which reverses a string passed as parameter and stores the reversed string in a new
string. Use a user defined function for reversing the string.

Source code:
def reverseString(st):
newstr = '' #create a new string
length = len(st)
for i in range(-1,-length-1,-1):
newstr += st[i]
return newstr

st = input("Enter a String: ")


st1 = reverseString(st)
print("The original String is:",st)
print("The reversed String is:",st1)

Output:
Enter a String: Hello World
The original String is: Hello World
The reversed String is: dlroW olleH
4) Write a program using a user defined function to check if a string is a palindrome or not. (A string is called
palindrome if it reads same backwards as forward.
For example, Kanak is a palindrome.)
def checkPalin(st):
i=0
j = len(st) - 1
while(i <= j):
if(st[i] != st[j]):
return False
i += 1
j -= 1
return True
st = input("Enter a String: ")
result = checkPalin(st)
if result == True:
print("The given string",st,"is a palindrome")
else:
print("The given string",st,"is not a palindrome")

Output 1:
Enter a String: kanak
The given string kanak is a palindrome

Output 2:
Enter a String: computer
The given string computer is not a palindrome

5) Program to count no of ‘p’ in the string pineapple.


def lettercount():
count = 0
for letter in word:
if letter == 'p':
count = count + 1
print(count)
word=input(‘Enter string:’)
lettercount()

Output is:
Enter string:applee
2
UNIT-I
FILE HANDLING IN PYTHON

ABOUT FILE:
A file is a sequence of bytes contain data and store it on some storage device. File handling is an
important part of any computer application.

NEED FOR FILE HANDLING

➔ To store data for future reference

➔ Sometime the output generated by a program is large thus file help to store that huge data.

TYPES OF FILES

Text Files:

A file whose contents can be viewed using a text editor is called a text file. A text file is simply a
sequence of ASCII or Unicode characters. In text file, translation will take place after the EOL or delimiter
is encountered. Thus, it is slower than binary file.

Binary Files:

A binary file stores the data in the same way as stored in the memory. In Binary file there is no
delimiter for a line. The file contents returned by a binary file is raw i.e. with no translation, thus Binary
files are faster than text files.

CSV Files:

CSV stands for Comma Separated Values. CSV is just like a text file, in a human readable format
which is extensively used to store tabular data, in a spreadsheet or database. The separator character of
CSV files is called a delimiter. Default delimiter is comma (,). Other delimiters are tab (\t), colon (:), pipe (|),
semicolon (;) characters.

TEXT FILE Vs. BINARY FILES

Text Files Binary Files


Stores data in ASCII or Unicode format so Contains raw data so that not human
that text files are human readable. readable.
Each line is delimited by EOL or end of Line No delimiter for a line
(like \n).
Slower than Binary File Faster than text files

In Python, any type of File Handling consists the following three steps:

1. Opening of a file with specific mode. Using open () method / with statement of python.

2. Process file i.e perform read or write operation.

3. Close the file, if file has opened using open () method

STEPS TO PROCESS A FILE

1. Open the file by specifying file-path and file-mode(reading/writing)


i. Reading purpose: If the data is to be brought in from a file to memory.
ii. Writing purpose: If the data is to be sent from memory to file.

2. Assign its reference to a file object or file-handle.


3. Process the file as per requirement of program i.e perform the desired operation.
4. Close the file.

Opening a Text File

The first step of file handling is to open the file by specifying file-path and file-mode. If no file-mode is
specified by default file will be open in reading mode.

Python has two ways to open a file: -


1) Using built in function open()
2) Using Python ‘with’ statement

1) Using built-in function open() : -

Syntax: <file_object_name> = open(<file_path>,<mode>)

Example: f = open(“demo.txt”,”r”)
2) Using Python ‘with’ statement: -

Syntax: with open(<file_path>, <mode>) as <file_object>:

Example: with open(“demo.txt”) as f:

About File Object:


o It serves as a link to file residing in your computer.
o It is a reference to the file on the disk
o It helps to perform operations on the file.

Absolute Path:
• Absolute file paths are notated by a leading forward slash or drive label.
Example C:\\KVSROMUMBAI\\demo.txt
• An absolute path, which always begins with the root folder.

Relative Path:
A relative path, is relative to the program’s current working directory.

Example ‘.\test.txt’ or ‘test.txt’

File Modes (File Access Modes):

It indicates that for what purpose the file is being opened.

Text Binary File Description Purpose


File Mode
Mode
Opens a file for reading, Shows error if the file
“r” “rb” Read does not exist. It is the default file-mode.
Opens a file for writing, creates the file if it
“w” “wb” Write does not exist.
If the file exists, the previous contents will be
lost.
Opens a file for appending, Old data will retain
“a” “ab” Append if file already exist.
Creates the file if it does not exist.
File must exist otherwise error is raised.
“r+” “rb+” or Read and Both reading and writing operations can take
“r+b” Write place.
File is created if it does not exist.
“w+” “wb+” or Write and If the file exists previous data is truncated
“w+b” Read (removed).
Both reading and writing operations can take
place.
File is created if it does not exist.
“a+” “ab+” or Append and If the file exists previous data is retained
“a+b” Read and the new data will be added at the end of the
file.
Both reading and writing operations can take
place.

CLOSING A FILE: -
close() method is use to close the opened file. In python files are automatically close at the end of the
program but it is advisable to close a file after the end of the program.

S yntax: <fileObject>.close()

Example : f.close()

Moreover, if file has opened using ‘with’ statement of python then it will automatically close after
the nested block of code.

READING from a Text File: -


A Program can reads a text file from disk. The followings methods are used to read data from the
text file:
1. read()
2. readline()
3. readlines()

1. read() - The read() method returns the whole text in the form of string. You can also specify how
many characters you want to return by passing the size as argument.

Syntax: <file_object>.read([n]) where n is the No. of bytes that we want to read from the file.

a) <file_object>.read() – It will read the whole file.

b) <file_object>.read(n) – It will read exactly n bytes from the beginning of the file.

Example:
f = open("demo.txt", "r")

print(f.read(15)) # Returns the first 15 characters of the file"demo.txt".

2. readline() - readline() method will return a line, if n is specified reads n bytes.

Syntax: <file_object>.readline()

Example
f = open("demo.txt", "r")

print(f.readline()) # It will read the first line

print(f.readline()) # It will read the next line and so on

3. readlines() – This method will return a list of strings, each separated by \n. readlines() can be used to read
the entire content of the file.

Syntax: <file_object>.readlines()

It returns a list, which can then be used for manipulation.

Example: f = open("demo.txt", "r")


print(f.readlines())

Some Examples of Text File Handling: -

# Program to print the first and last line of the text file abcd.txt
myf=open("abcd.txt","r")
lst=myf.readlines()
print(lst[0]) # Used to print the first line
print(lst[-1]) # Used to print the last line
myf.close()

# Program to count No. of lines in a text file python.txt


myf=open("python.txt","r")
lst=myf.readlines()
print(len(lst))
myf.close()

# Program to count a specific word "python" in a text file text_demo.txt


myf=open("text_demo.txt","r")
st=myf.read()
c=0
for i in st.split():
if (i=="python" or i=="PYTHON" or i=="Python"):
c=c+1
print("The word python occurs ", c , “ times in the file.”)
myf.close()

# Program to print first n lines from the text file para.txt


myf=open("para.txt","r")
lst=myf.readlines()
n=int(input("Enter how many lines you wish to display"))
for i in range(0,n):
print(lst[i])
myf.close()

# Program to print n lines at the end from a text file abcd.txt

myf=open("abcd.txt","r")
lst=myf.readlines()
n =int(input('Enter how many lines you wish to print from last'))
for i in range(-1,-n-1,-1):
print(lst[i])
myf.close()

# Program to count total number of digits in a file myfile.txt

myf=open("myfile.txt","r")
x=myf.read()
c=0
for i in x:
if(i.isdigit()):
c=c+1
print('Total digits=',c)
myf.close()

Difference between read(), readline() and readlines():

The read() method reads data from a text file, and store its contents in a string type variable. It
can either read the whole content from the file if any parameter is not passed inside read method,
otherwise if n is passed inside read() the method will read n number of characters.
The readline() function reads data line by line from the text file. At a time it will return one line
of data in the form of string.
The readlines() function reads all lines and return them in a list.

Assume the content of text file, 'portfolio.txt' is:


Samrat Roy
12-11-1999
AB+
NAGPUR

Now, carefully watch the given code and then identify the data type of record1 and record2?

file = open("portfolio.txt")
record1 = file.readlines()
file.close()

Ans: - Data type of record1 will be list.

file = open("portfolio.txt")
record2 = file.read()
file.close()

Ans: - Data type of record2 will be string.

# Suppose the content of the file 'quotes.txt' is: -

All of us do not have equal talent.


But, all of us have an equal opportunity to develop our talents.
I am not handsome but I can give my hand to someone who needs help.
Because Beauty is required in the heart, not in face.

Now, tell what will be the output of the following code(s)?

FILE = open("quotes.txt")
LC = 0
DATA = FILE.readlines()
for L in DATA:
if L[0] == 'B':
LC += 1
print("No. of lines starts with B =",LC)
FILE.close()

Output:

No. of lines starts with B = 2

And, what will be the output of the following code: -

FILE = open("quotes.txt")
AC = 0
DATA = FILE.read()
for L in DATA:
if L=='B':
AC+=1
print("Total No. of alphabet B in the file =",AC)
FILE.close()

Output:

Total No. of alphabet B in the file = 3


WRITING into a text file: -

A Program can also write strings into a text file. Followings are the methods to write a data to the
file:

write ()
writelines()

Note: - To write into a text file, we must add parameter as ‘w’ or ‘a’ in the open() function which specifies the

file access mode :

"a" – for append the data at the end of the file

"w" – for overwrite any existing content and then write the new data

Difference between ‘a’ and ‘w’ modes i.e. append and write modes: -

If you open a file in “w” means write mode, Python overwrites an existing file or creates a new
file. For an existing file, the earlier data gets removed.

If you want to write into a file with retaining the previous data, the file must be opened in “a”
means append mode.

1) write() – This method takes a string ( as parameter ) and writes it in the file. For storing data with end of line
character, we will have to add \n character to the end of the string.

Example:

# Open the file "demo.txt" and add content in it

f = open("demo.txt", "w")

f.write("Hello students\nUse this study material\nYou will get good marks!")

f.close()

# open the file and read the content of it


f = open("demo.txt", "r")

print(f.read())

# Open the previous file "demo.txt" and add more content to the file:

f = open("demo.txt", "a")

f.write("\nAll the Best.")

f.close()

# Now again open the file in read mode and see the result …. (Check by yourself)

2) writelines() - Drawback of write() function is it will write a string in a text file at a time, and it can't be
used for writing a list, tuple etc. into a file. writelines() method will help to write a sequence of strings to the
file. The sequence can be any object producing strings, typically a list of strings. So, whenever we have to
write a sequence of string / data type, we will use writelines(), instead of write().

# Program showing use of writelines() method

f = open("demo.txt", "w")
f.writelines(["Python is just amazing!", "\nWe love python"]) # here we used list data
f.close()

#open and read the file after the appending

f = open("demo.txt", "r")
print(f.read())
flush() function: - The flush() function forces the writing of data on disc which was still pending in the
output buffer.

Syntax : <file_object>.flush()

# Program to demonstrate the use of flush() function

f = open("demo_flush.txt","w+")
f.write("India is my country.\n")

f.flush()

# After some statements x = "Jai Hind"

x=”Jai Hind”
f.write(x)

f.seek(0) # Here seek() will move the file pointer(handle) at the beginning of the file.
print(f.read())
f.close()

seek() function: – The seek() function changes the position of the file-pointer by placing the file-pointer at
the specified position in the open file.

Syntax: <file_object>.seek(offset, mode)

Offset will be 0 or 1 or 2

0 for beginning of the file (to move file pointer w.r.t. beginning of file) it is default mode.
1 for current position of file pointer (to move file pointer w.r.t current position of it.)
2 for end of file (to move file-pointer w.e.t. end of file)

Example:
f=open("demo_seek.txt","r")
print(f.read()) # after reading all the bytes file pointer reaches to the end of the file.

f.seek(6) # Now the file pointer will move to the 6th Byte from beginning.
print(f.read()) # It will print the remaining number of bytes after 6th Byte.

tell() function: – This function returns the current position of file pointer in the file.

Syntax: <file_object>.tell()

Example:
f=open("d:\\pooja\\demo_seek.txt","r")
print(f.read(5)) # This will read 5 bytes from the beginning
print(f.tell()) # This will show 5 as file pointer is at 5th character from beginning

BINARY FILES:

A Binary file stores the information in the form of a stream of bytes. A binary file stores the data
in the same way as stored in the memory. In Binary file there is no delimiter for a line. The file contents
returned by a binary file is raw i.e. with no translation, thus Binary files are faster than text files.

Python objects (list, dictionary etc) have a specific structure which must be maintained
while storing or accessing them. Python provides a special module called pickle module for this.

PICKLING refers to the process of converting the structure(list/dictionary) to a byte of stream before
writing it to a file. The process to converts any kind of python objects (list, dict etc.) into byte streams (0s
and 1s).

UNPICKLING is used to convert the byte stream back to the original structure while reading the
contents of the file.

pickle Module: -
Before reading or writing to a file, we have to import the pickle module.

import pickle

pickle module has two main methods: dump() and load()

pickle.dump() – This method is used to write the object in the file which is opened in ‘wb’ or ‘ab’
i.e. write binary or append binary access mode respectively.

Syntax : pickle.dump(<structure>,<FileObject>)

Here, Structure can be list or dictionary.


FileObject is the file handle of file in which we have to write.

# Simple program to write a list data into a binary file

import pickle
fo = open("binary_file1.dat","wb")
Laptop = ["Dell","HP","ACER"]
pickle.dump(Laptop,fo)
fo.close()

pickle.load() – This method is used to read data from a file and return back into the structure (list/dictionary).

Syntax : <structure> = pickle.load(<FileObject>)

Structure can be any sequence in Python such as list, dictionary etc. FileObject is the file handle of file in
which we have to write.

# Program to read data from a binary file

fbin = open("binary_file1.dat","rb")
x=pickle.load(fbin)
print(x)
fbin.close()
# Simple program to write a dictionary data into a binary file

import pickle
f=open("my_bin1.bin","wb")
D1={3:'Maruti',2:'Honda',4:'Hundai',1:'BMW'}
pickle.dump(D1,f)
f.close()

f1=open("my_bin1.bin","rb")
D2=pickle.load(f1)
print(D2)
f.close()

# Write a User defined function bdict() to store customer data into a binary file customer.dat using a
dictionary and print them on screen after reading them. The customer data contains
customer_ID(c1,c2,c3) as key, and name, city as values.

import pickle
def bdict():
f = open("customer.dat","wb")
d = {'C1':['Siman Raheja','Haryana'],
'C2':['Praharsh Kumar','Pune'],
'C3':['Vinita Minj','Indore']}
pickle.dump(d,f)
f.close()

f = open("customer.dat","rb")
d = pickle.load(f)
print(d)
f.close()

# Sample program to insert any number of records (as per user’s choice) of employee (employee number,
name, salary and allowance) and then display all the records.

import pickle
bfile=open("empfile.dat","ab")
recno=1
while True:
print("RECORD No.", recno)
eno=int(input("\tEmployee number : "))
ename=input("\tEmployee Name : ")
ebasic=int(input("\tBasic Salary : "))
allow=int(input("\tAllowances : "))
totsal=ebasic+allow
print("\tTOTAL SALARY : ", totsal)

edata=[eno,ename,ebasic,allow,totsal]
pickle.dump(edata,bfile)

ans=input("Do you wish to enter more records (y/n)? ")


recno=recno+1
if ans.lower()=='n':
print("Record entry OVER ")
break
bfile.close()
rbfile=open("empfile.dat","rb")
readrec=1
try:
while True:
edata=pickle.load(rbfile)
print("Record Number : ",readrec)
print(edata)
readrec=readrec+1
except EOFError:
print('Sorry No more records to show now.')
pass
rbfile.close()

# Write a program that have a binary file “Book.dat”. The file has structure [BookNo, Book_Name, Author,
Price]. Now do as directed: -

1) Write a user defined function CreateFile() to input data for a record and add to Book.dat.
2) Write the definition of show_all_books() UDF to display the details of all the books.
3) Write a User Defined function CountRec(Author) in Python which accepts the Author name as
parameter, display the details of the book of the same author also return the number of books of the
given Author are stored in the binary file “Book.dat"

import pickle

def createfile():
fobj=open("Book.dat","ab")

BookNo=int(input("Enter Book Number : "))


Book_name=input("Enter book Name :")
Author = input("Enter Author name: ")
Price = int(input("Price of book : "))
rec=[BookNo, Book_name ,Author, Price]
pickle.dump(rec, fobj)
print("Record saved")
fobj.close()

def show_all_books():
fobj=open("Book.dat","rb")
L1=[]

try:
while True:
L1=pickle.load(fobj)
print(L1)

except EOFError:
print('All Record displayed')
pass
fobj.close()

def countrec(Author):
fobj=open("Book.dat", "rb")
cnt = 0
print("Book No Book Name Author Price")

try:
while True:
r=pickle.load(fobj)
if Author==r[2]:
cnt = cnt + 1
print(r[0],"\t",r[1],"\t",r[2],'\t',r[3])
except:
print()

fobj.close()
return cnt

# Write a program that uses a binary file “STUDENT.DAT” has structure [roll_number, Name, Percentage].
Write a User defined function countrec() that would read contents of the file
“STUDENT.DAT” and display the details of those students whose percentage is above 75%.

import pickle

def createfile():
fobj=open("student.dat","ab")

rno=int(input("Enter Roll No : "))


nm=input("Enter Name :")
p = int(input("Enter percentage: "))

rec=[rno, nm , p]
pickle.dump(rec, fobj)
print("Record saved")
fobj.close()

def countrec():
fobj=open("student.dat","rb")
num = 0
try:
while True:
rec=pickle.load(fobj)

if rec[2]>375:
num = num + 1
print(rec[0],rec[1],rec[2])
except:
fobj.close()
return num

createfile()
countrec()

CSV FILES: -

CSV stands for Comma Separated Values. It is a type of plain text file that uses specific structure to
arrange tabular data i.e. data stored in rows and columns such as a spreadsheet or database.

CSV is like a text file, It is in human readable format and extensively used to store tabular data, in a
spreadsheet or database.

Each line of the csv file is a data record. Each record consists of one or more fields, separated by
commas. The separator character of CSV files is called a delimiter.

Default delimiter is (,). Other delimiters are tab(\t), colon (:), pipe(|), semicolon (;) characters.

READING FROM A CSV FILE

To read data from csv files, reader() method of csv module is used.
csv.reader() returns a reader object.
STEPS TO READ

1) import csv module

import csv

2) Open csv file in read mode.


f = open(“csv_demo.csv”,”r”)

3) Create the reader object.


demo_reader = csv.reader(f)

4) Fetch data through for loop, row by row.


for x in demo_reader:
print(x)

5) Close the file


f.close()

# Program to read from a csv file import csv

f = open("emp.csv","r")
emp_reader=csv.reader(f)
for row in emp_reader:
print(row[0],row[1],row[2]) # print(row) : As a list
f.close()

WRITING IN TO CSV FILES:

To write data into csv files, writer() function of csv module is used.

csv.writer(): This function returns a writer object which writes data into writer object.
Significance of writer object

The csv.writer() returns a writer object that converts the data into a delimited string.The string
can be later converted into csv files using the writerow() or writerows() method.
Syntax:

<writer_object>.writerow() :

Writes one row of data in to the writer object.

<writer_object>.writerows()

Writes multiple rows into the writer object.

# Program to write data into a CSV File and to read data stored in csv file

import csv
f=open("mycsv.csv","w",newline='')
w=csv.writer(f)
lst=["RNO","NAME","MARKS"]
w.writerow(lst)

n=int(input('Enter how many students record you want to add'))


for x in range(n):
r=int(input('Enter rno'))
n=input('Enter name')
m=int(input('Enter marks'))
lst2=[r,n,m]
w.writerow(lst2)
f.close()

f=open("mycsv.csv","r")
rec=csv.reader(f)
for i in rec:
print(i)
f.close()

# Program to write Employee Name, EmpID and Dept for some employees in a csv file then display
records of all the employees.

import csv

f=open("emp.csv","w",newline='')
emp_writer = csv.writer(f)

emp_writer.writerow(["EmpName","EmpID","Dept"])

emp_rec = []

while True:
print("Enter Employee details: ")
empname = input("EmpName : ")
eid = int(input("EmpID : "))
dept = input("Department : ")

emp_rec.append([empname,eid,dept])

ch = input("Do you want to continue ?? (Y?N)")

if ch == "N" or ch =="n":
break

emp_writer.writerows(emp_rec)

f.close()

f=open("emp.csv","r")

rec=csv.reader(f)

for i in rec:
print(i)

f.close()

Question based on CSV file Handling: -

Madhwan, is doing internship in “SQUARE Solutions Pvt. Ltd.”. He wrote the following python code to store
student’s data in csv file (Student.csv) handling. Unfortunately, he forgot some steps of the python code.
Please help him to create a CSV File 'Student.csv' by completing the code.

CSV File
1,SAKSHAM,XII,A
2,ARNAV,XI,A
3,SHREEVALI,XII,A
4,BHOOMI,XI,A
5,SWARIT,XII,A

The Incomplete Code written by Madhwan is as follows: -

import_____ #Statement-1

csvfh = open(_____, _____, newline='') #Statement-2

stuwriter = csv._____ #Statement-3

data = []

header = ['ROLL_NO', 'NAME', 'CLASS', 'SECTION']

data.append(header)

for i in range(5):
roll_no = int(input("Enter Roll Number : "))
name = input("Enter Name : ")
Class = input("Enter Class : ")
section = input("Enter Section : ")
rec = [_____] #Statement-4
data.append(rec)
stuwriter. _____ (data) #Statement-5

csvfh.close()

a) Identify the suitable code for Statement-1.

a) csv file
b) CSV
c) csv
d) Csv

Correct Answer : c) csv

b) Identify the correct parameters for Statement-2?

a) "School.csv","w"
b) "Student.csv","w"
c) "Student.csv","r"
d) "School.csv","r"

Correct Answer: b) "Student.csv","w"

c) Choose the function name (with argument) to complete Statement-3

a) reader(csvfh)
b) reader(MyFile)
c) writer(csvfh)
d) writer(MyFile)

Correct Answer : c) writer(csvfh)

d) Identify the suitable code for Statement-4.

a) 'ROLL_NO', 'NAME', 'CLASS', 'SECTION'


b) ROLL_NO, NAME, CLASS, SECTION
c) 'roll_no','name','Class','section'
d) roll_no,name,Class,section

Correct Answer : d) roll_no,name,Class,section

e) Choose the function name that should be used for Statement-5 to create the desired CSV File.

a) dump()
b) load()
c) writerows()
d) writerow()

Correct Answer : c) writerows()


Data Structures: Stack using List
Data Structure

In Data Structure w e a r e collecting and organizing data in such a way that we can perform
operations on these data in an effective way.

Stack
A stack is a data structure whose elements are accessed according to the Last- In First-
Out (LIFO) mechanism. This is because in a stack, insertion and deletion of elements can
only take place at one end, which is called top of the stack.

Consider the following examples of stacks:


1. A pile of books
2. A stack of coins
3. Ten glass plates placed one above another.

Fig.1 A stack of coins (ref: google.com)


In the above picture coins are kept one above the other and if any additional coin I need to be
added, it can be added only on the top.

Similarly, If we want to remove any coin from the stack, the coin on the top of the stack has to
be removed first. That means, the coin that was kept last (i.e. at the top) in the stack has
to be taken out first.
The two operations performed on the stack are:

• Push operation: It means inserting element at the top of the stack. This can be
done with the help of append() method of the list as: st.append(element) where ‘st’ is
a list.
• Pop operation: It means removing the topmost element from the stack. This can be
performed using pop() method of the list as: st.pop() where ‘st’is a list. This method
returns the removed element that can be displayed.
Applications of Stack

• Recursion
• Postfix notations(Evaluation of expressions)
• Tower of Hanoi

# Program to implement stack using list

st=[] #to create an empty list


def stkpush():
n=int(input("Enter a No. : "))
st.append(n)

def stkpop():
if len(st) ==0:
print("Underflow")
else:
print(st.pop()," removed")

def display():
if st==[ ]:
print("Underflow")
else:
print("stack is: ")
L=len(st)-1
for i in range(L,-1,-1): print(st[i])

char=True
while(char):
print("1.Push")
print("2.Pop")
print("3.display")
ch=int(input("Enter choice: "))
if ch==1:
stkpush()
elif ch==2:
stkpop()
elif ch==3:
display()
else:
char=False
Output: -

# A Menu Driven Program to store Name and marks out of 100 for some students in a stack
and implementation of stack operations.

stk=[]
ui='y'

while(ui=='y'):
print('Menu')
print('1.Push a student record’)
print(‘2.Pop a student record’)
print(‘3.Show all students record')
print('4.Search student record scored above 90')

ans=int(input('Enter your choice(1/2/3/0)'))

if(ans==1):
n=input('Enter Name')
m=int(input('Enter Total marks obtained out of 100'))
stk.append((n,m))
if(ans==2):
if(stk==[]):
print('Stack is empty')
else:
y=stk.pop()
print(y,' is removed from stack')

if (ans==3):
s=len(stk)
for i in range(s-1,-1,-1):
print('============')
print(stk[i])

if(ans==4):
s=len(stk)
for i in range(s-1,-1,-1):
if (stk[i][1]>=90):
print('************')
print(stk[i])

***
UNIT-II-COMPUTER NETWORK

EVOLUTION OF NETWORK

TRANSMISSION MEDIA

NETWORKING DEVICES

NETWORKING TOPOLOGIES

NETWORKING PROTOCOLS

SWITCHING TECHNIQUES

WEB SERVICES
ARPANET

INTERNET
EVOLUTION OF
NETWORKING
CIRCUIT
INTERSPACE
SWITCHING

SWITCHING MESSAGE
TECHNOLOGIES SWITCHING

PACKET
SWITCHING

TRANSMISSION
MEDIA

UNGUIDED
GUIDED MEDIA
MEDIA

TWISTED PAIR FIBRE OPTIC


COAXIAL CABLE INFRARED RADIOWAVE MICROWAVE SATELLITE
CABLE CABLE
MODEM

RJ-45
SWITCH/HUB
CONNECTOR

REPEATER SWITCH
NETWORK
DEVICES

ETHERNET
ROUTER
CARD

WI-FI CARD GATEWAY

NETWORK NETWORK
TOPOLOGIES TYPES

BUS LAN
STAR MAN
TREE WAN
PAN
NETWORK PROTOCOLS

WIRELESS
TCP/IP FTP PPP HTTP SMTP TELNET VOIP POP3 HTTPS
PROTOCOLS

WEB SERVICES

URL WWW HTML XML DOMAIN WEBSITE WEB WEB WEB


• Uniform • World Wide • Hyper Text • Extensible NAME • A website is BROWSER SERVER HOISTING
Resource Web Markup Markup • Domain a collection • The software • A Web • Web hosting
Locator Langauge Langauge Name of web that access Server is a is an online
System pages which to web sites. WWW service that
makes it consists of server that enables you
easier to text, images responds to to publish
resolve IP and all types the requests your website
addresses of multi- made by or web
into names. media files web application
browsers. on the
internet.
COMPUTER NETWORK

Short Answer Questions ( 1 Mark/2 Marks)

Q: Abbreviation (based 1 or 2 marks)

1 NIU Network Interface Unit


2 MAC Media Access Control
3 TCP/IP Transmission Control Protocol/Internet Protocol
4 PAN Personal Area Network
5 LAN Local Area Network
6 MAN Metropolitan Area Network
7 WAN Wide Area Network
8 UTP Unshielded Twisted Pair
9 STP Shielded Twisted Pair
10 Mbps Mega bits per sec
11 EMI Electro Magnetic Interference
12 RJ Registered Jack
13 Wi-Fi Wireless Fidelity
14 VPN Virtual Private Network
15 IAAS Infrastructure As A Service
16 PAAS Platform As A Service
17 SAAS Software As A Service
18 DAAS Desktop As A Service
19 IOT Internet Of Things
20 NIC Network Interface Card
21 CSMA/CD Carrier Sense Multiple Access/Collision Detection
22 CSMA/CA Carrier Sense Multiple Access/Collision Avoidance
23 DNS Domain Name System
24 DHCP Dynamic Host Configuration Protocol
25 ISP Internet Service Provider
26 URL Uniform Resource Locator
27 HTTP Hyper Text Transfer Protocol
28 FTP File Transfer Protocol
29 FDMA Frequency Division Multiple Access
30 TDMA Time division Multiple Access
31 CDMA Code Division Multiple Access
32 SIM Subscriber Identity Module
33 EDGE Enhanced Data rates for GSM Evolution
34 UMTS Universal Mobile Telecommunications System
35 LTE Long Term Evolution
36 GPRS General Packet Radio Service
37 ICMP Internet Control Message Protocol
38 OSI Open Systems Interconnection
39 SMTP Simple Mail Transfer Protocol
40 VoIP Voice Over Internet Protocol
41 SIP Session Initiation Protocol
42 QoS Quality of Service
43 POP Post Office Protocol
44 IMAP Internet Mail Access Protocol
45 SCP Secure Copy Protocol
46 SSH Secure Shell
47 IEEE Institute of Electrical & Electronic
Engineering
48 NFC Near-Field Communication
49 NFS Network File System
50 NTP Network Time Protocol
51 SLIP Serial Line Internet Protocol
52 PPP Point to Point Protocol
53 UDP User Datagram Protocol
54 SNMP Simple Network Management Protocol

Q. What are the components required for networking?


Ans Components of a network are:
Sender
Receiver
Transmission media
NIC
Connecting components: Switch, Hub, Router, Modem, Repeater,
bridges, gateway

Q. Define internet?
Ans Internet is a network of networks.

Q. Write two advantage and disadvantage of networks.


Ans Advantages:
1. Resource sharing
2. Enhanced communication
3. Reliability and flexibility
Disadvantages:
1. Network setup cost
2. Malware infection
3. Security of networks
Q. What is ARPAnet?
Ans ARPAnet (Advanced Research Project Agency Network is a project sponsored by U. S.
Department of Defense.

Q. What is communication channel?


Ans Communication channel mean the connecting cables that link various workstations. Following are
three basic types of communication channels available:
a) Twisted-Pair Cables
b) Coaxial Cables
c) Fiber-optic Cables

Q. Define baud, bps and Bps. How are these interlinked?


Ans Baud is a unit of measurement for the information carrying capacity of a communication channel.
bps- bits per second. It refers to a thousand bits transmitted per second.
Bps- Bytes per second. It refers to a thousand bytes transmitted per second. All these terms are
measurement

Q. What do you understand by Interspace?


Ans Interspace is a client/server software program that allows multiple users to communicate online
with real-time audio, video and text chat I dynamic 3D environments.

Q. Define Client and server.


Ans Server- It is a special computer that provides services/data to other computers/devices on a network
Client- It is a computer on a network that demands for service from server

Q. Name any two switching circuits .


Ans The two switching circuits are i)Circuit Switching ii)Message Switching

Q.Give one example of each – Guided media and Unguided media.


Ans: Guided – Twisted pair, Coaxial Cable, Optical Fiber (any one)
Unguided – Radio waves, Satellite, Micro Waves (any one)

Q. Name the protocol that is used to transfer file from one computer to another.
Ans:FTP

Q.Name the transmission media best suitable for connecting to desert areas.
Ans: Microwave

Q.Rearrange the following terms in increasing order of speedy medium of data transfer:
Telephone line, Fiber Optics, Coaxial Cable, Twisted Paired Cable.
Ans: Telephone line, Twisted Pair Cable, Coaxial Cable, Fiber Optics.

Q.Name the transmission media suitable to establish PAN.


Ans: Bluetooth, infrared

Q. Name the protocol that is used to upload and download files on internet.
Ans: FTP or HTTP

Q..Name the protocol that is used to send emails. Ans:-SMTP

Q. Name the protocol that is used to receive emails. Ans:-POP

Q.Name the transmission media best suitable for connecting to hilly areas.
Ans: Microwave / Radio wave.

Q.Name the fastest available transmission media.


Ans: OFC (Optical Fiber Cable)

Q.Which type of network (out of LAN, PAN and MAN) is formed, when you connect two mobiles using
Bluetooth to transfer a video?
Ans:PAN

Q.Out of SMTP and POP3 which protocol is used to receive emails ?


Ans: POP3

Q. Ravi has purchased a new Smart TV and wants to cast a video from his mobile to his new Smart TV.
Identify the type of network he is using and explain it.
Ans: Ravi is using PAN-Personal Area Network. It is a private network which is setup by an individual to
transfer data among his personal devices of home.

Q.Your friend Rakesh complaints that somebody accessed his mobile device remotely and deleted the
important files. Also he claims that the password of his social media accounts were changed. Write a the
name of crime?
Ans:The gaining of unauthorized access to data in a system or computer is termed as hacking. It can be
classified in two ways: (i) Ethical Hacking (ii)Cracking

Q.. Identify the parts of URL:


http://www.google.com/index.html

Ans:

Q.. What do you mean by Protocol?


Ans: A protocol means the rules that are applicable for a network or we can say that the common set of
rules used for communication in network.

Q.What is web hosting?


Ans: Web hosting is the service that makes our website available to be viewed by others on the Internet.
A web host provides space on its server, so that other computers around the world can access our website
by means of a network or modem.

Q. Which protocol is used to creating a connection with a remote machine?


Ans: Telnet: It is an older internet utility that lets us log on to remote computer system. It also facilitates
for terminal emulation purpose.

Q.Explain the purpose of a router.


Ans: A router established connection between two networks and it can handle network with different
protocols. Using a routing table, routers make sure that the data packets are travelling through the best
possible paths to reach their destination.

Q.What are repeaters?


Ans: A repeater is an electronic device that receives a signal and retransmits it at a higher level and/ or
higher power, or onto the other side of an obstruction, so that the signal can cover longer distances

Q. What is the difference between hub and switch? Which is more preferable in a large network of
computers and why?
Ans: Hub forwards the message to every node connected and create a huge traffic in the network hence
reduces efficiency whereas a Switch (also called intelligent hub) redirects the received information/ packet
to the intended node(s).
In a large network a switch is preferred to reduce the unwanted traffic in the network. It makes the network
much more efficient.

Q.Differentiate between web server and web browser. Write any two popular web browsers.
Ans: Web Browser : A web browser is a software application for accessing information on the World Wide
Web. When a user requests a web page from a particular website, the web browser retrieves the necessary
content from a web server and then displays the page on the user‟s device.
Web Server : A web server is a computer that runs websites. The basic objective of the webserver is to
store, process and deliver web pages to the users. This intercommunication is done using Hypertext
Transfer Protocol (HTTP).
Popular web browsers: Google Chrome, Mozila Firefox, Internet Explorer etc.

Q.Define network interface card


Ans: NIC is a network adapter used to set up a wired network. It acts as an interface between computer
and the network. It is a circuit board mounted on the motherboard of a computer. Each NIC has a MAC
address, which helps in uniqyuely identifying the computer on the network

Q.Identify the Domain name and URL from the following:


http://www.income.in/home.aboutus.hml
Ans:Domain name – income.in
URL – http://www.income.in/home.aboutus.hml.

Q.Categorize the following under client-side and server-side scripts category:


1. Jave Script
2. ASP
3. VB Script
4. JSP
Ans Client Side Scripts : VB SAcript, Java Script
Server Side Scripts: ASP, JSP

Q. Identify the type of topologies on the basis of the following:


1. Since every node is directly connected to the server, a large amount of cable is needed which increases
the installation cost of the network.
2. It has a single common data path connecting all the nodes.
Ans:1. Star Topology
2. Bus Topology

Q.Differentiate between circuit switching and message switching.


Ans :

Circuit Switching Packet Switching

In-circuit switching has there are 3 phases:


i) Connection Establishment.
ii) Data Transfer. In Packet switching directly data transfer takes
iii) Connection Released. place.

In-circuit switching, each data unit knows In Packet switching, each data unit just knows the
the entire path address which is provided by final destination address intermediate path is
the source. decided by the routers.

In-Circuit switching, data is processed at the In Packet switching, data is processed at all
source system only intermediate nodes including the source system.

The delay between data units in circuit The delay between data units in packet switching
switching is uniform. is not uniform.
Q. What is communication channel? Name the basic types of communication channels available
Ans: Communication channel mean the connecting cables that link various workstations. Following are
three basic types of communication channels available:
a) Twisted-Pair Cables
b) Coaxial Cables
c) Fiber-optic Cables.

Q.. Which of the following communication medium requires line of sight communication?
Microwave, radio wave , infrared, Bluetooth
Ans: Microwave, infrared

Q. Arrange the following networks based in descending order of area covered:


WAN, MAN, PAN, LAN
Ans: PAN, WAN, LAN, MAN

Q.. What is routing?


Ans: Routing is the process of selecting paths to move information across networks When a data packet
reaches a router, the router selects the best route to the destination network from js routing table and
forwards the data packet to the neighbouring router as per the selected best path. This way each router
keeps passing the data packet(s) to its neighbouring router on best route the destination and finally the
data packet reaches its destination.

Q. . What are the similarities and differences between bus and tree topologies?
Ans: Similarities: In both Bus and Tree topologies transmission can be done in both the directions, and
can be received by all other stations. In both cases, there is no need to remove packets from the medium.
Differences: Bus topology is slower as compared to tree topology of network. Tree topology is
expensive as compared to Bus Topology

Q.. What are the limitations of star topology?


Ans: Requires more cable length than a linear topology. If the hub, switch, or concentrator fails, nodes
attached are disabled. More expensive than linear bus topologies because of the cost of the hubs, etc.

Q.. When do you think, ring topology becomes the best choice for a network?
Ans: Ring topology becomes the best choice for a network when, short amount of cable is required.
No wiring closet space requires.

Q.. Write the two advantages and two disadvantages of Bus Topology in network.
Ans. ADVANTAGE: Easy to connect a computer or peripheral to a linear bus. Requires less cable
length than a star topology
.
DISADVANTAGE: Slower as compared to tree and star topologies of network. Breakage of wire at
any point disturbs the entire
Q.. Define the following:

(i)RJ-45 (ii) modem

(iii) Ethernet card (iv)firewall (v)Switch


Ans: (i) RJ-45: RJ45 is a standard type of connector for network cables and networks. It is an
8-pin connector usually used with Ethernet cables.
(ii) MODEM: Modem stands for Modulation Demodulation. A modem converts the digital data
signals into analogue data signals..
(iii)Ethernet card: The computers parts of Ethernet are connected through a special card
called Ethernet card. It contains connections for either coaxial or twisted pair cables.
(iv) firewall: A firewall is a network security device, either hardware or software-based, which
monitors all incoming and outgoing traffic and based on a defined set of security rules
(v)Switch: A Switch is a small hardware device that joins multiple computers together
within one local area network (LAN).

Q.. Differentiate between


(a) hub and switch.
Ans: Hubs are basic network devices that do not perform packet filtering or addressing function; they
send the data packets to all the connected devices. Switches, on the other hand, connect several
devices in a network. Switches are mostly utilised to transmit data packets between various network
devices such as routers and servers.

(b) Bridge and gateway


Ans: Bridge connects two different LAN working on same protocol. While gateway will settle for and
transfer the packet across networks employing a completely different protocol.

Q.. Match the protocols with funtions :


Protocol Function

1.SMTP a. Transfer of files over internet

2. FTP b. retrieve mails from recipient’s server

3. POP c. Request response protocol between server and client

4. HTTP d. Transfer mail from one user to other user

Answer: 1.d, 2. a, 3.b,4.c

Q. Define web browser and web server.


Ans: Web Browser: A Web Browser is software which used for displaying the content on web page(s).
It is used by client to view web sites.

Example of Web browser – Google Chrome, Fire Fox, Internet Explorer, Safari, Opera, etc.
Web Server: A Web Server is software which fulfills the request(s) done by web browser. Web server
have different ports to handle different request from web browser like generally FTP request is handle
at Port 110 and HTTP request is handle at Port 80. Example of Web server are – Apache, IIS

Long Answer Type Questions (5 marks)

Q: Uplifting Skills Hub India is a knowledge and skill community which has an aim to
uplift the standard of knowledge and skills in society. It is planning to set up its
training centres in multiple towns and villages pan India with its head offices in the nearest cities. They
have created a model of their network with a city, a town, and 3 villages as follows.
As a network consultant, you have to suggest the best network related solutions for their issues/ problems
raised in (i) to (iv) keeping in mind the distance between various locations and given parameters.
Note:
In Villages, there are community centers, in which one room has been given as a
training center for this organization to install computers. The organization has got financial support
from the government and top IT companies.
i. Suggest the most appropriate location of the SERVER in the B_HUB (out of the 4 locations), to get
the best and effective connectivity. Justify your answer.
ii. Suggest the best-wired medium and draw the cable layout (location to location) to efficiently
connect various locations within the B_HUB.
iii. Which hardware device will you suggest to connect all the computers within each location of
B_HUB?
iv. Which service/protocol will be most helpful to conduct live interactions of Experts from Head
Office and people at all locations of B_HUB?
v. What kind of network will be formed between city head office and town?
Ans:
i. B-TOWN can house the server as it has the maximum no. of computers.
ii. The optical fiber cable is the best for this star topology.

iii. Switch device - connecting all the computers within each location of B_HUB
iv. VoIP- Voice Over Internet Protocol
v. MAN
Q: Rehaana Medicos Centre has set up its new centre in Dubai. It has four buildings as shown in the
diagram given below:
Distances between various buildings are as follows:
Accounts to Research Lab 55 m

Accounts to Store 150 m

Store to Packaging Unit 160 m

Packaging Unit to Research Lab 60 m

Accounts to Packaging Unit 125 m

Store to Research Lab 1 80 m

No of Computers
Accounts 25

Research Lab 100

Store 15

Packaging Unit 60

As a network expert, provide the best possible answer for the following
queries:
i) Suggest a cable layout of connections between the buildings.
ii) Suggest the most suitable place (i.e. buildings) to house the server of
this organization.
iii) Suggest the placement of the Repeater device with justification.
iv) Suggest a system (hardware/software) to prevent unauthorized access to or from the network.
(v) Suggest the placement of the Hub/ Switch with justification.
Ans:
(i)
(ii) Research Lab
(iii) With respect to above topology repeater is not needed, as none of the distance is above 100m
(iv) Firewall
(v) Switch is better than hub being unicast, secure and fast device. It is needed in all buildings

Q: PVS Computers decided to open a new office at Ernakulum, the office consist of Five Buildings
and each contains number of computers. The details are shown below.

building 1 building 2

building 3 building 4 building 5

Computers in each building are networked but buildings are not networked so far. The Company has
now decided to connect building also.
(i) Suggest a cable layout for connecting the buildings
(ii) Do you think anywhere Repeaters required in the campus? Why?
(iii) The company wants to link this office to their head office at Delhi
(a) Which type of transmission medium is appropriate for such a link?
(b) What type of network would this connection result into?
(iv) Where server is to be installed? Why?
(v) Suggest the wired Transmission Media used to connect all buildings efficiently.

(i) Any efficient layout with shortest Wire length


(ii) Between 3 and 4 due to larger distance
(iii) (a) Wireless (b) WAN
(iv) Building-3 due to maximum no of Computers
(v) Co- axial cable or fibre optics
(1 mark for each correct answer)

Q: “VidyaDaan” an NGO is planning to setup its new campus at Nagpur for its
web-based activities. The campus has four (04) UNITS as shown below:

(i) Suggest an ideal topology for connecting the above UNITs.

(ii) Suggest the most suitable place i.e. UNIT to install the server for the above

NGO.

(iii) Which network device is used to connect the computers in all UNITs?

(iv) Suggest the placement of Repeater in the UNITs of above network.


(v) NGO is planning to connect its Regional Office at Kota, Rajasthan. Which out of the following
wired communication, will you suggest for a very high-speed connectivity?

(a) Twisted Pair cable (b) Ethernet cable (c) Optical Fibre

Ans:

(i) Bus and Star topology both possible

(ii)ADMIN

(iii) Switch

(iv)

1. ADMIN & RESOURCE

2. ADMIN & FINANCE

(v) (c) Optical Fiber

Q: “China Middleton Fashion” is planning to expand their network in India,


starting with two cities in India to provide infrastructure for distribution of
their product. The company has planned to set up their main office units in
Chennai at three locations and have named their offices as “Production
Unit”, “Finance Unit” and “Media Unit”. The company has its corporate unit
in New Delhi. A rough layout of the same is as follows:
INDIA

Approximate distances between these Units is as follows:


i) Suggest the kind of network required (out of LAN, MAN, WAN) for connecting each of the
following office units:
a. Production Unit and Media Unit
b. Production Unit and Finance Unit
ii) Which of the following communication media, will you suggest to be procured by the company for
connecting their local offices in Chennai for very effective communication? Ethernet Cable, Optical
Fiber, Telephone Cable.
iii) Which of the following devices will you suggest for connecting all the computers within each of
their office units?
*Switch/Hub *Modem *Telephone
iv) Suggest a cable layout for connecting the company’s local office units in Chennai.
v) Suggest the most suitable place to house the server for the organization with suitable reason.

(i)(a) Production Unit and Media Unit :MAN


(b)Production Unit and Finance Unit:LAN
(ii) Switch/Hub
(iii) Optical fiber
(iv) Star Topology
(v) Server should be placed in the Production Unit as it has maximum number
of computers.

Q ‘SmartEdu’ is an educational organization is planning to setup its new campus at Cochin for its web
based activities. The campus has four compounds as shown in the diagram.

Computers in each building are networked but buildings are not networked. The company has now decided
to connect the buildings.
i) Suggest a most suitable cable layout for the above connection
ii) Suggest most suitable topology of the connection between the building.
iii) Suggest the most suitable building to place the server by giving suitable reason.
iv) Suggest the placement of the following devices
a) Repeater b) Hub/Switch
v) Organization is planning to link its head office in Chennai. Suggest an efficient medium for efficient
data communication.
Ans:- (i)
(ii) Star topology
(iii) Training Compound, as per 80:20 rule maximum computers mean maximum internal traffic
(iv) between Main to Training, resource to Training and Training to Finance as distance is greater than
100m
(v) Optical Fibre
RDBMS: Relational Database Management System

Relation • Table in RDBMS

Attribute • Columns name of a table

Tuple • Rows of table

Domain • Pool of values for Attributes

Degree • total number of attributes(columns)

cardinality • total number of tuples(rows)

STRUCTURED QUERY LANGUAGE

TYPES OF COMMAND

DATA
TYPES OF CONSTRAINTS
DATA DEFINITION MANIPULATION TRANSACTION
LANGUAGE (DDL) LANGUAGE (DML) CONTROL
COMMANDS LANGUAGE (TCL)
COMMANDS PRIMARY KEY
INSERT COMMAND
CREATE TABLE
CHECK
COMMAND
SAVEPOINT
COMMAND FOREIGN KEY
SELECT COMMAND
ALTER TABLE
COMMAND
COMMIT COMMAND NOT NULL
UPDATE
COMMAND

DROP TABLE DEFAULT


COMMAND
DELETE COMMAND ROLLBACK
COMMAND

SQL: Interface with Python

step1 :
• import pymysql or mysql.connector

step2
• mydb=mysql.connector.connect(host="____",user="____",passwd="______")

step3
• mycursor=mydb.cursor()

step4
• mycursor.execute("______SQL QUERY__________")
Database Management System

DATABASE:

➢ May be defined as a collection of interrelated data stored together to serve


multipleapplication
➢ It is computer based record keeping system.
➢ It not only allows to store but also allows us modification of data as per requirements
DBMS:
➢ A DBMS refers to Database Management System
➢ It is a software that is responsible for storing, manipulating, maintaining and
utilizingdatabase.
➢ A database along with a DBMS is referred to as a database system.
➢ There are various DBMS software available in the market like :- Oracle, MS SQL
Server, MySQL, Sybase, PostgreSQL, SQLite
Purpose of DBMS:
➢ Reduced Data redundancy –
➢ Control Data Inconsistency
➢ Sharing of data
➢ Ensure data integrity
➢ Enforce standard

Relational Database Model:


➢ In relational database model data is organized into table (i.e. rows and columns).
➢ These tables are also known as relations.
➢ A row in a table represent relationship among a set of values.
➢ A column represent the field/attributes related to relation under which information
willbe stored.
➢ For example if we want to store details of students then : Roll, Name, Class, Section,
etc.will be the column/attributes and the collection of all the column information will
become a Row/Record
Sample Tables:
EMPLOYEE:

Dept:
Deptno dname Loc
10 Accounting New York
20 Research Dallas
30 Sales Chicago
40 Operations Bostan
Component of a table:
➢ Byte: group of 8 bits and is used to store a character.
➢ Data Item: smallest unit of named data. It represent one type of information and
oftenreferred to as a field or column information
➢ Record : collection of data items which represent a complete unit of information
➢ Table: collection of all Rows and Columns.

Common RDBMS:
➢ Oracle, MS SQL Server, MySQL, IBM DB2, IBM Informix, SAP Sybase, Adaptive
Server Enterprise, SAP Sybase IQ, Teradata, PostgreSQL, SQLite, etc.
➢ Out of these MySQL, PostgreSQL and SQLite are Open source implementation.
MySQL
➢ Runs on virtually all platforms including Linux, Unix and Windows. Popular for web
based application and online publishing. It is a part of LAMP (Linux, Apache, MySQL,
PHP) stack
SQLite
➢ Relational DBMS but it is not client-server database engine rather, it is embedded into
end program. Arguably the most widely deployed database engine as it is used by
severalbrowsers, OS and embedded systems (Mobiles).
PostgreSQL
➢ General purpose object-relational DBMS.
➢ It is the most advanced open source database system. It is free and open source
i.e.source code is available under PostgreSQL license, a liberal open source
license.
Common DBMS Tools for Mobile Devices:
➢ SQL Anywhere, DB2 Everywhere, IBM Mobile Database, SQL Server Compact, SQL
Server Express, Oracle DatabaseLite, SQLite, SQLBase etc.
➢ Out of these SQLite is public domain open source implementation.
Relational Data Model:-

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

Characteristics of relational database are:-


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

Advantages of a relational model are as follows:


➢ Changes made in the table structure do not affect the data access or other
applicationprograms.
➢ Tabular view also provides easier database design, use, implementation
andmanagement.
➢ Built-in query support .
➢ Mathematical operations can be successfully carried out using RDBMS.

The limitations of relational model are:

➢ RDBMS incurs hardware and system software overheads.


➢ The size of database becomes very large.

Various Terms Used in Relational Model: - A relational database is a type of database that
stores and provides access to data points that are related to one another.
Basic Terminologies related to a Relational Database:-

➢ Entity: An entity is something that exists and an object which can be distinctly
identified. For example, student entity, employee entity,
➢ Attribute: The term attribute is also used to represent a column.
➢ Tuple: Each row in a table is known as tuple.
➢ Cardinality of Relation: It is the number of records or tuples in the relation.
➢ Degree of Relation: Number of columns or attributes is known as degree of a relation.
➢ Domain of Relation: It defines the kind of data represented by the attribute.
➢ Body of the Relation: It consists of an unordered set of 0 or more tuples.

Concept of Keys
➢ In relation each record must be unique i.e. no two identical records are allowed in
theDatabase.
➢ A key attribute identifies the record and must have unique values. There are
varioustypes of Keys:
Primary key:

➢ A set of one or more attribute that can identify a record uniquely in the relation is
calledPrimary Key.
➢ There can be only 1 primary key in a table
➢ Allows only distinct (no duplicate) values and also forces mandatory entry (NOT NULL)
i.e. we cannot left it blank.

Candidate Key

➢ In a table there can be more than one attribute which contains unique values.
Thesecolumns are known as candidate key as they are the candidate for primary
key.
➢ Among these database analyst select one as a primary key based on requirement like
must contain unique value, compulsory entry and where maximum searching is done
etc.
Alternate Key

➢ In case of multiple candidate keys, one of them will be selected as Primary Key and
restof the column will serve as Alternate Key
➢ A Candidate Key which is not a primary key is an Alternate Key.

Foreign key

➢ Used to create relationship between two tables.


➢ It is a non-key attribute whose value is derived from the Primary key of another table.
➢ Foreign key column will for the value in Primary key of another table, if present
thenentry will be allowed otherwise data will be rejected.
➢ Primary Key column table from where values will be derived is known as Primary Table
or Master Table or Parent Table and Foreign key column table will be Foreign Table or
Detail Table or Child table.
Example:

From the Above table definition we can observe that the DEPTNO column of EMPLOYEE tableis
deriving its value from DEPTNO of table DEPARTMENT. So we can say that the DEPTNO of
EMPLOYEE table is a foreign key whose value is dependent upon the Primary key columnDEPTNO
of table DEPARTMENT.

REFERENTIAL INTEGRITY:
➢ Used to ensure relationship between records in related tables is valid and user
don’taccidentally delete or change the related data.
➢ Referential integrity can be applied when:
➢ The master table’s column is a Primary Key or has a unique index
➢ The related fields have the same data type
➢ Both tables must belong to same database.
➢ When referential integrity is enforced using Foreign Key you must observe the following
rules:
➢ You cannot enter a value in Child Table which is not available in Master Table’s Primary
key column. However you can enter NULL values in foreign key
➢ You cannot delete a record from Master Table if matching record exists in related table.
➢ You cannot modify or change the Primary Key value in Master table if its matching record
is present in related table.
Structured Query Language
➢ It is a language that enables you to create and operate on relational databases
➢ It is the standard language used by almost all the database s/w vendors.
➢ Pronounced as SEQUEL
➢ It is portable i.e. it is compatible with most of the database.
➢ It is not a case sensitive language.
➢ It is very easy to learn.
SQL – features
➢ Allows creating/modifying a database’s structure
➢ Changing security settings for system
➢ Permitting users for working on databases or tables
➢ Querying database
➢ Inserting/modifying/deleting the database contents
Classification of SQL
➢ DDL (Data Definition Language)
➢ DML (Data Manipulation Language)
➢ DCL (Data Control Language)
➢ TCL (Transaction Control Language)
Data Definition Language:
➢ It allows to create database objects like creating a table, view or any other
databaseobjects.
➢ The information about created objects are stored in special file called DATA
DICTIONARY
➢ DATA DICTIONARY contains metadata i.e. data about data.
➢ The commands of DDL are –
o CREATE – To create a new database object
o ALTER – To modify existing database object
o DROP – To permanently remove existing database object.
Data Manipulation Language:
➢ It allows to perform following operation on data in the table
➢ Retrieval of information stored in table
➢ Insertion of new data in table
➢ Modification of existing data in table
➢ Deletion of existing data from table
➢ DML is of 2 type
➢ Procedural DML (in this we specify what data is needed and how to get it)
➢ Non-Procedural DML (in this we specifywhat data is needed
withoutspecifying how to get it)
➢ The commands of DML are
o SELECT – To retrieve data from the table
o INSERT – To insert new tuple/row in the table
o UPDATE – To update existing tuple/row from the table
o DELETE – To delete existing tuple/row from the table

Exercise
:

1. What is Database? What are the advantages of Database System?


2. What is DDL and DML? Give examples of command belonging to each category
3. What is the difference between Primary key and Candidate key
4. What is Primary Key? What are the restriction imposed by Primary Key? How many primary
key can be applied on a Table?
5. What is Degree and Cardinality of table?
6. Explain the purpose of DDL and DML commands used in SQL. Also give two examples of
each
Introduction of MYSQL
Brief history of MySQL:

➢ MySQL is freely available open source RDBMS


➢ It can be downloaded from www.mysql.org
➢ In MySQL information is stored in Tables.
➢ Provides features that support secure environment for storing, maintaining and
accessingdata.
➢ It is fast, reliable, scalable alternative to many of the commercial RDBMS today.
➢ It is developed and supported by MySQL AB, a company based in Sweden.
➢ This company is now subsidiary of Sun Microsystems. On April 2009 Oracle Corp.
acquires Sun Microsystems.
➢ The chief inventor of MySQL was Michael Widenius(a.k.a Monty).
MySQL has been named after Monty’s daughter My. The logo of MySQL is dolphin and
name of that dolphin is ‘Sakila’.

MYSQL DATABASE SYSTEM:

➢ MySQL database system refers to the combination of a MySQL server instance and
MySQL database.
➢ It operates using Client/Server architecture in which the server runs on the
machinecontaining the database and client connects to server over a network
➢ MySQL is a multiuser database system, meaning several users can access the
databasesimultaneously.

The Server

➢ Listens for client requests coming in over the network and access the database as per
therequirements and provide the requested information to the Client.

The Client

➢ Are the programs that connect to MySQL server and sends requests to the server and
receives the response of Server. Client may be the MySQL prompt or it may be Front-end
programming which connect to server programmatically like connecting to MySQL using
Python Language or Java or any other language.

FEATURES OF MYSQL:

➢ Speed - MySQL runs very fast.


➢ Ease of Use -Can be managed from command line or GUI
➢ Cost Is available free of cost. It is Open Source
➢ Query language Support -Supports SQL
➢ Portability – Can be run on any platform and supported by various compilers
➢ Data Types - supports various data types like Numbers, Char etc.
➢ Security -Offers privileges and password systems that is very flexible and secure.
➢ Scalability and Limits -Can handle large databases. Some of real life MySQL databases
contains millions of records.
➢ Connectivity-Clients can connect to MySQL using drivers
➢ Localization -The server can provide error message to client in many language
➢ Client and Tools -Provides several client and utility programs. Like mysqldump and
mysqladmin. GUI tools like MySQL Administration and Query Browser.

STARTING MYSQL:

Click on Start →All Programs →MySQL → MySQL Server→ MySQL →Command LineClient

To exit from MySQL type exit or quit in front of MySQL prompt.


SQL and MYSQL:
➢ SQL stands for Structured Query Language.
➢ It is a language that enables you to create and operate on relational databases.
➢ MySQL uses SQL in order to access databases.
➢ It is the standard language used by almost all the database s/w vendors.
MYSQL Elements
➢ Literals
➢ Data types
➢ Nulls
➢ Comments
Literals
➢ It means the fixed value or constant value. It may be of character, numeric or date
timetype.
➢ Character and date/time literals are always in single quotation marks whereas
numericliterals must be without single quotation marks
➢ For example – ‘Virat’, 12, 12.56, ‘04-20-2018’
➢ Date and time values are always in the format YYYY-MM-DD HH:MI:SS
➢ Special character like quotes are always written be preceding it back-slash(\). For
example if we want to store value as Tom’s Cat then it should be written as Tom\’s
Cat
Data Type
➢ Means the type of value and type of operation we can perform on data. For example
onnumeric value we can store numbers and perform all arithmetic operations and so
on.
➢ MySQL support three categories of data types:
➢ Numeric
➢ Date and time
➢ String types

➢ Numeric Data Types

Data type Description

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


2147483647
TINYINT Small integer value between 0 – 255 (4 digits)

SMALLINT More than TINYINT between -32768 to 32767 (5 digit)

MEDIUMINT Integer values up to 9 digits

BIGINT Very large integer value up to 11 digits

FLOAT(M,D) Real numbers i.e. number with decimal. M specify length


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

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


D)
DECIMAL It is used to store exact numeric value that preserve exact
precision for e.g. money data in accounting system.
DECIMAL(P,D) means P no. of significant digits (1-65), D
represent no. of digit after decimal(0-30), for e.g
DECIMAL(6,2) means 4 digit before decimal and 2 digit
after decimal. Max will be 9999.99
Date and Time Types
➢ DATE-A date in YYYY-MM-DD format between 1000-01-01 to 9999-12-31.
➢ DATETIME-Combination of date and time. For example to store 4th December 2018
and time is afternoon 3:30 then it should be written as – 2018-12-04 15:30:00
➢ TIMESTAMP - Similar to DATATIME but it is written without hyphen for
example the above date time is stored as 20181204153000
➢ TIME-To store time in the format HH:MM:SS
➢ YEAR(M) -To store only year part of data where M may be 2 or 4 i.e. year in 2 digit
like 18 or 4 digit like 2018.
String Types
➢ CHAR(M)
o Fixed length string between 1 and 255.
o It always occupy M size, irrespective of actual number of characters entered.
o Mostly use in the case where the data to be insert is of fixed size like
Grade(A,B,C,..) or Employee code as E001, E002, etc
➢ VARCHAR(M)
o Variable length string between 1 and 65535 (from MySQL 5.0.3) , earlier it was
255
o It takes size as per the data entered for example with VARCHAR(20) if the data
entered is MOBILE then it will take only 6 byte.
o It is useful for the data like name, address where the number of character to
beenter is not fixed.
➢ Difference between CHAR & VARCHAR

Char varchar
Fixed length string Variable length string
Fast, no memory allocation every time Slow, as it take size according to data so every
time memory allocation is done
It takes more memory It takes less space
Simple Queries in SQL
➢ Show Databases- This command is used to list all databases on MySql Server
➢ Use <databasename>- This command is used to change/select/open given database
e.g. To open a database named ‘test’
>>> use test
➢ Show tables – This command will list all the tables from current database. If no database
isselected it will generate error.
➢ Select database () – This command will display the name of current database.
➢ Desc <tablename> or Describe <tablename> - This command will be used to display the
structure of the table.

The above figure display the use of describe command

➢ Create database <databasename> - This command is use to create a new


database.For example – create database mydb will new database mydb
Above command will generate error, if database already exist. To supress the error following
command can be used

create database if not exist mydb

➢ Drop database <databasename> - This command is used to remove existing database.


For example – drop database mydb will permanently delete mydb database.
Above command will generate error, if database already exist. To supress the error following
command can be used

drop database if exist mydb

➢ Create table <tablename> - This command / statement is used to create a new table in
adatabase. The syntax the is

CREATE TABLE table_name ( column1


datatype[(size)] [constraint] ,column2
datatype[(Size)] [constraint],
column3 datatypeI[(size)] [constraints] ,
....
);
Here size and constraints are optional.
a. g.
CREATE TABLE pet (
name VARCHAR(20),
owner VARCHAR(20),
species
VARCHAR(20),sex
CHAR(1),
birth DATE, death DATE);

➢ Drop table <tablename> - This command is used to permanently delete the table from
database.
For example, drop table pet; will delete pet table from database
➢ Alter table <tablename> - This command is used to modify the structure of existing table
such as adding new column, removing existing column, rename or changing data type, size
and constraints.
o Adding new column to exiting
tableSyntax :

Alter table <tablename>


Add [column] column_name datatype [(size)];

o Removing new existing column from the table


Syntax:
Alter table <tablename>
drop column <column_name>;

o Changing datatype/size of the column


Systax:
alter table <tablename>
modify column <colname> datatype(size);

o Renaming column name


Alter table tablename
Change old_columnname new_column_name datatype (size)

➢ Update <tablename> - This command is used to update data from the


tableSyntax:

UPDATE table_name SET column_name=new_value, column2_name=new_value


WHERE condition;
e.g. UPDATE emp set sal=sal+100 where ename =’Scot’

The above query will update salary of Scot by 100.


If where clause is not given, it will update/modify the value of column from each row.
➢ Inserting into table_name – This command is used to add new row to the

tableSyntax :

INSERT INTO table_name VALUES (list of values)

➢ Select data from Table using Select statement


Syntax:
Select clause select */column_list
from clause from table(s)
where clause where condition
group by clause group by column_name
having clause having condition
order by clause order by column_name asc/desc
limit clause; limit m,n;
➢ Selecting/displaying entire data from the table
Syntax:
SELECT * From tablename;

➢ Selecting/displaying data from specific column


Syntax:
SELECT column1, column2, column3, …. FROM tablename;

➢ Giving descripting name for column using column alias


Syntax:
SELECT */col_name as ‘alias1’ FROM tablename;

➢ Removing duplicate value from the column using distinct clause


Syntax:
SELECT DISTINCT column_name FROM tablename;

➢ Display all data from column using all clause


Syntax:
SELECT ALL column_name FROM tablename;

➢ Inserting text in the


querySyntax:
SELECT ‘text’ FROM tablename;
Number of row in result depend on total number of rows in the table
➢ Performing simple calculation in the
querySyntax:
Select 2+4;
All operation can be perform such as addition (+), subtraction (-), multiplication (*), division(/)
and remainder (%)

Number of row in result depend on total number of rows in the table

➢ Performing calculation on
columnSyntax:
SELECT column1 operator value, column2…. FROM Tablename

➢ Working with null value


Any operation on NULL will result into NULL, MySql provide ifnull() function to workwith
null value. If column contain null value it is replace value given value, otherwise display
original value.

Syntax:
ifnull(column, value_to_replace’)
Here, comm column contains null value which is replaced by ‘N/A’.

➢ Restricting rows using where clause


Where clause in the query will restrict number of rows in the output based on condition.
Syntax:
SELECT */column list
FROM Tablename
where condition ;
Condition (column_name operator expression)

Relational Operator
> greater than
< less than
>= greater than equal to
<= less than equal to
= equal
! = or <> not equal to
Logical Operator
And – evaluated true if all the logical expression is true otherwise
false.Or - evaluated true if any the logical expression is true otherwise
false. Logical operator is used to combine two or more logical
expression,
Membership Operator
in – Not
in
The IN operator allows you to specify multiple values in a WHERE clause.The
IN operator is a shorthand for multiple OR conditions.
Comparing NULL
is null – is
not null
NULL (Absence of value) value cannot be compared using Relational operator. The
above statement is used to check whether column contains NULL or not.
Range Operator
Between
Pattern Matching
Like
Not Like

Like clause is used to match pattern using two wild card characters
_ (underscore) – single unknown character
% (modulo) - Zero or more unknown characters
e.g.
words staring with ‘t’ ‘t%’
words ending with ‘t’ ‘%t’
words containing ‘t’ - ‘%t%’
word with ‘t’ as second letter - ‘_t%’
words with ‘t’ as third last character – ‘%t_ _’
words containing four letter and ‘t’ as second letter – ‘_ t_ _’

➢ Ordering data using ORDER BY clause


• ORDER BY clause is used to arrange data in ascending/descending order
• Ordering can be done on more than one column, in this case data is
arrangedaccording first column and then second column and onwards.
• By default data is arranged in ascending order, in no ordering information
(asc/desc)is given.

Syntax:

SELECT */col_list
FROM tablename
ORDER BY col1 asc/desc, col2 asc/desc;
Aggregate Functions
➢ An aggregate function performs a calculation on multiple values and returns a
singlevalue.
➢ These function work on multiple rows collectively return single value.
➢ List of Aggregate functions are
o max() : return maximum value in set of value

o min() – return minimum value from the set of values


o avg() –return average value in set of non-null values
o sum() - Return the summation of all non-NULL values of the set of values.

o count() - Return the number of rows in a group


▪ Count(*) – return number of rows, including rows with NULL

▪ Count(column_name) - return number of rows, excluding rows with


NULL for the given column

▪ Count (distinct column_name) – return number of rows with


duplicateremoved

In above example there are 14 row in the EMP table, but distinct clause
only consider unique value.
➢ Group By Clause

o It is used in a SELECT statement to collect data across multiple records and group
the results by one or more columns.
Syntax:
SELECT column_name, aggregate_function
FROM table_name
GROUP BY column_name
In above example salary is grouped on job and maximum salary from each job isdisplayed.
o Select clause involving group by clause can contain column present in group by
clause, aggregate function or no column. Otherwise it will return random data
fromother column as given below.

➢ Having clause –
o Having clause is used to place condition on aggregate function in conjunction
withgroup by clause.
o Having clause in placed after where clause in select statement.
Syntax:
SELECT columm_name, aggregate_function(col_name)
FROM table
WHERE condition GROUP BY
column_name
HAVING aggregate_function(column_name) operator expression;

The above query will display deptno, maximum salary and number of employees from
each department.
The query given below display deptno, maximum salary and number of employees
from those department which have maximum salary greater than equal to 3000.

As condition is on aggregate function max(), where clause can’t be used in this case.
Exercise Questions:
1. What is MySQL used for? Abhay wants to start learning MySQL. From where can he obtain the
MySQL software ?
2. In the table “Student”, Priya wanted to increase the Marks(Column Name:Marks) of those students
by 5 who have got Marks below 33. She has entered the following statement:
3. SELECT Marks+5 FROM Student WHERE Marks<33;
Identify errors(if any) in the above statement. Rewrite the correct SQL statement.

4. Write SQL statement to add a column ‘‘COUNTRY’’ with data type and size as VARCHAR(70) to the
existing table named ‘‘PLAYER’’. Is it a DDL or DML or TCL command ?
5. Table Student has the columns RNO and SCORE. It has 3 rows in it. Following two SQL statements
were entered that produced the output (AVG(SCORE) as 45 and COUNT(SCORE) as 2) :
(i) AVG(SCORE)
(ii) Count(score)
6. ‘Employee’ table has a column named ‘CITY’ that stores city in which each employee resides. Write
SQL query to display details of all rows except those rows that have CITY as ‘DELHI’ or ‘MUMBAI’ or
‘CHANDIGARH’.
7. How is a database related to a table ?
Write SQL query to create the above table with appropriate data types and sizes of columns.

8. Ms. Rajshri is the Class Teacher of Class XII. She wants to create a table named ‘Student’ to store
marks in different subjects of her class. Identify any 4 columns for the table along with their suitable
data types.
9. “XYZ” Company conducts workshops for employees of organizations. The company requires
data of workshops that are organized. Write SQL query to create a table ‘Workshop’ with the
following structure:

10. Ariya wants to add another column ‘Gender’ in the already existing table ‘CUSTOMERS’. She
has written the following statement. However, it errors. Rewrite the correct statement.
MODIFY TABLE CUSTOMERS GENDER char(1);

11. Explain the following statement with the help of example:


12. “In a transaction either all the SQL statements be committed or all rolled back.”
13. How is HAVING clause similar to WHERE clause? How is HAVING clause different from WHERE
clause? Explain with the help of examples of each.
14. Consider the following table ‘Transporter’ that stores the order details about items to be
transported. Write SQL commands for the statements (i) to (viii).
Table : TRANSPORTER
ORDERNO DRIVERNAME DRIVERGRADE ITEM TRAVELDATE DESTINATION
10012 RAM YADAV A TELEVISION 2019-04-19 MUMBAI
10014 SOMNATH FURNITURE 2019-01-12 PUNE
10016 MOHAN VERMA B WASHING MACHINE 2019-06-06 LUCKNOW
10018 RISHI SINGH A REFRIGERATOR 2019-04-07 MUMBAI
10019 RADHE MOHAN TELEVISION 2019-05-30 UDAIPUR
10020 BISHEN PRATAP B REFRIGERATOR 2019-05-02 MUMBAI
10021 RAM TELEVISION 2019-05-03 PUNE

(i) To display names of drivers and destination city where TELEVISION is being transported.
(ii) To display driver names and destinations where destination is not MUMBAI.
(iii) To display the names of destination cities where items are being transported. There
should be no duplicate values.
(iv) To display details of rows that have some value in DRIVERGRADE column.
(v) To display names of drivers, names of items and travel dates for those items that are
being transported on or before 1st April 2019.
(vi) To display the number of drivers who have ‘MOHAN’ anywhere in their names.
(vii) To display the names of drivers, item names and travel dates in alphabetic (ascending)
order of driver names.
(viii) To display names of drivers whose names are three characters long.

17. In CHAR(10) and VARCHAR(10), what does the number 10 indicate ?

18. ‘Employee’ table has a column named ‘CITY’ that stores city in which each employee resides. Write
SQL query to display details of all rows except those rows that have CITY as ‘DELHI’ or ‘MUMBAI’ or
‘CHANDIGARH’.

19.Consider the table given below. Write SQL queries for (i) to (vii).
Table : Gym
REGID NAME PREWEIGHT CURRWEIGHT DOJ GENDER BRANCH

1001 SHEELA SIA 115 98 2017-09-02 F ADARSH VIHAR

1002 FAWAD KHAN 92 80 2018-10-11 M MODEL TOWN

1003 PAWAN SINGH 85 80 2018-02-03 M NIRMAN NAGAR

1004 SUPRIYA ARORA 113 100 2018-01-16 F MODEL TOWN

1005 AJOY BASU 67 75 2017-12-09 M NIRMAN NAGAR

1006 TANMAY JACOB 100 71 2017-11-18 M ADARSH VIHAR

1007 LAKSHMI VENKAT 98 95 2018-06-09 F MODEL TOWN

Columns REGID stores Registration Id, PREWEIGHT stores weight of the person before joining Gym,
CURRWEIGHT stores current weight, DOJ stores Date of Joining, BRANCH stores the branch of Gym
where the person has enrolled.

(i) To display names of members along with their previous and current weights who are in
Model Town branch.
(ii) To display all names of members, previous weight, current weight, Change in weight (i.e.
how much increase from previous weight or decrease from previous weight, Decrease will
be displayed with negative sign)
(iii) To display BRANCH wise count of members in the Gym. (i.e. display the BRANCH and
number of members in each BRANCH)
(iv) To display names and date of joining of all the members who joined in the year 2018.
(v) To display Names and Current weight of all the members in descending order of Current
Weight.
(vi) To display the names and date of joining of male members who have joined after 27 th
September 2018.
(vii) To display names and date of joining of members who have their names starting with ‘S’
and ending with ‘a’.

20. Consider the table Flight given below, write command in SQL for (i) to (iv) and output for (v) to (viii)

Table : FLIGHT

Flight_N Origin Destination Seats FlightDate Rate


o

1005 Varanasi Nepal 275 12-Dec-07 3000

2785 Delhi Kerala 290 17-Jan-08 5500

6587 Mumbai Varanasi 435 19-Feb-08 5000

1265 Varanasi Nepal 200 02-Jan-08 5400


4457 Delhi Lucknow 150 22-Feb-08 4500

6856 Varanasi Mumbai 180 03-Mar-08 6000

i) To display Flight flying between Varanasi and Nepal.


ii) To display the different Origin of Flights.
iii) To display list of flights in descending order of Rate.
iv) To display flight details of the flight whose flightdate is after Jan 2008.
v) SELECT Flight_No, Destination FROM Flight WHERE Destination LIKE ‘_u%’;
vi) SELECT Origin, COUNT(*) FROM Flight GROUP BY Origin;
vii) SELECT Origin, Destination FROM Flight WHERE seats>400;
viii) SELECT SUM(Rate),MAX( Seats) FROM Flight;
Joins
➢ A relational database consists of multiple related tables linking together using
commoncolumns, which are known as foreign key columns.
➢ It is used retrieve data from multiple tables.
➢ Consider the tables below EMP, DEPT & SALGARDE that stored related information,all
the examples on join will be explained with help of these following three tables

EMP Table

empno ename job mgr hiredate sal comm deptno


7369 SMITH CLERK 7902 1993-06-13 800.00 0.00 20
7499 ALLEN SALESMAN 7698 1998-08-15 1600.00 300.00 30
7521 WARD SALESMAN 7698 1996-03-26 1250.00 500.00 30
7566 JONES MANAGER 7839 1995-10-31 2975.00 20
7698 BLAKE MANAGER 7839 1992-06-11 2850.00 30
7782 CLARK MANAGER 7839 1993-05-14 2450.00 10
7788 SCOTT ANALYST 7566 1996-03-05 3000.00 20
7839 KING PRESIDENT 1990-06-09 5000.00 0.00 10
7844 TURNER SALESMAN 7698 1995-06-04 1500.00 0.00 30
7876 ADAMS CLERK 7788 1999-06-04 1100.00 20
7900 JAMES CLERK 7698 2000-06-23 950.00 30
7934 MILLER CLERK 7782 2000-01-21 1300.00 10
7902 FORD ANALYST 7566 1997-12-05 3000.00 20
7654 MARTIN SALESMAN 7698 1998-12-05 1250.00 1400.00 30

DEPT Table

deptno dname location


10 Accounting New York
20 Research Dallas
30 Sales Chicago
40 Operations Boston
SALGRADE Table

grade losal hisal


1 700.00 1200.00
2 1201.00 1400.00
4 2001.00 3000.00
5 3001.00 99999.00
3 1401.00 2000.00
➢ Types of Join
❖ Cartesian Product or Cross join
❖ Equi Join
❖ Natural Join
❖ Non-Equi Join
❖ Self Join
❖ Left Outer Join
❖ Right Outer Join
➢ Cartesian Product or Cross join
❖ The cross join makes a Cartesian product of rows from the joined tables.
❖ The cross join combines each row from the first table with every row from
theright table to make the result set.
❖ If Table1 has degree d1 and cardinality c1 and table2 has degree d2 and
cardinality c2, their Cartesian Product has degree d=d1+d2 and
cardinalityc=c1*c2;

Ven Diagram

Syntax:
SELECT * FROM table1, table2;Or

SELECT * FROM table1 CROSS JOIN table2;Or

SELECT * FROM table1 JOIN table2;


e.g. SELECT * FROM emp, dept;
SELECT * FROM emp CROSS JOIN dept;SELECT

* FROM emp JOIN DEPT;

Output:

+ + + + + + + + + + + +

| empno | ename | job | mgr | hiredate | sal | comm | deptno | deptno | dname | loc |

+ + + + + + + + + + + +
| 7369 | SMITH | CLERK | 7902 | 1980-12-17 | 800.00 | NULL | 20 | 10 | ACCOUNTING | NEW YORK |

| 7369 | SMITH | CLERK | 7902 | 1980-12-17 | 800.00 | NULL | 20 | 20 | RESEARCH | DALLAS |

| 7369 | SMITH | CLERK | 7902 | 1980-12-17 | 800.00 | NULL | 20 | 30 | SALES | CHICAGO |

| 7369 | SMITH | CLERK | 7902 | 1980-12-17 | 800.00 | NULL | 20 | 40 | OPERATIONS | BOSTON |

| 7499 | ALLEN | SALESMAN | 7698 | 1981-02-20 | 1600.00 | 300.00 | 30 | 10 | ACCOUNTING | NEW YORK |

| 7499 | ALLEN | SALESMAN | 7698 | 1981-02-20 | 1600.00 | 300.00 | 30 | 20 | RESEARCH | DALLAS |

| 7499 | ALLEN | SALESMAN | 7698 | 1981-02-20 | 1600.00 | 300.00 | 30 | 30 | SALES | CHICAGO |

| 7499 | ALLEN | SALESMAN | 7698 | 1981-02-20 | 1600.00 | 300.00 | 30 | 40 | OPERATIONS | BOSTON |

| 7521 | WARD | SALESMAN | 7698 | 1981-02-22 | 1250.00 | 500.00 | 30 | 10 | ACCOUNTING | NEW YORK |

| 7521 | WARD | SALESMAN | 7698 | 1981-02-22 | 1250.00 | 500.00 | 30 | 20 | RESEARCH | DALLAS |

| 7521 | WARD | SALESMAN | 7698 | 1981-02-22 | 1250.00 | 500.00 | 30 | 30 | SALES | CHICAGO |

| 7521 | WARD | SALESMAN | 7698 | 1981-02-22 | 1250.00 | 500.00 | 30 | 40 | OPERATIONS | BOSTON |

| 7566 | JONES | MANAGER | 7839 | 1981-04-02 | 2975.00 | NULL | 20 | 10 | ACCOUNTING | NEW YORK |

| 7566 | JONES | MANAGER | 7839 | 1981-04-02 | 2975.00 | NULL | 20 | 20 | RESEARCH | DALLAS |

| 7566 | JONES | MANAGER | 7839 | 1981-04-02 | 2975.00 | NULL | 20 | 30 | SALES | CHICAGO |

| 7566 | JONES | MANAGER | 7839 | 1981-04-02 | 2975.00 | NULL | 20 | 40 | OPERATIONS | BOSTON |

| 7654 | MARTIN | SALESMAN | 7698 | 1981-09-28 | 1250.00 | 1400.00 | 30 | 10 | ACCOUNTING | NEW YORK |

| 7654 | MARTIN | SALESMAN | 7698 | 1981-09-28 | 1250.00 | 1400.00 | 30 | 20 | RESEARCH | DALLAS |

| 7654 | MARTIN | SALESMAN | 7698 | 1981-09-28 | 1250.00 | 1400.00 | 30 | 30 | SALES | CHICAGO |

| 7654 | MARTIN | SALESMAN | 7698 | 1981-09-28 | 1250.00 | 1400.00 | 30 | 40 | OPERATIONS | BOSTON |

| 7698 | BLAKE | MANAGER | 7839 | 1981-05-01 | 2850.00 | NULL | 30 | 10 | ACCOUNTING | NEW YORK |

| 7698 | BLAKE | MANAGER | 7839 | 1981-05-01 | 2850.00 | NULL | 30 | 20 | RESEARCH | DALLAS |

| 7698 | BLAKE | MANAGER | 7839 | 1981-05-01 | 2850.00 | NULL | 30 | 30 | SALES | CHICAGO |

| 7698 | BLAKE | MANAGER | 7839 | 1981-05-01 | 2850.00 | NULL | 30 | 40 | OPERATIONS | BOSTON |

| 7782 | CLARK | MANAGER | 7839 | 1981-06-09 | 2450.00 | NULL | 10 | 10 | ACCOUNTING | NEW YORK |

| 7782 | CLARK | MANAGER | 7839 | 1981-06-09 | 2450.00 | NULL | 10 | 20 | RESEARCH | DALLAS |

| 7782 | CLARK | MANAGER | 7839 | 1981-06-09 | 2450.00 | NULL | 10 | 30 | SALES | CHICAGO |

| 7782 | CLARK | MANAGER | 7839 | 1981-06-09 | 2450.00 | NULL | 10 | 40 | OPERATIONS | BOSTON |

| 7788 | SCOTT | ANALYST | 7566 | 1982-12-09 | 3000.00 | NULL | 20 | 10 | ACCOUNTING | NEW YORK |

| 7788 | SCOTT | ANALYST | 7566 | 1982-12-09 | 3000.00 | NULL | 20 | 20 | RESEARCH | DALLAS |

| 7788 | SCOTT | ANALYST | 7566 | 1982-12-09 | 3000.00 | NULL | 20 | 30 | SALES | CHICAGO |

| 7788 | SCOTT | ANALYST | 7566 | 1982-12-09 | 3000.00 | NULL | 20 | 40 | OPERATIONS | BOSTON |

| 7839 | KING | PRESIDENT | NULL | 1981-11-17 | 5000.00 | NULL | 10 | 10 | ACCOUNTING | NEW YORK |

| 7839 | KING | PRESIDENT | NULL | 1981-11-17 | 5000.00 | NULL | 10 | 20 | RESEARCH | DALLAS |

| 7839 | KING | PRESIDENT | NULL | 1981-11-17 | 5000.00 | NULL | 10 | 30 | SALES | CHICAGO |

| 7839 | KING | PRESIDENT | NULL | 1981-11-17 | 5000.00 | NULL | 10 | 40 | OPERATIONS | BOSTON |


| 7844 | TURNER | SALESMAN | 7698 | 1981-09-08 | 1500.00 | 0.00 | 30 | 10 | ACCOUNTING | NEW YORK |

| 7844 | TURNER | SALESMAN | 7698 | 1981-09-08 | 1500.00 | 0.00 | 30 | 20 | RESEARCH | DALLAS |

| 7844 | TURNER | SALESMAN | 7698 | 1981-09-08 | 1500.00 | 0.00 | 30 | 30 | SALES | CHICAGO |

| 7844 | TURNER | SALESMAN | 7698 | 1981-09-08 | 1500.00 | 0.00 | 30 | 40 | OPERATIONS | BOSTON |

| 7876 | ADAMS | CLERK | 7788 | 1983-01-12 | 1100.00 | NULL | 20 | 10 | ACCOUNTING | NEW YORK |

| 7876 | ADAMS | CLERK | 7788 | 1983-01-12 | 1100.00 | NULL | 20 | 20 | RESEARCH | DALLAS |

| 7876 | ADAMS | CLERK | 7788 | 1983-01-12 | 1100.00 | NULL | 20 | 30 | SALES | CHICAGO |

| 7876 | ADAMS | CLERK | 7788 | 1983-01-12 | 1100.00 | NULL | 20 | 40 | OPERATIONS | BOSTON |

| 7900 | JAMES | CLERK | 7698 | 1981-12-03 | 950.00 | NULL | 30 | 10 | ACCOUNTING | NEW YORK |

| 7900 | JAMES | CLERK | 7698 | 1981-12-03 | 950.00 | NULL | 30 | 20 | RESEARCH | DALLAS |

| 7900 | JAMES | CLERK | 7698 | 1981-12-03 | 950.00 | NULL | 30 | 30 | SALES | CHICAGO |

| 7900 | JAMES | CLERK | 7698 | 1981-12-03 | 950.00 | NULL | 30 | 40 | OPERATIONS | BOSTON |

| 7902 | FORD | ANALYST | 7566 | 1981-12-03 | 3000.00 | NULL | 20 | 10 | ACCOUNTING | NEW YORK |

| 7902 | FORD | ANALYST | 7566 | 1981-12-03 | 3000.00 | NULL | 20 | 20 | RESEARCH | DALLAS |

| 7902 | FORD | ANALYST | 7566 | 1981-12-03 | 3000.00 | NULL | 20 | 30 | SALES | CHICAGO |

| 7902 | FORD | ANALYST | 7566 | 1981-12-03 | 3000.00 | NULL | 20 | 40 | OPERATIONS | BOSTON |

| 7934 | MILLER | CLERK | 7782 | 1982-01-23 | 1300.00 | NULL | 10 | 10 | ACCOUNTING | NEW YORK |

| 7934 | MILLER | CLERK | 7782 | 1982-01-23 | 1300.00 | NULL | 10 | 20 | RESEARCH | DALLAS |

| 7934 | MILLER | CLERK | 7782 | 1982-01-23 | 1300.00 | NULL | 10 | 30 | SALES | CHICAGO |

| 7934 | MILLER | CLERK | 7782 | 1982-01-23 | 1300.00 | NULL | 10 | 40 | OPERATIONS | BOSTON |

+ + + + + + + + + + + +

56 rows in set (0.02 sec)


Note: Above output has 56 row (14*4) and 11 columns (8+3)

➢ Equi Join-
❖ It performs a JOIN against equality or matching column(s) values of the
associatedtables.

Ven Diagram
Syntax

SELECT * /Column_list
FROM Table1, Table 2
WHERE table1.column=Table2.column;Or

SELECT * /Column_list
FROM Table1 join Table2 on Table1.Column=Table2.Column;
Example: SELECT * FROM emp JOIN dept ON emp.deptno=dept.deptno;Or

SELECT * FROM emp, dept WHERE emp.deptno=dept.deptno;


Output:

+ + + + + + + + + + + +

| empno | ename | job | mgr | hiredate | sal | comm | deptno | deptno | dname | loc |

+ + + + + + + + + + + +

| 7369 | SMITH | CLERK | 7902 | 1980-12-17 | 800.00 | NULL | 20 | 20 | RESEARCH | DALLAS |

| 7499 | ALLEN | SALESMAN | 7698 | 1981-02-20 | 1600.00 | 300.00 | 30 | 30 | SALES | CHICAGO |

| 7521 | WARD | SALESMAN | 7698 | 1981-02-22 | 1250.00 | 500.00 | 30 | 30 | SALES | CHICAGO |

| 7566 | JONES | MANAGER | 7839 | 1981-04-02 | 2975.00 | NULL | 20 | 20 | RESEARCH | DALLAS |

| 7654 | MARTIN | SALESMAN | 7698 | 1981-09-28 | 1250.00 | 1400.00 | 30 | 30 | SALES | CHICAGO |

| 7698 | BLAKE | MANAGER | 7839 | 1981-05-01 | 2850.00 | NULL | 30 | 30 | SALES | CHICAGO |

| 7782 | CLARK | MANAGER | 7839 | 1981-06-09 | 2450.00 | NULL | 10 | 10 | ACCOUNTING | NEW YORK |

| 7788 | SCOTT | ANALYST | 7566 | 1982-12-09 | 3000.00 | NULL | 20 | 20 | RESEARCH | DALLAS |

| 7839 | KING | PRESIDENT | NULL | 1981-11-17 | 5000.00 | NULL | 10 | 10 | ACCOUNTING | NEW YORK |

| 7844 | TURNER | SALESMAN | 7698 | 1981-09-08 | 1500.00 | 0.00 | 30 | 30 | SALES | CHICAGO |

| 7876 | ADAMS | CLERK | 7788 | 1983-01-12 | 1100.00 | NULL | 20 | 20 | RESEARCH | DALLAS |

| 7900 | JAMES | CLERK | 7698 | 1981-12-03 | 950.00 | NULL | 30 | 30 | SALES | CHICAGO |

| 7902 | FORD | ANALYST | 7566 | 1981-12-03 | 3000.00 | NULL | 20 | 20 | RESEARCH | DALLAS |

| 7934 | MILLER | CLERK | 7782 | 1982-01-23 | 1300.00 | NULL | 10 | 10 | ACCOUNTING | NEW YORK |

+ + + + + + + + + + + +

Example 1: Display the employee name, sal and name of department name
Ans: In the above query ename and sal belong to emp table whereas dname belongs
toDEPT table. So, to retrieve data in this we will use join
SELECT emp.ename, emp.sal, dept.dname
FROM emp, dept WHERE emp.deptno=dept.deptno;
Output:
+ + + +
| ename | sal | dname |
+ + + +
| SMITH | 800.00 | RESEARCH |
| ALLEN | 1600.00 | SALES |
| WARD | 1250.00 | SALES |
| JONES | 2975.00 | RESEARCH |
| MARTIN | 1250.00 | SALES |
| BLAKE | 2850.00 | SALES |
| CLARK | 2450.00 | ACCOUNTING |
| SCOTT | 3000.00 | RESEARCH |
| KING | 5000.00 | ACCOUNTING |
| TURNER | 1500.00 | SALES |
| ADAMS | 1100.00 | RESEARCH |
| JAMES | 950.00 | SALES |
| FORD | 3000.00 | RESEARCH |
| MILLER | 1300.00 | ACCOUNTING |
+ + + +Note:

❖ In case of join full qualified (table_name.column_name) name is used to avoid


ambiguity as both table contains common columns as PRIMARY KEY and
FOREIGN KEY.
❖ Table Alias – Like column alias table alias can be used in case of join as given
below.

SELECT e.ename, e.sal FROM emp e, dept d WHERE emp.deptno=dept.deptno;

❖ Here ‘e’ & ‘d’ are table alias for EMP & DEPT table respectively.

➢ Non- Equi Join


❖ It uses comparison operator instead of the equal sign like >, <, >=, <= along with join
condition.
Syntax:
SELECT * /Column_list
FROM table1, table2,..
WHERE table1.column relational_operator table2.column;
Note: Where relational operator are other than equality operator and between.

Example: Display the employee name, salary and grade of each employee.
Ans: In the above query the involved table are EMP and SALGRADE.
SELECT e.ename, e.sal, s.grade
FROM emp e, salgarde s
WHERE e.sal BETWEEN s.losal AND s.hisal;Output:

+ + + +
| ename | sal | grade |
+ + + +
| SMITH | 800.00 | 1|
| ALLEN | 1600.00 | 3|
| WARD | 1250.00 | 2|
| JONES | 2975.00 | 4|
| MARTIN | 1250.00 | 2|
| BLAKE | 2850.00 | 4|
| CLARK | 2450.00 | 4|
| SCOTT | 3000.00 | 4|
| KING | 5000.00 | 5|
| TURNER | 1500.00 | 3|
| ADAMS | 1100.00 | 1|
| JAMES | 950.00 | 1|
| FORD | 3000.00 | 4|
| MILLER | 1300.00 | 2|
+ + + +
➢ Natural Join
❖ A natural join is a type of join operation that creates an implicit join by
combiningtables based on columns with the same name and data type.
❖ It makes the SELECT query simpler with minimal use of conditions.
❖ There is no need to specify the name of common column in the SELECT statement.
❖ Common column is present only once in the output.

Syntax:

SELECT */column_list
FROM Table1 NATURAL JOIN TABLE2;

Or

SELECT */column_list
FROM TABLE1 join on common_column_name;

Example :
SELECT * FROM emp JOIN dept USING(deptno);Or
SELECT * FROM emp NATURAL JOIN DEPT;

Output:
+ + + + + + + + + + +

| deptno | empno | ename | job | mgr | hiredate | sal | comm | dname | loc |

+ + + + + + + + + + +
| 20 | 7369 | SMITH | CLERK | 7902 | 1980-12-17 | 800.00 | NULL | RESEARCH | DALLAS |
| 30 | 7499 | ALLEN | SALESMAN | 7698 | 1981-02-20 | 1600.00 | 300.00 | SALES | CHICAGO |
| 30 | 7521 | WARD | SALESMAN | 7698 | 1981-02-22 | 1250.00 | 500.00 | SALES | CHICAGO |
| 20 | 7566 | JONES | MANAGER | 7839 | 1981-04-02 | 2975.00 | NULL | RESEARCH | DALLAS |
| 30 | 7654 | MARTIN | SALESMAN | 7698 | 1981-09-28 | 1250.00 | 1400.00 | SALES | CHICAGO |
| 30 | 7698 | BLAKE | MANAGER | 7839 | 1981-05-01 | 2850.00 | NULL | SALES | CHICAGO |
| 10 | 7782 | CLARK | MANAGER | 7839 | 1981-06-09 | 2450.00 | NULL | ACCOUNTING | NEW YORK |
| 20 | 7788 | SCOTT | ANALYST | 7566 | 1982-12-09 | 3000.00 | NULL | RESEARCH | DALLAS |
| 10 | 7839 | KING | PRESIDENT | NULL | 1981-11-17 | 5000.00 | NULL | ACCOUNTING | NEW YORK |
| 30 | 7844 | TURNER | SALESMAN | 7698 | 1981-09-08 | 1500.00 | 0.00 | SALES | CHICAGO |
| 20 | 7876 | ADAMS | CLERK | 7788 | 1983-01-12 | 1100.00 | NULL | RESEARCH | DALLAS |
| 30 | 7900 | JAMES | CLERK | 7698 | 1981-12-03 | 950.00 | NULL | SALES | CHICAGO |
| 20 | 7902 | FORD | ANALYST | 7566 | 1981-12-03 | 3000.00 | NULL | RESEARCH | DALLAS |
| 10 | 7934 | MILLER | CLERK | 7782 | 1982-01-23 | 1300.00 | NULL | ACCOUNTING | NEW YORK |
+ + + + + + + + + + +

➢ Difference between Equi-Join vs Natural Join

Equi-Join Natural Join


Join performed on equality of value of the Join is performed on column haing
columns common name.
Where clause is used to specify the There is no need to use where clause
condition
Both columns from tables are displayed in Common column is displayed only
the result. once
Solved Exercise on Join:

Consider the following two table Customer and Saleman


Customer Table:

salesman_id name city commission


5001 James Hoog New York 0.15
5002 Nail Knite Paris 0.13
5005 Pit Alex London 0.11
5006 Mc Lyon Paris 0.14
5007 Paul Adam Rome 0.13

Customer Table:

customer_id cust_name city grade salesman_id


3002 Nick Rimando New York 100 5001
3007 Brad Davis New York 200 5001
3005 Graham Zusi California 200 5002
3008 Julian Green London 300 5002
3004 Fabian Johnson Paris 300 5006
3009 Geoff Cameron Berlin 100 5003
3003 Jozy Altidor Moscow 200 5007

Q1. Write a SQL query to display Salesman, cust_name and city from above table where the
salesperson and customer belongs to same city.
Ans:
SELECT s.name AS "Salesman",

c.cust_name, c.city

FROM salesman s,customer c

WHERE s.city=c.city;

Or
SELECT salesman.name AS "Salesman",

customer.cust_name, customer.city

FROM salesman,customer
WHERE salesman.city=customer.city;
Q2. write a SQL query to display ord_no, purch_amt, cust_name, city of those orders whereorder
amount exists between 500 and 2000.
Ans:
SELECT o.ord_no,o.purch_amt,
c.cust_name,c.city
FROM orders o,customer c
WHERE o.customer_id=c.customer_id
AND o.purch_amt BETWEEN 500 AND 2000;
Q3. Write a SQL query to display Customer Name, city, Salesman, commission the all
salesperson(s) and their respective the customer(s).
Ans:
SELECT c.cust_name AS "Customer Name",c.city,

s.name AS "Salesman", s.commission FROM

customer c, salesman s

WHERE c.salesman_id=s.salesman_id;

Q4. What are Joins in SQL?

Ans. Joins in SQL are the statements or clauses using which we can combine two or more tables,
based on some common fields present among the tables.
Q5.Explain the different types of Joins in SQL?Ans:

Some of the major joins in SQL are-

❖ Equi Join – Inner join is used to return the records which are having matching
valuesin both the tables.
❖ Left Join – Left join is used to concatenate all the rows of the left table and
thematching rows in the right table.
❖ Right Join-Right join is used to concatenate all the rows of the right table and
thematching rows in the left table.
❖ Full Join-Full join is used to return all the records of both the tables as long as there
isa matching record in either table.
❖ Self Join-Self join is a join that is used to join a table to itself. In a self-join, a table is
considered as if it were two tables.
❖ Cartesian Join-Cartesian join is used to return the number of rows in the first table
multiplied by the number of rows in the second table. It is also referred to as cross
join.
Q6. What is Natural Join?
Ans: Natural join is used to create an implicit join clause based on the value of common attributesin
the two tables. Common attributes are the attributes that have the same name in both tables.
Natural join does not need any comparison operator as in the case of equi join.

Q7. What is an Equi Join?

63 | P a g e
Ans: An Equi Join is a type of join that combines tables based on matching values in the
specified columns.
❖ The column names do not need to be the same.
❖ The resultant table can contain repeated columns.
❖ It is possible to perform an equi join on more than two

tables.Q 8. What is the difference between cross join and natural join?

Ans: A cross join produces a cross product or cartesian product of two tables whereas the natural
join is based on all the columns having the same name and data types in both the tables.

Unsolved Exercise:
1. Consider the following tables PARTICIPANT and ACTIVITY and answer the questions that follow :

(i) When the table ‘‘PARTICIPANT’’ was first created, the column ‘NAME’ was planned as
the Primary key by the Programmer. Later a field ADMNO had to be set up as Primary
key. Explain the reason.
OR

Identify data type and size to be used for column ACTIVITYCODE in table ACTIVITY.

(ii) To display Names of Participants, Activity Code, Activity Name in alphabetic ascending
order of names of participants.

(iii) To display Names of Participants along with Activity Codes and Activity Names for only
those participants who are taking part in Activities that have ‘bag’ in their Activity
Names and Points of activity are above 250.

2. In a database there are two tables ‘LOAN’ and ‘BORROWER’ as shown below:

Table: LOAN

Loan_no Branch_name Amount


K-70 Downtown 5000
K-230 Redwood 6000
K-260 Perryridge 3700
Table : BORROWER

Customer_Name Loan_no
Jones K-170
Smith K-230
Hayes K-155

(i) Identify the foreign key column in the table BORROWER.


(ii) How many rows and columns will be there in the cross join of these two tables?
(iii) Write sql query to display customer smith’s loan record with their Name, Loan _no,
Branch _name and Loan amount
(iv) Write sql query to list names of all customers with their Amount in ascending order?
Interface of Python with an SQL database

➢ The real world application need to store data persistently


➢ The front end (User Interface) is designed in Python or any other programming language
and Data stored in database (Backend).
➢ Therefore, there is need to connect Python application and Database.
➢ The connectivity is achieved through API called MySQL-Connector.
➢ It needs to be installed using pip command on Command Prompt
❖ Press Window +R to open Run Window
❖ Type CMD press enter
❖ It will open Command Prompt
❖ Move to Script Folder of Python, if Python Path is not set
CD C:\Users\Your_User_Name\AppData\Local\Programs\Python\Python310\Scripts\

❖ Run Following command


pip install mysql-connector

❖ To check whether it is installed or not, use pip list command.


➢ Step to Connect Python to MySQL
❖ Import MySQL Connector to your program
import mysql.connector

❖ Establish connection using mysql.connector connect() method. This method will generated
ER_ACCESS_DENIED_ERROR is password is wrong.
mycon=mysql.connector.connect((host=”localhost”,user=”root”,password=””,
database=’test’)

host : - server name on which MySQL is running, default is localhost (127.0.0.1) for local
machine

user : user_name of MySQL, default is ‘root’

password : - Password for user ‘root’, default is no password i. e. “”


database: - Name of MySQL database to connect

❖ Create Cursor using method of connection object’s (mycon) cursor() method


mycursor=mycon.cursor()
❖ Execute the query using cursor method execute(SQL_Command),
result_set=mycursor.execute(‘SELECT * FROM EMP;”)

❖ Result_set object holds all the record (rows) returned by execute() method
❖ Perform required operations using various cursor method
❖ Close Cursor using close() method of Cursor object
mycursor.close()

❖ Close Database connection using close() method connection


objectMycon.close()
❖ Other method
▪ is_connected()- It is a connection method and return true is connection
isestablished otherwise false.
myconn.is_connected()
▪ commit() – it is a method of connection object and save the same made
bytransaction.
myconn.commit()
▪ rollback() – it is a method of connection object that undo all the
changesmade.
Myconn.rollback()

▪ fetchone() – It is method of cursor object that fetches next one row of a


queryresult set.
▪ Fetchall() – it is another method of cursor object that fetches all the rows
inthe result set.
▪ rowcount()- it is a method of cursor object that returns the number of
rowsaffected by execute() method.
➢ Creating Database from Python
Listing database in MySQL before the execution of the code
Code:

Result of Show databases command after the code.

➢ Listing database from Python

Output:
('information_schema',)
('mydb',)

('mysql',)
('newdb',)
('performance_schema',)
('school',)

('sys',)
('test',)
('xiicomm',)

➢ Reading table data


➢ Updating Records
Details of Persons table before updating

Code:

Output:
Enter name of the person to update Address Rohit
Enter New Address Patna
1 records updated

Details of Persons table after updating


➢ Deleting Record
Details of Persons table before deleting the row

Code:

Details of Persons table after deleting record with Personid= 1

Exercise:
1. What is the role of execute() method?
2. What is the significance of using connect()?
3. Explain the following method of cursor object
a. fetchone()
b. rowcount
c. fetchall()
4. What is Python’s database interface known as?
Class: XII Session: 2022-23 Computer

Science (083)

Sample Question Paper (Theory)

Maximum Marks: 70 Time Allowed: 3 hours

General Instructions:

1. This question paper contains five sections, Section A to E.


2. All questions are compulsory.
3. Section A have 18 questions carrying 01 mark each.
4. Section B has 07 Very Short Answer type questions carrying 02 marks each.
5. Section C has 05 Short Answer type questions carrying 03 marks each.
6. Section D has 03 Long Answer type questions carrying 05 marks each.
7. Section E has 02 questions carrying 04 marks each. One internal choice is given
in Q35 against part c only.
8. All programming questions are to be answered using Python Language only.

SECTION
A
1. Which of the following is an invalid statement? 1
a. abc=1,000,000 c. a b c=100 200 300
b. a, b, c= 100,200,300 d. a=b=c=100
2. Which of the following operators has the highest precedence? 1
(a) << (b) ** (c)% (d)and
3. What will be the output of the following Python code snippet? 1

d1 = {"john":40, "peter":45}
d2 = {"john":466, "peter":45}
d1 > d2
a) True
b) False
c) Error
d) None
4. What will be the value of the given expression? 1
3+3.00, 3**3.0
(a) (6.0, 27.0)
(b) (6.0, 9.00)
(c) (6,27)
(d) [6.0,27.0]
(e) [6,27]
5. Select the correct output of the code: 1
a = "foobar"
a = a.partition("o")
(a) ["fo","","bar"]
(b) ["f","oo","bar"]
(c) ["f","o","bar"]
(d) ("f","o","obar")
6. If a text file is opened in w+ mode, then what is the initial position of file 1
pointer/cursor?

(a) Beginning of file (b) End of the file


(c) Beginning of last line of text file (d) Undetermined

7. Fill in the blank: 1

Keyword is used to set foreign key in SQL.

(a) foreign key (b)unique (c) references (d)primary


8. Which of the following commands will change the datatype of the table in 1
MYSQL?
(a) DELETE TABLE
(b) DROP TABLE
(c) REMOVE TABLE
(d) ALTER TABLE
9. For a user defined function with header 1
def start (x, y, z=10),
Which of the following function call statements will generate an
error?

(a) start(10) (b) start(x = 10,y = 20)


(b) start(y = 20, x = 10) (d) All of the above

10 Fill in the blank: 1


.
_______________ refers to a situation of keeping the same data in different
formats in two different tables
(a) data redundancy
(b) data privacy
(c) data inconsistency
(d) data integrity
11 What is the binary file mode associated with “file must exist, otherwise error 1
. will be raised and reading and writing can take place”?
(a) ‘wb+’ (b) ‘w+’ (c) ‘rb’ (d) ‘rb+’

12 Fill in the blank: 1


.
Group by clause uses ______________ clause to apply conditions on
aggregate rows
(a) where (b) order by (c) sort (d) having
13 Fill in the blank: 1
.
What kind of transmission medium is most appropriate to carry data in a
computer network that is exposed to electrical interferences?

a. Unshielded twisted pair b. Optical fiber c. Coaxial cable d. Microwave


14 If x = 12 and y = ‘12’, then what will be the output of the following code? 1
.
print(x*2, y*2, sep="")

(a) 2424 (b) 24 24 (c) 241212 (d) 24 1212


15 Which of the following is not a built in aggregate function in SQL? 1
.

a) avg b) max c) total d) count


16 Name the method which is used for displaying only one resultset. 1
.
(a) fetchmany (b) fetchno (c) fetchall (d) fetchone
Q17 and 18 are ASSERTION AND REASONING based questions. Mark the
correct choice as
a. Both A and R are true and R is the correct explanation for A
b. Both A and R are true and R is not the correct explanation for A
c. Both A and R are false.
d. A is True but R is False
e. A is false but R is True

17 Assertion (A): Parameters with default arguments can be followed by 1


. parameters with no default argument.
Reason (R): Syntactically, it would be impossible for the interpreter to decide
which values match which arguments if mixed modes were allowed while
providing default arguments.

18 Assertion (A): Local Variables are accessible only within a function or block 1
. in which it is declared
Reason (R): Global variables are accessible in the whole program.
SECTION B

19 Correct the following code segment: 2


.
DEF say(message, times = 1)
print(message * times , end : ’ ‘)
say(times=10, ‘Hello and’)
say('World')
20 Write two points of difference between Circuit Switching and Packet 2
. Switching.
OR

Write two points of difference between Coaxial and fiber.


21 Find the output. 1
.
(a) def example(a):
a = a+2
a=a*2
return a
>>>print(example("hello"))

(b) Sum = 0 1

for k in range(10 , 1, -2):


Sum = Sum+k
print(Sum)
22 Explain the referential integrity constraint. What conditions must be met in 2
. order to set referential integrity?
23 (a) Write the full forms of the following: 2
. (i) CDMA (ii) SLIP

(b) What is the use of HTTP?


24 Predict the output of the Python code given below: 2
.
def modifyList(x):
x.append(sum(x))
print(x, end= ‘ ’)
L = [1,2,3,4]
print(L, end= ‘ ’)
modifyList(L)
print(L)
OR

Predict the output of the Python code given below:


l1 = [10,15,16,18,20]
l1.remove(15)
l1.insert(1,30)
print (l1[::-2])

25 2
.

(a) Find the Degree and Cardinality of the Cartesian product of the
Supplier and Product relations.
(b) Identify the foreign key in the given tables, also mention in which table
it is appearing as a foreign key?

OR

Find output:
(a) select *from product p, supplier s where p.supcode=s.supcode;
(b) select *from product natural join supplier;

SECTION C
26 (a) Create the connection of Python with MYSQL, in which (1) 1+2
User=Admin Password= Admin2123 Database Name=System

(b) Write the output of the queries (a) to (d) based on the table, Staff given
below:

Table: Staff

(a) Select avg(exp) from staff where gender = ‘F’;


(b) Select min(doj) from staff;
(c) Select *from staff where gender!=’M’ and dept like ‘_ _ _ _ _’;
(d) Select name, doj from staff where dept not in (‘Finance’,’Sales’);

27 Assume that a text file named TEXT1.TXT already contains some text written 3
. into it, write a program with a function named vowelwords(), that reads the
file TEXT1.TXT and create a new file named TEXT2.TXT , which shall
contain only those words from the
file TEXT1.TXT which don’t start with an uppercase vowel(i.e. with
‘A’,’E’,’I’,’O’,’U’)

for example if the file TEXT1.TXT contains


Carry Umbrella and Overcoat When it Rains
then the file TEXT2.TXT shall contain
Carry and when it Rains.

OR

Write a Python program to count all the line having 'a' as last character.
28 Dileep has to create a database named Company in MYSQL. 3
.
He now needs to create a table named Employee in the database to store the
records of employees in the company. The table Employee has the following
structure:
Table: Employee

Help him to complete the task by suggesting appropriate SQL commands.


29. Write a function merge_tuple(t1,t2), where t1 and t2 are the tuples of elements 3
passed as argument to the function. The function returns another tuple named
that stores the sum of consecutive element of t1 and t2, only if they are of same
length else return -1

For example:

T1=(1,2,3,4)
T2=(5,6,7,8)
Then function should return
(6,8,10,12)

And if
T1=(1,2,3)
T2=(5,6,7,8)
Then function should return
-1

30. Rajiv has created a dictionary containing employee names and their salaries as 3
key value pairs of 6 employees.
Write a program, with separate user defined functions to perform the following
operations:
● Push the keys (employee name) of the dictionary into a stack, where the
corresponding value (salary) is less than 85000.
● Pop and display the content of the stack.
For example:
If the sample content of the dictionary is as follows:

Emp={"Ajay":76000, "Jyothi":150000, "David":89000, "Remya":65000,


"Karthika":90000, "Vijay":82000}

The output from the program should be:


Vijay Remya Ajay

OR
Aruna has a list containing temperatures of 10 cities. You need to help her
create a program with separate user defined functions to perform the following
operations based on this list.
● Traverse the content of the list and push the negative temperatures into a stack.
● Pop and display the content of the stack.
For Example:
If the sample Content of the list is as follows:
T=[-9, 3, 31, -6, 12, 19, -2, 15, -5, 38]
Sample Output of the code should be:
-5 -2 -6 -9

SECTIO
ND
31 Excel Public School, Coimbatore is setting up the network between its 5
. different
wings of school campus. There are 4 wings namely SENIOR(S),
JUNIOR (J),
ADMIN (A) and HOSTEL (H).
Distances between various wings are given below:
Wing A to Wing S 100m
Wing A to Wing J 200m
Wing A to Wing H 400m
Wing S to Wing J 300m
Wing S to Wing H 100m
Wing J to Wing H 450m
Number of Computers installed at various wings are as follows:
Wings Number of Computers
Wing A 20
Wing S 150
Wing J 50
Wing H 25
(a) Suggest the best-wired medium and mention the topology or
layout to connect various wings of Excel Public School,
Coimbatore.
(b) Name the most suitable wing to house the server. Justify your
answer.
(c) Suggest placement of HUB/SWITCH in the network of the
School.
(d) Suggest a device that can provide wireless Internet access to all
smartphone/laptop users in the campus of Excel Public School,
Coimbatore.
(e) Draw suitable layout to connect all four wings of Excel Public
School

32 (a) Write the output of the code given below: 2+3


.
x = 10
def localvar():
global x
x+=5
print(x, end=' ')
print(x+5, end=' ')
localvar()
print(x, end=' ')

(b) following code establishes connectivity between Python and


MYSQL:

____________________ #statement 1
dataBase = mysql.connector.connect(
host ="localhost",
user ="user",
passwd ="password",
database = "gfg"
)

# preparing a cursor object


cursorObject = ____________________ #statement 2

# creating table
studentRecord = """CREATE TABLE STUDENT (
NAME VARCHAR(20) NOT NULL,
BRANCH VARCHAR(50),
ROLL INT NOT NULL,
SECTION VARCHAR(5),
AGE INT
)"""

# table created
cursorObject.________________________ #statement 3

# disconnecting from server


dataBase.close(

Write the following missing statements to complete the code:


Statement 1 – to import requisite module
Statement 2 – to form the cursor object
Statement 3- to execute the command that creates table

33 What is the advantage of using a csv file for permanent storage? 5


.
Write a program to
(a) add/insert records in file “data.csv”. Structure of a record is roll number,
name and class.
(b) search and display record for a given class

O
R

A binary file “emp.dat” has structure [EID, Ename, designation, salary].

I.Write a user defined function CreateEmp() to input data for a record and add
to emp.dat.

II.Write a function display() in Python to display the detail of all employees.


SECTIO
NE
3 Write SQL queries for (a) to (d) based on the tables PASSENGER and 1+1+2
4
FLIGHT given below:

(a) what will be the degree and cardinality of the resulting relation after
Cartesian product of above relations?

(b) what will be the degree and cardinality of the resulting flight after addition
of two rows and deletion of one column?

(c) (i) Write a query to display the NAME, corresponding FARE and F_DATE
of all PASSENGERS who have a flight to START from DELHI.

(ii) Write a query to delete the records of flights which end at Mumbai.
OR
(c) create a new table traveller having same fields and tuples as passenger.
3 Sudev, a student of class 12th, is learning CSV File Module in Python. During 5
5. examination, he has been assigned an incomplete python code to create a CSV
file ‘customer.csv’. Help him in completing the code which creates the desired
CSV file.
I. Identify suitable code for the blank space in line marked as Statement-
a) include
b) add
c) Import
d) import
II. Identify the missing code for the blank space in line marked as Statement-2.
a) Customer
b) reader
c) csvwriter
d) writer
III. Identify the argument name for the blank space in line marked as Statement-
3?
a) Row
b) Rec
c) row
d) rec
IV. Identify the missing file name for the blank space in line marked as
Statement-4?
a) customer
b) customer.csv
c) customer.txt
d) customer.dat
V. Identify the object name for the blank space in line marked as Statement-5?
a) i
b) Rec
c) row
d) rec
Class: XII Session: 2022-23 Computer

Science (083)

Marking Scheme

SECTION
A
1. c. a b c=100 200 300 1

2. (b) ** 1

3. c) Error 1

4. (a) (6.0, 27.0) 1

5. (d) ("f","o","obar") 1

6. (a) Beginning of file 1

7. (c) references 1

8. (d) ALTER TABLE 1

9. (c) start(10) 1

10 (c) data inconsistency 1


.

11 (d) ‘rb+’ 1
.
12 (d) having 1
.
13 b. Optical fiber 1
.

14 (c) 241212 1
.
15 c) total 1
.
16 (d) fetchone 1
.
17 e. A is false but R is True 1
.
18. b. Both A and R are true and R is not the correct explanation for A 1

SECTION B

19 Correct the following code segment: 2


. def say(message, times = 1):
print(message * times , end = ’ ‘)
say(‘Hello and’,times=10)
say('World')

20 2
. Any two point of difference

. OR
21 (a) typeerror 1+1
.
(b) 30

22 Referential integrity refers to the relationship between tables. Because each 1+1
. table in a database must have a primary key, this primary key can appear in
other tables because of its relationship to data within those tables. When a
primary key from one table appears in another table, it is called a foreign key .

• Referential integrity requires that a foreign key must have a matching


primary key or it must be null.
• This constraint is specified between two tables (parent and child);
• it maintains the correspondence between rows in these tables.
• It means the reference from a row in one table to another table must be
valid.
23 CDMA: Code Division Multiple Access 1+1
. SLIP : Serial Line Internet Protocol

hypertext Transfer Protocol (HTTP) is an application-layer protocol


for transmitting hypermedia documents, such as HTML. It was designed
for communication between web browsers and web servers
24 [1,2,3,4] [1,2,3,4,10] [1,2,3,4,10] 2
.
OR
[20, 16, 10]

25 2
.

(a) Degree= 9 cardinality = 15


(b) Supcode in product table
OR

Find output:
(a)
PID PNAME QTY PRIC COMPANY SUPCO SUPCO SNAM CITY
E DE DE E
101 DIGITAL 120 1200 RENBIX S01 S01 GET KOLKA
CAMER 0 ALL IN TA
A 14X
102 DIGITAL 100 2200 DIGI POP S02 S02 DIGI CHENN
PAD 11I 0 BUSY AI
GROU
P
104 PENDRI 500 1100 STOREKIN S01 S01 GET KOLKA
VE G ALL IN TA
16GB
106 LED 70 2800 DISPEXPE S02 S02 DIGI CHENN
SCREEN 0 RTS BUSY AI
32 GROU
P
105 CAR 60 1200 MOVEON SO3 SO3 EASY DELHI
GPS 0 MARK
SYSTEM ET
CORP

(b)
PID PNAME QTY PRICE COMPANY SUPCOD SNAME CITY
E
101 DIGITAL 120 12000 RENBIX S01 GET KOLKAT
CAMERA ALL IN A
14X
102 DIGITAL 100 22000 DIGI POP S02 DIGI CHENNA
PAD 11I BUSY I
GROUP
104 PENDRIV 500 1100 STOREKING S01 GET KOLKAT
E 16GB ALL IN A
106 LED 70 28000 DISPEXPERT S02 DIGI CHENNA
SCREEN S BUSY I
32 GROUP
105 CAR GPS 60 12000 MOVEON SO3 EASY DELHI
SYSTEM MARKE
T CORP

SECTION C
26 (a) import mysqlconnector as myc 1
mycon=myc.connect(host=”localhost” user=”Admin” passwd=”Admin123”
databse=”System”)
0.5
X4
(b) Write the output of the queries (a) to (d) based on the table, Staff given
below:

Table: Staff

(a) 5.66
(b) 12-01-2006
(c) 3 Christina 15-11-2009 Sales F 12
7 habeena 16-08-2011 Sales F 10
(d) Dima 03-05-2016
Danish 11-09-2013

27 f1=open(“TEXT1.TXT”) 3
.
f2=open(“TEXT2.TXT”,”w”)
data=f1.read().split()
for word in data:
if word[0] not in “AEIOU”:
f2.write(word, “ “)
f1.close()
f2.close()

OR

f1=open(“TEXT1.TXT”)
data=f1.readlines()
for line in data:
if line.strip()[-1]==”a”:
print(line)
f1.close()

28 Create table Employee(Empid int(5) primary key, Empname char(25) not null, 3
. Design char(15) unique , Salary float, DOB date);
29. def merge_tuple(t1,t2): 3
t3=( )
if len(t1)==len(t2):
for i in range(len(t1)):
t3[i]=t1[i]+t2[i]
return t3
return -1
30. def push(d, stack): 3
for key in d:
if d[key]<85000:
stack.append(key)

def pop(stack):
if stack==[ ]:
print(“underflow”)
else:
print(stack.pop())
OR
def push(l, stack):
for ele in l:
if ele<0:
stack.append(ele)

def pop(stack):
if stack==[ ]:
print(“underflow”)
else:
print(stack.pop())

SECTIO
ND
31 (a) Star topology , optical fibre or coaxial
.

(b) S wing as it has maximum no. of computers resulting in maximum


internal traffic as per 80:20 rule
(c) hub/Switch should be place in all the wings
(d) WiFi Router OR WiMax OR RF Router OR Wireless Modem OR
RFTransmitter
(e) any suitable layout

32 (a) 15 20 15 2+3
.
(b) Statement 1 – import mysql.connector
Statement 2 – database.cursor()
Statement 3- execute(studentRecord)

33 (any 2) 1+2+
. • CSV is human readable and easy to edit manually. 2
• CSV is simple to implement and parse. OR
• CSV is processed by almost all existing applications.
• CSV provides a straightforward information schema. 2+3
• CSV is faster to handle.
• CSV is smaller in size.
• CSV is considered to be standard format.

Write a program to
(a)

(b) f=open(“data.csv”,”r”)

data=csv.reader()

cls=input(“class to search record”)

for row in data:


If row[2]==Cls:

print(row)

OR

I.

import pickle

def CreateEmp():

f1=open("emp.dat",'wb')

eid=input("Enter E. Id")

ename=input("Enter Name")

designation=input("Enter Designation")

salary=int(input("Enter Salary"))

l=[eid,ename,designation,salary]

pickle.dump(l,f1)

f1.close()

II.

import pickle

def display():

f2=open("emp.dat","rb")

while True:

try:

rec=pickle.load(f2)

print(rec['eid'],rec['ename'],rec['designation'],rec['salary'])

except EOFError:

break
f2.close()

SECTION
E
3 (a) degree = 9 cardinality = 20 1+1+2
4
(b) degree = 8 cardinality = 28

(c) (i) Select Name, fare, f_date from passenger p, flight f where p.fno=f.fno
and start=”DELHI”;

(ii) delete from flight where end=”MUMBAI”;


OR
(c) Create table traveller as select * from passenger;

3 I. d) import 5
5. II. c) csvwriter
III. d) rec
IV. b) customer.csv
V. d) rec
d. There is not such file opening mode
7 Fill in the blank: 1
Command used to remove a column/attribute from the table/relation is _________.
a. Update
b. Drop
c. Alter
d. Remove
8 Shridharan created a database namely work. Now he wants to create a table in 1
it. For this he needs to open the database he created. Write command to open
the database that is created by Shridharan.
9 What will be the output of the following code: 1
address = ‘42/B/III, Van-Vihar Colony, Nagpur’
str = address.replace(‘/’,’@’)
print(address)
10 Fill in the blank: 1
The attribute which is a candidate key but not a primary key is known as
_______________________.
11 Which of the following gives the result as string when applied to text file in 1
Python:
a. read()
b. readline()
c. readlines()
d. get()
12 When following command is run the result yielded 20 rows: 1
SELECT * FROM Clock;
But when following command is run; it yielded 17 rows only:
SELECT name FROM Clock;
Can you state the reason for the difference?
13 Which of the following is used for remote login: 1
a. VoIP
b. HTTP
c. IMAP
d. TELNET
14 What will be the output of the following statement: 1
print(30/5+(16+6))
15 Rajiv ran following two commands: 1
SELECT count(commission) FROM Employee;
SELECT count(*) FROM Employee;
Output of first command is 8 where output of second command is 14. What is
the reason for the difference?
16 After executing any DML command from Python in Python-Mysql connectivity, 1
following is necessary to execute in order to make the changes permanent in
MySQL:
a. save()
b. store()
c. commit()
d. update()
Questions 17 and 18 are ASSERTION (A) and REASONING ® based questions. Mark the
correct choice as
a. Both A and R are true and R is the correct explanation of A.
b. Both A and R are true and R is not the correct explanation of A.
c. A is true but R is false.
d. A is false but R is true.
17 Assertion (A): Inside a function if we make changes in a string it will reflect 1
back to the original string.
Reason (R): String is an immutable datatype and it is called by value.
18 Assertion (A): In CSV file there is a blank line after every record. 1
Reason (R): Default value of newline is ‘\n’ in open() statement used with
csv file.
SECTION – B
19 Following code is having some errors. Rewrite the code after correcting and 2
underlining each correction:
x == 20
def printme():
y = x + 10
sum = 0
for i in range(x,y)
if i%3=0:
sum=sum+i+1
Elseif:
sum += 2
return(sum)
20 Write one advantage and one disadvantage of using Fiber Optic Cable. 2
OR
Write two differences between Circuit Switching and Packet Switching.
21 What will be the output of the following code: 2
sub = “083 Comp. Sc. & 065 Info. Prac.”
n = len(sub)
s=’’
for i in range(n):
if sub[i].isupper():
s = s + sub[i].lower()
elif sub[i].islower():
s = s + sub[i]
elif sub[i].isdigit():
s = s + ‘x’
elif sub[i].isspace():
pass
else:
s = s + ‘!’
print(s)
22 Define Foreign Key. Identify foreign key from the following tables: 2
Table: Bank_Account
Acctno Name BCode Type
1001 Amrita A2 Savings
1002 Parthodas A3 Current
1005 Miraben A2 Current

Table: Branch
Code City
A1 Delhi
A2 Mumbai
A3 Nagpur
23 a. What is the full form of SMTP and HTTP? 1
b. What is the use of POP3? 1
24 What will be the output of the following code: 2
def Call4Change():
for i in range(len(lst)):
if lst[i]%2==0:
lst[i]+=1
elif lst[i]%3==0:
lst[i]+=2
elif lst[i]%5==0:
lst[i]+=4
else:
lst[i]=0
lst = [1, 2, 9, 5, 12, 6, 7, 3, 10, 8, 11, 4]
Call4Change()
print(lst)
OR
What will be the output of the following code:
def Value2New(M, N=10):
M = M + N
N = N*2
if N%10==0:
N=N/5
return(M,N)
P,Q = Value2New(100,20)
print(P,’#’,Q)
P,Q = Value2New(50)
print(P,’#’,Q)
25 Name the SQL function that will be used in following situations:
a. To find the average salary paid to employees. ½
b. To find the month in which an employee is hired. ½
c. To find position of a substring in customer name. ½
d. To find 40% of totalmarks rounded to 2 decimal places. ½
OR
Consider the following tables and write queries for a and b:
Table: Bank_Account
Acctno Name BCode Type
1001 Amrita A2 Savings
1002 Parthodas A3 Current
1005 Miraben A2 Current

Table: Branch
Code City
A1 Delhi
A2 Mumbai
A3 Nagpur
a. To list Acctno, Name and City of those accounts whose Account Type is 1
Current. 1
b. To display Acctno and Name of those accounts whose Code is A2.
SECTION – C
26 Consider the following tables and answer the questions a and b:
Table: Garment
GCode GName Rate Qty CCode
G101 Saree 1250 100 C03
G102 Lehanga 2000 100 C02
G103 Plazzo 750 105 C02
G104 Suit 2000 250 C01
G105 Patiala 1850 105 C01
Table: Cloth
CCode CName
C01 Polyester
C02 Cotton
C03 Silk
C04 Cotton-
Polyester
a. What will be output of the following command:
1
SELECT * FROM GARMENT NATURAL JOIN CLOTH;
b. What will be the output of following commands:
i. SELECT DISTINCT QTY FROM GARMENT;
½
ii. SELECT SUM(QTY) FROM GARMENT GROUP BY CCODE
½
HAVING COUNT(*)>1;
½
iii. SELECT GNAME, CNAME, RATE FROM GARMENT G,CLOTH C
WHERE G.CCODE = C.CCODE AND QTY>100;
½
iv. SELECT AVG(RATE) FROM GARMENT WHERE RATE BETWEEN
1000 AND 2000;
27 Write a function countbb() in Python, which reads the contents from a text file 3
‘article.txt’ and displays number of occurrences of words ‘bat’ and ‘ball’ (in all
possible cases) to the screen.
Example:
If the content of file article.txt is as follows:
Bat and ball games are field games played by two opposing teams. Action starts
when the defending team throws a ball at a dedicated player of the attacking
team, who tries to hit it with a bat and run between various safe areas in the
field to score runs (points). The defending team can use the ball in various
ways against the attacking team's players to force them off the field when they
are not in safe zones, and thus prevent them from further scoring. The best
known modern bat and ball games are cricket and baseball, with common roots
in the 18th-century games played in England.
The countbb() function should display as:
Number of times bat occurs is 3
Number of times ball occurs is 5
OR
Write a function SOnly() in Python, which reads the contents from a text file
‘news.txt’ and creates another file ‘modnews.txt’. New file contains only those
lines that starts with an alphabet.
Example:
If the content of file news.txt is as follows:
This is Peter from California.
24th street is where I live.
__name__ is used in Python functions.
User defined functions is what I am presently reading.
Upon execution of function Sonly() file modnews.txt should contain:
This is Peter from California.
User defined functions is what I am presently reading.
28 Consider following tables and write queries for situation a and b. Find the output
of c and d:
Table: CLUB
CoachID CoachNam Ag Sports Dateofapp Pay Sex
e e
1 KUKREJA 35 KARATE 1996-03-27 1000 M
2 RAVINA 34 KARATE 1998-01-20 1200 F
3 KARAN 34 SQUASH 1998-02-19 2000 M
4 TARUN 33 BASKETBALL 1998-01-01 1500 M
5 ZUBIN 36 SWIMMING 1998-01-12 750 M
6 KETAKI 36 SWIMMING 1998-02-24 800 F
7 ANKITA 39 SQUASH 1998-02-20 2200 F
8 ZAREEN 37 KARATE 1998-02-22 1100 F
9 KUSH 41 SWIMMING 1998-01-13 900 M
10 SHAILYA 37 BASKETBALL 1998-02-19 1700 M
Table: COACHES
Sportsperson Sex Coach_No
AJAY M 1
SEEMA F 2
VINOD M 1
TANEJA F 3
a. To list names of all coaches with their date of appointment in descending
order.
b. To display total pay given to coaches in each sport. 1
c. SELECT Sportsperson, Coachname FROM Club, Coaches WHERE Coachid 1
= Coach_no;
d. SELECT Sex, MAX(Dateofapp), MIN(Dateofapp) FROM Club GROUP ½
BY Sex; ½

29 Write a function SumDiv(L,x), where L is a list of integers and x is an integer; 3


passed as arguments to the function. The function returns the sum of elements
of L which are divisible by x or x+1.
For example,
If L Contains [10, 27, 12, 20, 22] and x is 5
Then function returns 42 (10+12+20)
30 A nested list contains the records of Mobiles in the following format: 3
[[modelno, name, price], [modelno, name, price], [modelno, name, price],….]
Write the following user defined functions to perform given operations on the stack
named Mobile:
a. Push operation – To push details (modelno, name, price) of those
mobiles which has price lower than 10000. Make a note that there cannot
be more than 20 elements in stack Mobile.
b. Pop operation – To pop elements from stack one by one and display
them. Also, display “Underflow” when stack becomes empty.
For example,
If the list contains
[[‘V20’, ‘Vivo 20 SE’, 18000], [‘S11’, ‘Lava S11’, 8900], [‘i88’, ‘IPro 88
SE’, 6500], [‘ip13’, ‘iPhone 13’, 125000]]
The stack should contain:
[‘i88’, ‘IPro 88 SE’, 6500]
[‘S11’, ‘Lava S11’, 8900]
The Output should be:
[‘i88’, ‘IPro 88 SE’, 6500]
[‘S11’, ‘Lava S11’, 8900]
Underflow
OR
A Dictionary Medal contains the details of schools and medals won by them in
following format {school_name:medals_won}.
Write a function Push(Medal) in Python that pushes those school names in stack
named SCHOOL which has won more than 3 medals. Maximum capacity of stack
SCHOOL is 15. Function also shows number of items pushed in stack. If number
of items exceeds 15 then it shows OVERFLOW.
For example:
If dictionary Medal contains
{‘KV1’:5, ‘KV2’:2, ‘KV3’:4, ‘KV4’:1, ‘KV5’:7}
Then stack should contain
KV5
KV3
KV1
The output should be:
Number of item pushed in stack Medal are 3

SECTION D
31 Superior Education Society is an educational Organization. It is planning to setup
its Campus at Nagpur with its head office at Mumbai. The Nagpur Campus has
4 main buildings – ADMIN, COMMERCE, ARTS and SCIENCE.
You as a network expert have to suggest the best network related solutions for
their problems raised in a to e, keeping in mind the distances between the
buildings and other given parameters:

Shortest distances between various buildings:


ADMIN to COMMERCE - 55 m
ADMIN to ARTS - 90 m
ADMIN to SCIENCE - 50 m
COMERCE to ARTS - 55 m
COMMERCE to SCIENCE - 50 m
ARTS to SCIENCE - 45 m
MUMBAI Head Office to NAGPUR Campus – 850 KM
Number of Computers installed at various buildings are as follows:
ADMIN – 110
COMMERCE – 75
ARTS – 40
SCIENCE – 12
MUMBAI Head Office – 20
a. Suggest the most appropriate location of the server inside the Nagpur 1
Campus to get the best connectivity for maximum number of computers.
Justify your answer.
b. Suggest and draw the cable layout to efficiently connect various buildings 1
within the Nagpur campus for connecting the computers.

1
c. Which of the following will you suggest to establish the online face-to-
face communication between the people in the ADMIN office of Nagpur
Campus and Mumbai Head office?
i. Cable TV
ii. E-mail
iii. Video Conferencing 1
iv. Text Chat
d. Suggest the placement of following devices with appropriate reasons:
i. Switch/Hub 1
ii. Repeater
e. Suggest the device/software to be installed in Nagpur Campus to take
care of data security and unauthorized access.
32 a. Write the output of the Code given below: 2
x = 15
def add(p=2, q=5):
global x
x = p+q+p*q
print(x,end=’@’)
m = 20
n = 5
add(m,n)
add(q=10, p = -3)
b. The code given below inserts the following record in table Garment: 3
GCode – integer
GName – string
Rate – decimal
Qty – integer
CCode = integer
Write missing Statements (Statement 1, Statement 2 and Statement 3) to
complete the code:
import mysql.connector as mycon
cn = mycon.connect(host=’localhost’, user=’test’, password=’None’,
database=’cloth’)
cur = ______________________ #Statement 1
while True:
GCode = int(input(“Enter Garment Code = “))
GName = input(“Enter Garment Name = “)
Rate = float(input(“Enter Rate = “))
Qty = int(input(“Enter Quantity = “))
CCode = int(input(“Enter Cloth Code = “))
q = “insert into Garment Values ({}, ‘{}’, {}, {}, {}”.format(GCode,
GName, Rate, Qty, CCode)
cur._______________(q) #Staatement 2
____________________ #Statement 3
ans = input(“Do you have more records (Y/N)=”)
if ans.upper()==’N’:
break
print(“Records Successfully Saved”)
cn.close()
OR
a. Write the output of the Code given below:
def Timing(T, m=0): 2
print(“Present Time is”,end=’:’)
if m>10 and m<=20:
print(“Quarter Past”,T)
elif m<=40:
print(“Half Past”,T)
elif m<=59:
print(“Quarter to”,T+1)
else:
print(“Incorrect Minutes”)
Timing(5,18)
Timing(11)
Timing(12,60)
b. The code given below reads those records from table Garment which has Qty 3
less than 50. Records in table Garments are stored with following attributes:
GCode – integer
GName – string
Rate – decimal
Qty – integer
CCode = integer
Write missing Statements (Statement 1, Statement 2 and Statement 3) to
complete the code:
import mysql.connector as mycon
cn = mycon.connect(host=’localhost’, user=’test’, password=’None’,
database=’cloth’)
cur = ______________________ #Statement 1
cur._________________________ #Staatement 2 (Create & Execute Query)
G = ____________________ #Statement 3Read complete result of query
print(“Required records are:”)
for i in G:
print(i)
cn.close()
33 What is the difference between CSV file and Text File? Write a program in 5
Python that defines and calls the following functions:
Insert() – To accept details of clock from the user and stores it in a csv file
‘watch.csv’. Each record of clock contains following fields – ClockID, ClockName,
YearofManf, Price. Function takes details of all clocks and stores them in file in
one go.
Delete() – To accept a ClockID and removes the record with given ClockID
from the file ‘watch.csv’. If ClockID not found then it should show a relevant
message. Before removing the record it should print the record getting removed.
OR
Give one advantage of using CSV file over Binary file. Write a program in Python 5
that defines and calls the following functions:
saving() – To accepts details of equipments from the user in following format
(ID, Name, Make, Price) and save it in a csv file ‘parts.csv’. Function saves
one record at a time.
search() – To accept two prices and displays details of those equipments which
has price between these two values.

SECTION E
34 Mayanti just started to work for a sports academy having several branches across
India. The sports academy appoints various trainers to train various sports. She
has been given the task to maintain the data of the trainers. She has made a
table called TRAINERS in the database which has following records:
Table: TRAINER
TrainerNo Name City HireDate Salary
101 SUNAINA MUMBAI 1998-10-15 90000
102 ANAMIKA DELHI 1994-12-24 80000
103 DEEPTI CHANDIGARH 2001-12-21 82000
104 MEENAKSHI DELHI 2002-12-25 78000
105 RICHA MUMBAI 1996-01-12 95000
106 MANIPRABHA CHENNAI 2001-12-12 69000
Based on the data given above answer the following questions:
a. Can City be used as Primary key for table TRAINER? Justify your answer. 1
b. What is the degree and cardinality of the table TRAINER? If we add two 1
rows and remove three rows from table TRAINER. Also if we add another
attribute in the table, what will be the degree and cardinality of the table
TRAINER will become?
c. Write statements for:
i. Insert a new record in table TRAINER with values, TrainerNo = 1
107, Name = Swastik, HireDate = 1999-01-22, Salary = 90000.
ii. Increase the salary of those Trainer having city as DELHI by 5000. 1
OR
c. Write Statements for:
i. Removes those records from table TRAINER who were hired after 1
year 2000.
ii. Add a new column Grade with datatype as Varchar and maximum 1
size as 2.
35 Tarun Nair is working under XYZ Incorporation which deals with exporting of goods
to foreign countries. To keep track of inventory he is creating a Python program
to store the information of item number and quantity in a binary file inventory.dat.
For that he has written the following code. Go through the code given and solve
problems given below:
def write(ino,qty):
F = open(____________) #Mark 2
L= _______________ #Mark 3
L.append([ino,qty])
F.close()
F=open('inventory.dat','wb')
pickle.dump(L,F)
F.close()

def Receive(ino,qty):
F=open(“inventory.dat”,”rb”)
L=pickle.load(F)
F.close()
for i in range(len(L)):
if L[i][0] == ino:
L[i][1] += qty
F=open("inventory.dat",'wb')
pickle.dump(L,F)
________________ #Mark 4

def Sent(ino,qty):
with open(“inventory.dat”,”rb”) as F:
L=pickle.load(F)
for i in range(len(L)):
if L[i][0] == ino:
L[i][1] -= qty
with open("inventory.dat",'wb') as F:
pickle.dump(L,F)
a. Write statement to open the file at Mark 2 to read records from the file. 1
b. Write statement at Mark 3 to read the content of binary file in list L. 1
c. Write statement at Mark 4 to close the file. 1
d. Why there is no need to close the file in function Sent()? 1
**************************************************************

You might also like