0% found this document useful (0 votes)
15 views72 pages

CS 12 TM

Uploaded by

Md Arif Ansari
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)
15 views72 pages

CS 12 TM

Uploaded by

Md Arif Ansari
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/ 72

TEACHER’S MANUAL

COMPUTER SCIENCE- XII

Ch-1: REVIEW OF PYTHON BASICS

Unsolved Questions
Ans 1. Python offers the following advantages:
(a) Platform-independent: It is platform-independent and can run across different platforms
like Windows, Linux/Unix, Mac OS and other operating systems. Thus, we can say that
Python is a portable language.
(b) Readability: Python programs use clear, simple, concise and English-like instructions that
are easy to read and understand even by non-programmers or people with no substantial
programming background.
(c) Object-oriented Language: It is an interactive, interpreted and object-oriented
programming language.
(d) GUI Programming: Python supports GUI applications that can be created and ported
to many system calls, libraries and window systems such as Windows MFC (Microsoft
Foundation Class Library), Macintosh and the X Window system of UNIX.
Ans 2. In Python, we can work in two ways—Interactive mode (Shell) and Script mode.
Ans 3. Advantages:
• Interactive mode is suitable for writing very short programs.

• Interactive mode is useful for testing code.

• In this mode, the result is obtained immediately after the execution of each line of code. Hence,
it runs very fast.

Disadvantages:

• Interactive mode does not save commands in the form of a program and also output is
sandwiched between commands.

Ans 4.
Ans. (i) >>>3+8.0+6*12
(ii) >>>16+5.0+44.0
Ans 5. Operators are special symbols which represent computation. They are applied on operand(s),
which can be values or variables.
Unary and Binary operators: An operator can be termed as unary or binary depending upon the
number of operands it takes. A unary operator takes only one operand and a binary operator takes
two operands. For example, in the expression –6 * 2 + 8 – 3, the first minus sign is a unary minus
and the second minus sign is a binary minus.
Ans 6. Expression: An expression is a combination of symbols, operators and operands. An expression
represents some value. The outcome of an expression is always a value. For example, 3 * 7 + 10 is
an expression.
Statement: A statement is defined as any programming instruction given in Python as per the
syntax. It is given to execute a task. It may or may not return a value as the result. For example,
print("Hello") is a statement.
Ans 7. The basic components of Python are character sets, tokens, expressions, statements,
operators and input-output, etc.
Ans 8. Variable is the user-defined name given to a value. Variables are not fixed/reserved. These
are defined by the user but they can have letters, digits and an underscore. They must begin with
either a letter or underscore. For example, _age, name, result_1, etc. Variables are very important
building blocks of any programming language as they allow programmers to store their values in
user-defined variables which they can use later in the program.

Ans 9. (i)
guru99 1
guru99 2
guru99 3
(ii)
100
200
300
(iii)
20
16
(iv)
1 1
2 1
2 2
3 1
3 2
3 3
4 1
4 2
4 3
4 4
5 1
5 2
5 3
5 4
5 5
(v)
15
(vi) 19
Ans 10. ok
Ans. 11. A list is a sequence data structure created by placing all the items (elements) inside a
square bracket[ ] separated by commas. The different ways to create a list are:
1. Creating an empty list. For example, L=[ ]
2. Creating a new list from an existing list using the list-slicing operation. For example,
lst=[1,2,3,4,5]
lst_new=lst[1:4]
3. Creating a list from an existing sequence using list() function. For example,
Str1=’Python’
Lst=list(Str1)
print(Lst)
4. Creating a list using the copy() function. For example,
Lst=[1,2,3,4,5]
Lst_new=Lst.copy()
Print(Lst_new)
Ans 12. Similarities:
• Both are sequence data types.
• The elements of lists are enclosed with square brackets while strings can be enclosed with a
single quote, double quotes and triple quotes.
Dissimilarities:
• Lists are mutable, unlike Strings.
Ans 13. Lists are c a l l e d mutable data types because values in the list can be modified in place,
which means that Python does not create a new list when you make changes to an element of
a list.
Ans 14. The insert() function can be used to insert an element/object at a specified index in the list.
It takes two arguments: the index where an item/object is to be inserted and the item/element itself.
The append() method adds a single item to the end of the existing list. It doesn't create a new list;
rather, it modifies the original list.
Ans 15.
L=[20,45,50,54,60,64,68,70,72,74]
n=len(L)
s=sum(L)/n
print(s)

Or
import statistics
L=[20,45,50,54,60,64,68,70,72,74]
m=statistics.mean(L)
print("Mean of List is : ",m)

Ans 16.
lst = [5,3,4,7,6,8,7,5,2,3,9]
lst.sort()
print ("Minimum element of a list of numbers is ", lst[0])

Ans 17.
lst=[]
n = int (input ("Enter the total subjects:"))
for i in range(n):
marks= eval (input ("Enter the marks in each subject:"))
lst.append(marks)
sum = 0
for i in lst :
sum = sum + i
Per=sum/n
print ("Total marks of student:", sum)
print("Percentage of student:", Per )

Ans 18. n=[6,'z',3,4,'y','c',5,7,'l']


for i in range (len(n)) :
if i % 2 != 0:
n[i] = n[i] * 2
print(n)

Ans 19. lst = [5,8,89,67,54,39,50,2,2,89,8,5]


n = len(lst)
element = int(input("Enter
element:"))
c = 0
for i in range(0, n):
if element == lst[i]:
c = c + 1

if c==0:
print("Not found")

else:
print(c)
Ans 20. lst=[10,20,30,40]
print("New list=",[lst[-1]]+lst[0:-1])

Ans 21. Num=[3, 25, 13, 6, 35, 8, 14, 45]


for i in range(len(Num) -1):
if Num[i+1] % 5 == 0 :
Num[i],Num[i+1]=Num[i+1],Num[i]
print(Num)

Ans 22.
tup1 = eval(input("Enter a tuple:"))
for i in tup1 :
print(i)
print(tup1)
print("Maximum value in tuple is :", max(tup1))
print("Minimum value in tuple is :", min(tup1))

Ans 23.
tup1 = eval(input("Enter elements in tuple 1:"))
tup2 = eval(input("Enter elements in tuple 2:"))
tup1,tup2 = tup2,tup1
print("Tuple 1:",tup1)
print("Tuple 2:",tup2)
print(tup1 < tup2)
print(tup1 > tup2)
print(tup1 == tup2)

Ans 24.
Dict1 = {}
while True :
clas = int(input("Enter class:"))
t_name = input("Enter class teacher name:")
dic[clas]= t_name
x = input("Do you want to add more records Y/N")
if x == "N" or x == "n":
break
search= int(input("Enter class which you want to search"))
print("class teacher name",dic1[search])

Ans 25.
dic = {}
while True :
st_name = input("Enter name :")
per = float(input("Enter percentage :"))
dic[st_name] = per
a = input("Do you want to add more records Y/N")
if a == "N" or a == "n":
break

name = input("Enter name which you want to delete :")


del dic[name]
print("Dictionary",dic)

Ans 26.
Dict1 = {}
while True :
cust_name= input("Enter Customer name:")
phone = int(input("Enter phone number:"))
item_name = input("Enter item :-")
cost = float(input("Enter cost :-"))
Dict1[cust_name] = [phone,item_name,cost]
p = input("Do you want to add more records press (Y/N) : ")
if p == "N" or p == "n":
break
for i in Dict1 :
print()
print(" Customer Name : ",i)
print("Phone Number:",Dict1[i][0],"\t","Item
name:",Dict1[i][1],"\t","Cost:",Dict1[i][2])

Ans 27.
str1='Python is easy to learn'
str1= str1.title()
output = ""
for word in str1.split():
output =output+ word[:-1] + word[-1].upper() + " "
print(output[:-1])

Ans 28.
str1 = input("Enter a string:")
new_str = ""
for i in str1:
if i not in new_str :
new_str += i
print(new_str)

Ans 29.
str1 = input("Enter your string: ")
sum = 0
for i in str1:
if i.isdigit():
sum += int(i)
print("Total: ", sum)

Ans 30.
string = input("Enter a string :")
lst = string.split()
max = 0
for i in lst:
if lst.count(i) > max :
max = lst.count(i)
maxvalue = i
print(maxvalue)

Ans 31.
str1 = input("Enter a string :")
new_str = str1[-1] + str1[1:-1] + str1[0]
print(new_str)

Ans 32.
lst = [10,2,3,5,100]
prod = 1
for i in lst :
prod =prod* i
print(prod)

Ans 33.
lst = [70,6,4,60,90,34,56,27,10]
lst.sort()
print("Minimum element is ",lst[0])

Ans 34.
lst1 = eval(input("Enter elements in list 1:"))
lst2 = eval(input("Enter elements in list 2 :"))
l1=list(lst1)
l2=list(lst2)
l1.extend(l2)
print(l1)

Ans 35.
Lst1 = [ ]
for i in range(1,6):
lst1 =lst+ [ i**2 ]
for i in range(6,26):
lst1=lst+ [i]
for i in range(26,31):
lst1=lst1+ [i**2]
print(lst1)
Ans 36.
lst = eval (input("Enter a list :"))

for i in lst:
if lst.count(i) == 1 :
print(i)

Ans 37.
string = input("Enter a string:")
print(list(string))
Ans 38.
d1 = {'A':1, 'B':2, 'C':3}
d2 = {'D':4}
d1.update(d2)
print(d1)

Ans 39. This program is not possible because the Python dictionary accepts only unique keys.
Ans 40.
dic={}
for i in range(1,16):
dic[i] = i**2

print(dic)

Ans 41.
d1 = eval(input("Enter first dictionary :- "))
d2 = eval(input("Enter second dictionary :- "))
d1.update(d2)
print(d1)

Ans 42.
n=int(input("Enter number of key-value pairs"))
dict1={}
i=1
while i<=n:
key1=int(input ("key"))
value1=input("enter value")
dict1[key1]=value1
i=i+1
for k in sorted(dict1.keys()):
print(k)
Ans 43.
d1 = {'a': 100, 'b': 200, 'c': 300}
d2 = {'a': 300, 'b': 200, 'd': 400}
for i in d2 :
if i in d1 :
d1[ i ] = d1[ i ] +d2[ i ]
else :
d1[ i ] = d2[ i ]
print(d1)

Ans 44.
dict1={1:10,2:200,3:300,4:400,5:600}
val = list( dict1.values() )
val.sort()
print("Highest 3 values ",val[ - 1 : - 4 : - 1])

Ans 45.
dic = {}
lst = ['a','c','b','d','c','d','e']
lst.sort()
for i in range(len(lst)):
dic[ i + 1 ] = lst [ i ]
print(dic)

Ans 46.
dict1 = eval (input("Enter a Dictionary :-"))
lst = list( dict1.values() )
print("Number of items :-",len(lst))

Ans 47.
[99, 105, 10, 43, 62, 8] Pass -1
[99, 10, 105, 43, 62, 8] Pass-2
[99, 10, 43, 105, 62, 8] Pass - 3
Ans 48.
def Bsort(l):
count = 0
for i in range(len(l) - 1, 0, -1):
for j in range(i):
if l[j] > l[j + 1]:
l[j],l[j+1] = l[j+1],l[j]
print(l)
count += 1
if count == 3:
break

Ans 49.
(i) 13
(ii) False
Ans 50.
Type casting refers to changing a variable of one data type into another. There are two types of type
casting: Implicit and Explicit.
Ans 51.
Comments provide explanatory notes to the readers of the program. Compiler or interpreter ignores
the comments but they are useful for specifying additional descriptive information regarding the
code and logic of the program.

Indentation makes the program more readable and presentable. Its main role is to highlight nesting
of groups of control statements.
TEACHER’S MANUAL

COMPUTER SCIENCE- XII

CH-2 FUNCTIONS

➢ Ans 1.

(i) A program having multiple functions is considered better designed than a


program without any functions because:
1. Program handling becomes easier: Only a small part of the program is
dealt with at a time.
2. Reduced lines of code: While working with functions, a common set of code
is written only once and can be called from any part of the program which
reduces lines of code and programming overheads.
3. Easy updation: In case a function is not used in a program, the same set of
code which is required in multiple programs has to be written repeatedly.
Hence, if we wish to make any change in a formula/expression, we have to
make changes at every place, else it will result in erroneous or undesirable
output. With function, however, it is required to make changes to only one
location (which is the function itself).

Ans 2. def calculate_area(x , y) :


return 1/2 * x * y
base = float(input("Enter the Base of a triangle:"))
height = float (input ("Enter the Height of a triangle:"))
area= calculate_area(base,height)
print("Area of a triangle is:", area)

Ans 3. def calculate_area(x,y,shape):


if shape=='triangle':
return 1/2 * x * y
elif shape=='rectangle':
return x*y
else:
print('Error')
shape=input('Enter the name of the shape')
if shape=='rectangle':
length=float(input('Enter length of a rectangle'))
width=float(input('Enter the width a rectangle'))
area = calculate_area(length,width,shape)
print('Area of a rectangle is',area)
elif shape=='triangle':
base = float(input("Enter the Base of a triangle:"))
height = float (input ("Enter the Height of a triangle:"))
area=calculate_area(base,height,shape)
print("Area of Triangle is:", area )
else:
print('Wrong input')

Ans 4. n=int(input('Enter number'))


for i in range(0,n+1):
for j in range(i):
print('*',end='')
print()

Ans 5. (i) Default arguments: A default argument is an argument that assumes a default
value if a value is not provided in the function call for that argument. Sometimes we can
provide default values for our positional arguments.
(ii) Keyword arguments: If there is a function with many parameters and we want to
specify only some of them in function call, then value for such parameters can be
provided by using their name instead of the position (order). These are called keyword
arguments or named arguments.
Ans 6. There are three types of functions in Python:
(i) Built-in Functions
(ii) Modules
(iii) User-defined Functions
1. Built-in Functions: Built-in functions are the predefined functions that are already available in
Python. Python has many useful built-in functions to make programming easier, faster and more
powerful. These are always available in the standard library and we don’t have to import any
module (file) for using them. For example, int(), print(), eval(), str(), float(), input(), etc.

2. Modules: A module is a file containing functions and variables defined in separate files.
A module is simply a file that contains Python code or series of instructions. Modules also
make it easier to reuse the same code in more than one program. For example, math
module, random module, string module, etc.
3. User-defined functions: User-defined functions are functions that you use to organize your
code in the body of a policy. Once you define a function, you can call it in the same way as the
built-in action and parser functions.
Ans 7. Scope of variables refers to the part of the program where it is visible, i.e., area
where you can refer (use) it. It holds the current set of variables and their values. The
two types of scope of variables are global scope and local scope.
➢ Global (module)
• Names assigned at the top level of a module, i.e., outside of any function,
or directly in the interpreter
• Names declared with a global keyword in a function
• Can be accessed inside or outside of the function
➢ Local (function)
• Names assigned inside a function definition or loop
• Cannot be accessed outside the function
Ans 8. The differences between global scope or local scope are:
➢ Global (module)
• Names assigned at the top level of a module, i.e., outside of any function,
or directlyin the interpreter
• Names declared with global keyword in a function
• Can be accessed inside or outside of the function
➢ Local (function)
• Names assigned inside a function definition or loop
• Cannot be accessed outside the function
Ans 9.
(a) Formal argument
(b) Keyword argument
(c) Actual parameter
(d) Default parameter
(e) Global variable
(f) Local variable
Ans 10. 1 ->5 ->9 ->10 ->5 ->6->1->2>3->6->7->10->11
Ans 11. It will return nothing as function is not being called, otherwise, returns 30.
Ans 12. 60
Ans 13. (i)
1
1
1
(ii)
1
10
1
(iii)
1
10
10
(iv)
Hello
Bye
Ans 14.
y= 5 a= 10
y= 10 a= 2
a+y 12
12
y= 5 a= 10

Ans 15. The function is not called.


Ans 16. (a) The function’s header has a colon missing at the end.
(b) The function is declared using define which is an invalid keyword. In the second line, the
bracket is not closed using parentheses. In the fourth line, variable i is used instead of I (capital
letter) and the input N is saved as a string, the code thus results in 'TypeError' when we try
to divide the integer value by N. In the last line, the incorrect Return statement is used which
should be return and Answer.
(c) In the first statement, the function is not correctly defined. It should be def. The second
function beta() has a missing colon at the end and the return statement and the expression
string ==str(n) are also wrong as the variable n is not defined in this function. The last
statement, where the alpha() function is called, is also wrong because the positional
arguments follow keyword arguments.
Ans 17. The flow of execution refers to the order in which statements are executed during a
program run. In other words, the order in which statements are executed during a program
run is called flow of execution. Function calls plays an important role in the flow of execution.
Instead of going to the next statement, the flow jumps to the first line of the called function,
executes all the statements there, and then comes back to pick up where it left off.
Ans 18.

def dollar_to_rupee(dollar) : #void


print("Rupees in" ,"dollar = ",dollar * 78)
def dollar_to_rupee_2(dollar) : # non Void
return dollar * 78
dollar = float(input("Enter dollar : "))
dollar_to_rupee(dollar) #void
print("Rupees in","dollar = ", dollar_to_rupee_2(dollar) )

Ans 19.

def vol( l = 1, w = 1 , h = 1 ) :
return l * w * h

length = int(input("Enter the length : "))


width = int(input("Enter the width : "))
height = int(input("Enter the height : "))

print("volume of box = ", vol( length , width , height ))

Ans 20.

def multiples(n,x):
if x == 4 :
print(n*x)
else :
print(n*x,end =",")
multiples(n,x+1)
num = int(input("Enter a number :-"))
multiples(num,1)

Ans 21. Recursion:


Recursion is one of the most powerful tools in a programming language. It is a function
calling itself again and again. Recursion is defining anything in terms of itself. In other
words, it is a method in which a function calls itself one or more times in its body.
Advantages:
i. The main benefit of a recursive approach to algorithm design is that it allows
programmers to take advantage of the repetitive structure present in many
problems.
ii. Complex case analysis and nested loops can be avoided.
iii. Recursion can lead to more readable and efficient algorithm descriptions.
iv. Recursion is also a useful way for defining objects that have a repeated similar
structural form.
Disadvantages:
i. It consumes more storage space because the recursive calls along with local
variables are stored on the stack.
ii. The computer may run out of memory if the recursive calls are not checked.
iii. It is less efficient in terms of speed and execution time.
Ans 22.

def add_ser(n):
if n==term+1:
return 0
elif n%2 == 0 :
return add_ser(n+1) + 1/n
elif n%2 != 0 :
return add_ser(n+1) - 1/n

term = int(input("Enter the terms :- "))


print(add_ser(2)+1)

Ans 23.

def g_c_d(a , b) :
if b == 0 :
return a
else :
return g_c_d (b, a % b)

a = int (input("Enter the first number :- "))


b = int (input ("Enter the second number :- "))
print ("Greatest common divisor of ", a ,'&', b, 'is' ,g_c_d(a , b))

Ans 24.

def list_muliply (x) :


mul = 1
for i in x :
mul *= i
print ("Answer after multiply:- ", mul)

lst = eval(input("Enter a List :- "))


list_multiply(lst)

Ans 25.

def fact (n) :


if n== term +1 :
return 1
else :
return n*fact(n+1)
term = int(input("Enter the term :-"))
print("Factorial =",fact(1))

Ans 26.

def prime(a):
for i in range (2,a) :
if a % i == 0 :
return "This is not prime number"
return "Prime number"

a = int(input("Enter a number : "))


print(prime(a))

Ans 27.
def check(x) :
if x[ -1 : - len(x) - 1 : - 1] == x:
print ("String is a palindrome.")
else :
print ("String is not a palindrome ")

string = input ("Enter a String :- ")


check(string)

Ans 28.

def word (x) :


for i in range (len(x) + 1) :
for j in range (len(x) - 1) :
if x[ j ][ 0 ] > x[ j + 1][ 0 ] :
x[ j ], x[ j + 1 ] = x[ j + 1 ], x[ j ]

string = ("-").join(x)
print("Sequence After sorting :- ", string)

str = input ("Enter hyphen-separated sequence of words :- ")


a = str.split("-")
word(a)

Ans 29.

A function calling itself is known as recursive function.

Advantage:

• Recursion makes the code short and simple.

Ans 30.

1 Recursive case

2 Base case

Ans 31. Base case is the case that causes the recursion to end.

Ans 32. It is the case that solves the problem by using a recursive call function to the same function.

Ans 33. Yes, it is necessary to have a base case in a recursive function because the base case is used
to stop the recursive function. If there is no base case, then python gives an error.

Ans 34. Here, base cases are:

(i)

if n == 0 :
return 5

(ii)

elif n == 1 :

return 8

(iii)

else:

return -1

Ans 35. Because of overhead of multiple function calls and maintaining a stack for it.

Ans 36. In iteration, the code is executed repeatedly using the same memory space. That is, the
memory space allocated once is used for each pass of the loop.

On the other hand, in recursion, since it involves a function call at each step, fresh memory is
allocated for each recursive call. For this reason, i.e., because of function call overheads, the
recursive function runs slower than its iterative counterpart.

Ans 37.
(a)

Output:

15
12
9
6
3
Finally

(b) It will give an error, error type (“RecursionError: maximum recursion depth exceeded while
pickling an object”) because there is no “base case”.

(c)

Output:

10
8
6
4
2
Finally

(d) It will also give an error, error type (“RecursionError: maximum recursion depth exceeded while
pickling an object”) because there is no “base case”.

Ans 38. 32
Ans 39. True

Ans 40. Yes, the above function will only work when the number is a power of 2. It will result in fi
nite recursion when n is not a power of 2. check(3) will result in an infinite recursion. The reason
is that in the last else statement, the function is calling itself without any change to the number
n : check(n/1). It returns RecursionError: maximum recursion depth exceeded in comparison
Ans 41. (a) Fn(12)

12 6 3 1 1 2 4 2 1
Output: -3
(b) Fn(10)

10 5 2 1 3 1 1
Output: 1
(c) Fn(7)
7 3 1 1 2
Output: -2
Ans 42. The above code will run into infinite recursion because the value of p is being decremented
after the recursion call. So, it is never actually changing.

Ans 43.

def check_primeAll (N) :

count = 0

for i in range(2, N + 1) :

count = 0

for j in range(2,i) :

if i % j == 0 :

count = 1

if count == 0 :

print(i)

Ans 44.

def EvenSum(NUMBERS):

n=len(NUMBERS)

s=0

for i in range(n):

if(NUMBERS[i] %2==0):

s=s+NUMBERS[i]

print(s)

NUMBERS=(7,8,4,90,66,34)

EvenSum(NUMBERS)

Ans 45.

def COUNTNOW(PLACES):
for i in PLACES.values():

if len(i)>5:

print(i)

PLACES={'1': "DELHI", '2': "LONDON", '3': "PARIS", '4': "NEW YORK", '5': "DUBAI"}

COUNTNOW(PLACES)

Ans 46.

def Calc_Average(tup1):

n=len(tup1)

total=0

avg=0

for i in tup1:

total=total+i

avg=total/n

return (total,avg)

tup1=(80,87,79,90,95)

Calc_Average(tup1)

Ans 47.

(a) abs(x)
(b) pow(x,y)
(c) fabs(x)

Ans 48.

(a) lstrip()
(b) isupper()
(c) isspace()

Ans 49.

def LShift(lst,n):

L=len(lst)

for x in range(0,n):

y=lst[0]

for i in range(0,L-1):

lst[i]=lst[i+1]

lst[L-1]=y

print("Left Shift",lst)

lst= [ 20,40,60,30,10,50,90,80,45,29]

n=3
print("Original list",lst)

LShift(lst,n)

Output:
Original list [20, 40, 60, 30, 10, 50, 90, 80, 45, 29]
Left Shift [30, 10, 50, 90, 80, 45, 20, 40, 60, 60]
TEACHER’S MANUAL

COMPUTER SCIENCE- XII

CH-3: USING PYTHON LIBRARIES

Ans 1. Commonly-used modules that contain source code for generic needs are called libraries. A
library in Python is a collection of various packages. Conceptually, there is no difference between
package and Python library. In Python, a library is used to loosely describe a collection of core or
main modules. For example, the math library of Python caters to mathematical computations.

Ans 2. 1. Open Python Script and then type the following program:

def energy (m, g, h) :

return m * g * h

def distance (u, a, t) :

return (u * t) + (1 / 2 * a * t **2)

def speed (d, t) :

return (d / t)

2. Now save this program as My_module.py.

3. On the Python shell import the module My_module by typing the statement:

import My_module

4. Call the functions:

My_module.energy(10, 4,8)

My_module.distance(1000,12,60)

My_module.speed(5000,15)

Ans 3.

def count_months_days (total_no._of_days):

print ("No. of month :- ", total_no_of_days // 30)

print ("Remaining days after months:- ", total_no_of_days % 30)

Ans 4. 1. Type the following program in a script file:

def vol(r):

return 4/3*( 3.14* r **3)

def area(r):

return 4*( 3.14* r**2)

2. Save this program with sphere.py extension and import it on Python shell with the following
command:

import sphere

sphere.vol(10)
sphere.area(20)

Ans 5. A module is a chunk of Python codes that exists in its own (.py) file and is intended to be
used by Python code outside itself. Modules allow one to bundle together code in a form in
which it can be easily used later. Modules can be “imported” in other programs so that the
functions and other definitions in imported modules become available to code that imports
them.

Ans 6. We reuse the functions defined in a module by importing them into our program. Importing
can be done in two ways:

(i) import <module name >


(ii) from <module name> import <function name>

Ans 7. We can import objects from a module by two ways:

import <module_name>

from <module_name> import <object>

Ans 8. Both statements are different from each other.

(a) import math: This statement imports the math module and creates a reference to that
module in the current calling program or namespace. We use dot(.) operator to access
functions from math module. For example, math.sqrt(121).
(b) from math import*: This statement shall import all the sub-modules or objects defined in
the math module into the current namespace. So, we would use only function name without
specifying the module name.

Ans 9. The math module is a collection of mathematical functions. They can be used on floats or
integers, but are primarily intended for floats and typically return floats. Some of the functions
available in math module are sqrt(), pow(), floor(), ceil(), etc.

Ans 10. When Python encounters an import statement, it does the following:
(i) Code of the imported module is interpreted and executed.
(ii) Defined functions and variables created in the module are now available to the program
that imported the module.
(iii) For imported module, a new namespace is set up with the same name as that of
the module. Any duplicate import statement for the same module in the same
program is ignored by Python.
(iv) If the search ends without any outcome, then the program throws a NameError
exception.

Ans 11. Output: 5

Ans 12. def main():

r=float(input(“Enter any radius:”))

a=math.pi*math.pow(r,2)

print(“Area=”, a)

main()

Ans 13. A Python name is an identifier—something we use to access a Python object and,
in Python, everything is an object. Thus, a name can hold any kind of value. Namespaces
are used to distinguish between different sections of a program. The body of a section
may consist of a method, a function, or all the methods of a class. So, a namespace is a
practical approach to define the scope, and it helps to avoid name conflicts. A
namespace in Python is a collection of names. So, a namespace is essentially a mapping
of names to corresponding objects. It ensures that names are unique and won’t lead to
any conflict. Python implements namespaces as dictionaries.

Ans 14. Each Python program file is a ‘module’ that imports other modules like objects and
attributes. A Python program folder is a ‘package’ of ‘modules’. A package can have ‘modules’ or
‘sub-folders’.

Ans 15.

import <module> statement imports the given module in the current namespace while from
<module> import statement imports the function which is present in a given module. For example,

(i) import math

a = 144

print( math.sqrt(a) )

(ii)

from math import sqrt

a = 121

print( sqrt(a) )

Ans 16. Using import * statement will import all the functions and classes into the currently-
executing program namespace, which may overwrite functions. This can be dangerous, especially if
we do not maintain that module and it becomes very difficult to identify from which library a
particular function came. This situation is called polluting the namespace.

Ans 17. A Python library is a reusable chunk of code that you may want to include in your programs/
projects. A library describes a collection of core modules. A library can be installed using a package
manager. A package must contain __init__.py file.

Ans 18. site-package is the target directory of manually built Python packages. When we build and
install Python packages from the source, we will find the installed modules in site-packages by
default.

Ans 19. (a) It imports module X.


(b) It imports all functions from module X.
(c) It imports functions a, b c from module X.

Ans 20. Both functions are in the math module.


Using Python Libraries

Ans 21. To access one of the functions from a module using import <module name> method, we
have to specify the name of the module and the name of the function, separated by a dot. This
format is called dot notation.

Ans 22. From the module import object, this statement should be avoided because it can lead to
name classes. For instance, if the program uses an object name that is also being imported, the
program will not be able to use that imported object. For example,

From math import log

def log(x):
return x*x*x

log(10)#it will return 1000 instead of the actual log value of 10.

Ans 23. The Python Standard Library is a collection of script modules accessible to a Python program
to simplify the programming process and remove the need to rewrite commonly-used commands.
They can be used by 'calling/importing' them at the beginning of a script.

Ans 24. “import” in Python loads a module into its own namespace whereas “from” imports a
module into the current namespace. “from” is used when we don't need to mention the module
name whereas when the “import” is used, we should mention the module name.

Ans 25.

one_mille_in_km = 1.609344

one_feet_in_inche = 12

def mile_to_km(x) :

"Return value in kilometer from miles "

return x * one_mille_in_km

def km_to_mile(x) :

"Return value in miles from kilometer "

return x / one_mille_in_km

def feet_to_inches( x ):

"Return value in inches from feet "

return x / one_feet_in_inche

def inches_to_feet(x) :

"Return value in feet from inches "

return x * one_feet_in_inche

Ans 26.

kg_in_tonnes = 0.001

kg_in_pound = 2.20462

def kg_to_tonnes(z):

kt = z*kg_in_tonnes

print(z,"kg is equal to",kt,"tonnes")

def tonnes_to_kg(z):

tk = z/kg_in_tonnes
print(z,"tonnes is equal to",tk,"kg")

def kg_to_pound(z):

kp = z*kg_in_pound

print(z,"kg is equal to",kp,"pounds")

def pound_to_kg(z):

pk = z/kg_in_pound

print(z,"pounds is equal to", pk, "kg")

Ans 27.

def area_of_triangle(b, h) :

return 1 / 2 * b * h

Ans 28.

def convert(string):

lst = string.split()

for i in lst:

print (i.capitalize(), end = " ")

convert("Python is easy to learn")

Ans 29.

def deleteChar(string, char):

newstr = “”

for ch in string:

if ch != char:

newstr+=ch

return newstr

string = input("Enter a string: ")

char = (input("Enter a character: "))

print(deleteChar(string, char))

Ans 30.

string = input("Enter a string :-")

sub = input("Enter a sub-string :-")

count = 0

n=0
while n < len(string) :

n = string.find(sub,n)

if n == -1 :

break

else :

count += 1

n += 1

print(count)
TEACHER’S MANUAL

COMPUTER SCIENCE - XII

CH. 4: DATA FILE HANDLING

Ans 1. ‘w’ mode: Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, it creates a new file
for writing.

‘a’ mode: Opens a file for appending. The file pointer is at the end of the file if the file exists. That is, the file is in the append
mode. If the file does not exist, it creates a new file for writing.

Ans 2. The file_object establishes a link between the program and the data file stored in the permanent storage and access
modes define the location of the file pointer, i.e., from where the data has to be read and written to the file.

Ans 3. ‘open’ function: When we want to read or write a file, we must first open the file. Opening the file communicates
with the operating system, which knows where the data for each file is stored. When we open a file, we are asking the
operating system to find the file by name and make sure the file exists. If the opening is successful, the operating system
returns us a file handle.

Close() function: The close() method of a file object flushes any unwritten information and closes the file object, after which
no more writing can be done. Python automatically closes a file when the reference object of a file is reassigned to another
file. A close() function breaks the link between the file object and the file on the disk.

Ans 4. To open binary file in read mode:

file=open(“C:\Myfiles\text1.dat”,’rb’)

To open binary file in write mode:

file=open(“C:\Myfiles\text1.dat”,’wb’)

Ans 5. In the file modes ’rb’, ‘ab’, ‘a+b’ and ‘r+’, data will not be lost.

Ans 6. (a) String

(b) String

(c) list

(d) list

Ans 7. (a)
• If the file is open in read mode, it gives an error.
• If the file is open in write or append mode, a new file will be created by python.

(b)
• If file is open in read mode, then python reads the data according to the program.
• If the file is open in write mode, then python deletes all data and writes new data according to the user.
• If the file is open in append mode, then the data in the file is retained and new data being written will be appended to
end.

Ans 8.

File Meaning
Mode
s
R Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the
default mode. If the specified file does not exist, it will generate FileNotFoundError.
Rb Opens a file for reading only in binary format. The file pointer is placed at the beginning of the
file. This is the default mode.
r+ Opens a file for both reading and writing. (+) The file pointer will be at the beginning of the
file.
rb+ Opens a file for both reading and writing in binary format. The file pointer will be at the
beginning of the file.
w Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, it
creates a new file for writing.
wb Opens a file for writing only in binary format. Overwrites the file if the file exists. If the file
does not exist, it creates a new file for writing.
w+ Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file
does not exist, itt creates a new file for reading and writing.
wb+ Opens a file for both writing and reading in binary format. Overwrites the existing file if the file
exists. If the file does not exist, creates a new file for reading and writing.
a Opens a file for appending. The file pointer is at the end of the file if the file exists. That is, the
file is in the append mode. If the file does not exist, it creates a new file for writing.
ab Opens a file for appending in binary format. The file pointer is at the end of the file if the file
exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for
writing.
a+ Opens a file for both appending and reading. The file pointer is at the end of the file if the file
exists. The file opens in the append mode. If the file does not exist, it creates a new file for
reading and writing.
ab+ Opens a file for both appending and reading in binary format. The file pointer is at the end of
the file if the file exists. The file opens in the append mode. If the file does not exist, it creates
a new file for reading and writing.

Ans 9. def fileout():

f = open("STRS.txt","w")
while True :
data = input("Enter string :- ")
f.write (data + "\n")
user = input("Do you want to enter more data (yes/no)")
if user == "No" or user == "no" :
break
f.close()

Ans 10. (i) three file objects are required to process three files sequentially.

(ii) three file objects are required to merge two sorted files.

Ans 11. Binary form: In binary files, data is stored in raw, i.e., binary form, no delimiter is needed and translation of data is
not required. Hence, binary files are faster and easier for the program to read and write than text files.

Text form: In text files, data is stored in Unicode or ASCII that can be read by program and user both. So, if data needs to be
readable by the user, text file is more suitable to store data.

Ans 12. The close() method of a file object flushes any unwritten information and closes the file object, after which no
more writing can be done. Python automatically closes a file when the reference object of a file is reassigned to another
file. It is a good practice to use the close() method to close a file.

Ans 13. When a file needs to be read by people or needs to be ported to a different type of system, text files
should be preferred over binary files.
Ans 14.
fobj1 = open("story1.txt","r")
fobj2 = open("story2.txt","w")
data = fobj1.readlines()
for i in data :
word = i.split()
fobj2.write( " ".join(word))
fobj2.write("\n")

print("File copied")
fobj1.close()
fobj2.close()

Ans 15.
import pickle
def bin_file( ) :
fobj1 = open("Sports.dat","rb")
fobj2 = open("Atheletic.dat","wb")
try :
while True :
data = pickle.load( fobj1 )
word = data.split(" ")
if data [:9] == "atheletics" or data[:9] == "Atheletics":
pickle.dump( data, fobj2 )
except EOFError :
fobj1.close()
fobj2.close()
print("Pragram saved Succesfully !!")
bin_file()

Ans 16.
Count_to = 0
Count_the = 0
fobj = open("Poem.txt", "r")
lst = file.readlines()
for i in lst :
word = i.split()
for j in word :
if j == "to" or j == "To" :
Count_to += 1
elif j == "the" or j == "The" :
Count_the += 1
print("Number 'to' : " , Count_to)
print("Number 'the' : " , Count_the)
file.close()

Ans 17.
count = 0
file = open("Poem.txt","r")
data = file.read()
for i in range (len(data)):
if data[i].isupper():
count += 1
print("Number of uppercase alphabets:", count)
file.close()

Ans 18.
file1 = input("Enter the name of the original file :- ")
file2 = input("Enter the name of the New file :- : ")
fobj1 = open( file1, "r")
fobj2= open( file2, "w")
data = fobj1.read()
fobj2.write(data)
print("Program run successfully")
fobj1.close()
fobj2.close()

Ans 19.
file1 = input("Enter the name of file which you want to append : ")
file2 = input("Enter the name of original file : ")
f1 = open( file2 , "r" )
f2 = open( file1 , "a" )
data = f1.read()
f2.write( "\n" + data)
print("Program run successfully ")
f1.close()
f2.close()

Ans 20.
u_p = open("Upper.txt","w")
l_w = open("Lower.txt" , "w" )
o_s = open ("Others.txt" , "w")
while True :
text = input("Enter a character: ")
if text == "quit" or text == "Quit" :
break
elif text.isupper() :
u_p.write( text + " " )
elif text.islower( ) :
l_w.write( text + " " )
else :
o_s.write( text + " " )
u_p.close()
l_w.close()
o_s.close()

Ans 21.
f = open("myfile.txt",'r')
data = f.readlines()
for i in data :
age = i.split(",")
if int(age[ 2 ]) >= 30 :
print(age[ : 2 ])

Ans 22.
count = 0
file = open("LINES.txt","r")
lst = file.readlines()
for i in lst :
if i[ 0 ] == "A" :
print(i)
count += 1
print()
print("Number of sentences started with A : ",count)
file.close()

Ans 23.

(a) Text file in both read and write mode :


file = open("example.txt","w+" )
(b) Binary file in write mode:
file = open("bfile.dat","wb" )

(c) Text file in both read and append mode:


file = open ("try.txt","a+" )
(d) Binary file in read only mode:
file = open("bfile.dat","rb" )

Ans 24. The close() method of a file object flushes any unwritten information and closes the file object after which no more
writing can be done. Python automatically closes a file when the reference object of a file is reassigned to another file. It is
a good practice to use the close() method to close a file.

Ans 25. In part "a", file P will read 10 characters but will not print anything while in part "b", it will read the whole character
present in the practice file and store it in variable "x".
Ans 26.
f = open("myfile.txt","w")
while True :
text = input("Enter text (Press End to stop) :")
if text == "END" :
break
else :
f.write(text + "\n")
f.close()
f = open("myfile.txt","r")
data = f.readlines()
for i in data :
if i[0].isupper() :
print(i)
f.close()

Ans 27.
def add(text) :
f.write("\n"+ text)
f = open("myfile.txt",'a')
text = input("Enter text:")
add(text)
f.close()

Ans 28.
file1 = open("Story.txt","r")
file2 = open("myfile.txt","w")
data = file1.readlines()
for line in data :
words = line.split()
for j in words :
file2.write( j )
file2.write(" = ")
file2.write( "index : " + str ( line.index( j ) ) + " line:" +
str(data.index( line) +1 ) )
file2.write( "\n" )
file1.close()
file2.close()

Ans 29.
fname = input("Enter name of the file:")
f = open(fname + ".txt",'r')
data = f.readlines()
for i in data :
if "#" in i :
print(i)
f.close()

Ans 30.
f1 = open("myfile.txt",'r')
data = f1.readlines()
content = ""
for i in data :
content += i+"\n"
for i in range (-1 , -len(content),-1):
print(content[ i ],end = "")
f1.close()

Ans 31.
f1 = open("mylife.txt",'r')
data = f1.readlines()
a = ""
for i in data :
for j in i :
if j.isalnum():
a += j
print("file size:",len(a),"bits")
f1.close()

Ans 32.
def Remove_Lowercase(f1,f2) :
data = f1.readlines()
for i in data :
if i[0].isupper() :
f2.write(i + "\n")
f1 = open("mylife.txt",'r')
f2 = open("mydiary.txt",'w')

Remove_Lowercase(f1,f2)
f1.close()
f2.close()

Ans 33.
f = open("mylife.txt",'r')
data = f.readlines()
for i in range (len(data)) :
line = data[ i ].split(",")
print("Line number =",i+1)
for j in range (len(line)):
print("Record number = ",j+1,end=" , ")
print(line[ j ])

f.close()

Ans 34.
file = open("mylife.txt", "w")
lst = []
while True:
data = input("Enter the content:")
if data == 'exit':
break
else :
lst = lst + [data + '\n']
file.writelines (lst)
file.close ()

Ans 35.
f1 = open("Diary.txt",'r')
data = f1.readlines()
for i in data :
print(i)
f1.close()

Ans 36. (a) file=open(‘Result.dat’,’rb’)


(b) f=open(‘Result.dat’,‘rb’)
data=f.readlines()
print(data[-1])

Ans 37.
f = open("emp.txt ",'a')
empno = input("Enter Employee No:")
ename = input("Enter Employee name:")
salary=float(input("Enter Salary"))
desig=input("Enter Designation:")
f.write(empno)
f.write(ename)
f.write(str(salary))
f.write(desig)
f.close()

Ans 38.

(a) It reads the text file.

(a) It opens the text file.

Ans 39.
Hello, world!
How are you?

Ans 40. This code print(size) will print 30 as ‘Welcome to Python Programming’ contains 30 characters. And print(data)
does not print anything because all the characters have been read by the read() function.

Ans 41.
f = open("Student.dat",'rb')
data = f.readlines()
for i in data :
line = i.split(',')
if (line[ 1 ])< 40 :
print(i)

f.close()
Ans 42.
4
8

Ans 43.
import pickle
file = open("Product.dat","rb")
lst = [ ]
while True :
try :
data = pickle.load(file)
lst += [data]
except EOFError :
break

file.close()

f = open("Product.dat","wb")
stock = int(input("Enter name of the stock to be updated :"))
for i in lst :
if stock == i["stock"] :
prod_code = input("Enter prod_code : ")
prod_desc = input("Enter prod_desc : ")
i["prod_code"] = prod_code
i [ "prod_desc" ] = prod_desc
pickle.dump(lst,f)
f.close()

Ans 44.
import pickle
file = open("Student.dat ","rb")
lst = [ ]
while True :
try :
data = pickle.load(file)
lst += [data]
except EOFError :
break
file.close()
for i in lst :
if i [2] > 75 :
print(i)

Ans 45.

To open a text file ‘Book.txt’ in read mode:


F = open(“BOOK.TXT”, “r”)
To open a text file “BOOK.TXT” in write mode:
F = open(“BOOK.TXT”, “w”)
Ans 46.

(a) File=open(‘Book.txt’, ‘a+’)


(b) File=open(‘Book.txt’, ‘w’)
(c) File=open(‘Book.txt’,’a’)
(d)
Ans 47. This program will accept name and phone number from the user and save it in ‘contacts.csv’ file.

Ans 48.
file = open("contacts.csv", "r")
data = file.readlines()
for i in data :
for j in range(len(i) +1 ) :
if i[ j ].isdigit() :
print("Name :",i[ : j-1]," Phone :",i[ j : ])
break

Ans 49. This program accepts a name from the user and finds this name in ‘Contact.csv’ file. If the name is present in the
file, then display its name and phone number.

Ans 50.
import pickle
file = open("Record.dat","wb")

while True :
dic = { }
Item_No = int(input("Enter Item No."))
Item_Name = input("Enter Item name :")
Qty = int(input("Enter Quantity : "))
Price = float(input("Enter price :"))
Amount=Price*Qty

dic[ "Item_No" ] = [ Item_No]


dic[ "Item_Name" ] = [ Item_Name ]
dic[ "Qty" ] = [ Qty ]
dic[ "Price" ] = [ Price ]
dic["Amount"] = [Amount]
pickle.dump( dic , file )
ans = input("Do you want to enter more records [ Y/N ] :")
if ans == "n" or ans == "N" :
break
file.close()

file = open("Record.dat","rb")
while True :
try :
dic = pickle.load(file)
print( "Item No. :","\t", dic[ "Item_No" ])
print( "Item Name :","\t", dic[ "Item_Name" ] )
print( "Quantity :","\t", dic[ "Qty" ] )
print( "Price :","\t",dic[ "Price" ] )
print( "Amount :", "\t" , dic[ "Amount"] )

except :
file.close()

Ans 51.
import csv
data = []
while True :
item_code = input("Enter item code :-")
name = input("Enter name :-")
price = input("Enter price :-")
qty = input("Enter Quantity :-")
data += [[ item_code, name, price, qty ]]
user = input("Do you want to enter more data (yes/no)")
if user == "No" or user == "no" :
break
with open("Groceries.csv","w",newline="") as f :
csv_file = csv.writer(f,delimiter=',')
csv_file.writerows(data)
TEACHER’S MANUAL

COMPUTER SCIENCE- XII

CH. 6: DATA STRUCTURES IN PYTHON

Ans 1. A Stack is a linear/sequence structure or a list of elements in which insertion and deletion can take place only
at one end, i.e., Stack’s top. For example, a pile of books, a Stack of coins, where you can remove only the top book
or the coin placed at the top. Stack is called LIFO (last in, first out) data structure because the element inserted last
would be the first to be deleted.

Ans 2. Two ways to create Stacks in Python are:

(i) Using list() function


(ii) By assigning elements in square brackets.

Ans 3. Some of the applications of Stacks include:


1. A simple example of Stack application is reversal of a given line. This can be accomplished by pushing
each character onto a Stack as it is read. When the line is finished, characters are then popped off
the Stack and they will come off in the reverse order.
2. The compilers use Stacks to store the previous state of a program when a function is called or during
recursion.
3. Another important Stack application is backtracking. (Backtracking is a form of recursion. But it
involves choosing only one option out of the possibilities.) Backtracking is used in a large number
of puzzles like Sudoku and in optimization problems such as knapsack.
4. Undo Mechanism in Text Editors is accomplished by keeping all text changes in a Stack.

Ans 4. Yes, stack can be used to convert a decimal number into a binary number. Example,
stack= []
decimal= int(input("Enter the decimal num : "))
while decimal!=0:
num= decimal%2
decimal = decimal//2
stack.append(num)
while len(stack) != 0:
a=stack.pop()
print(str(a),end='')

Ans 5. Algorithm to push an element into the stack:

(i) START
(ii) Stack=[ ] #Initialize a n e m p t y l i s t
(iii) element = input(“Enter the value to be added in the stack :”)
(iv) Stack.append(element) #Adding element into list
(v) END

Ans 6. Algorithm to pop an element from the stack:

(i) START
(ii) St_len = len(Stack) #Count the total number of elements in the Stack
(iii) if St_len == []: #Checks whether the Stack is e mpty or not
print(“Stack is empty”)
go to step 5
(iv) element = Stack.pop() #Removing last element from top of the Stack
(v) END

Ans 7.
def push(stack):
num=int(input("Enter integer number"))
temp=[num]
stack.append(temp)
def pop(stack):
if(stack==[]):
print("No Record")
else:
print("Deleted Record is :",stack.pop())
def display(stack):
l=len(stack)
for i in range(l-1,-1,-1):
print(stack[i])
stack=[ ]
ch='y'
while(ch=='y' or ch=='Y'):
print("1. Add Number\n")
print("2. Delete Number\n")
print("3. Display Number\n")
print("4. Exit")
op=int(input("Enter the Choice"))
if(op==1):
push(stack)
elif(op==2):
pop(stack)
elif(op==3):
display(stack)
elif(op==4):
break
else:
print('Wrong Input')
ch=input("Do you want to continue(Y/N)")

Ans 8.
def push(stack):
name=input("Enter Student name")
temp=[name]
stack.append(temp)
def pop(stack):
if(stack==[]):
print("No Record")
else:
print("Deleted Record is :",stack.pop())
def display(stack):
l=len(stack)
for i in range(l-1,-1,-1):
print(stack[i])
stack=[ ]
ch='y'
while(ch=='y' or ch=='Y'):
print("1. Add Student name\n")
print("2. Delete Student name\n")
print("3. Display Student name\n")
print("4. Exit")
op=int(input("Enter the Choice"))
if(op==1):
push(stack)
elif(op==2):
pop(stack)
elif(op==3):
display(stack)
elif(op==4):
break
else:
print('Wrong Input')
ch=input("Do you want to continue(Y/N)")

Ans 9. A Queue is called FIFO (first in, first out) data structure because the item
first inserted is the first to get removed A Queue consists of two open ends—
Front and Rear where,
• Data can only be removed from the front end of the Queue.
• A new data element can only be added to the rear end of the Queue.
Ans 10.
box = []
count = 0
def enqueue(box, element):
box.append(element)

def isEmpty(box):
if len(box)==0:
return True
else:
return False

def dequeue(box):
if not (isEmpty(box)):
return box.pop(0)
else :
return "Box is empty"

def size(box):
return len(box)

while(True):
print("1. Adding a shuttlecock")
print("2. Removing a shuttlecock")
print("3. Display number of shuttlecock")
print("4. exit ")
choice = int(input("Enter your choice"))
if choice == 1:
index+=1
enqueue(box,count)
print("Shuttle added")
continue
elif choice == 2:
deleteshuttle = dequeue(box)
print("The shuttle removed is : ",deleteshuttle)
continue
elif choice == 3:
print("The number of shuttles in the box = ",size(box))
continue
elif choice == 4:
break
else:
print("Wrong choice.")

Ans 11.
stack =[]
c='y'
while (c=='y'or c=='Y') :
print()
print("1. Add")
print("2. Delete")
print("3. Display")
print("4. Exit")
choice = int(input("Enter your choice:"))
if (choice==1):
a= float(input("Enter floating point number: "))
stack.append(a)
elif choice == 2 :
if stack == []:
print("UnderFlow")
else :
stack.pop()
print(stack)
elif choice==3:
l=len(stack)
for i in range(0,l):
print(stack[i])
else :
print("Wrong Input")
c=input("Do you want to continue")

Ans 12.
def add(directory):
city_name=input("Enter city name: ")
pincode=int(input("Enter pincode"))
data=[city_name,pincode]
directory.append(data)
def delete(directory):
directory.pop()
print(directory)

directory =[]
c='y'
while (c=='y'or c=='Y') :
print()
print("1. Add")
print("2. Delete")
choice = int(input("Enter your choice:"))
if (choice==1):
add(directory)
elif choice == 2 :
if directory == []:
print("UnderFlow")
else :
delete(directory)
else :
print("Wrong Input")
c=input("Do you want to continue")

Ans 13.
def add(Books):
book_name=input("Enter book name: ")
book_price=float(input(“Enter price of book”))
data=[book_name, book_price]
Books.append(book_name)
print(Books)
def delete(Books):
if Books == []:
print("UnderFlow")
else :
Books.pop()

Ans 14.
def AddClient(Client):
client_name=input(“Enter name of the client:”)
Client.append(client_name)
print(Client)

def DeleteClient(Client):
if Client==[];
print(“Queue is empty”)
else :
Client.pop(0)

Ans 15.
def AddScore(Game):
score=int(input("Enter game Score: "))
Game.append(score)
print(Game)
def Delscore(Game):
if Game == []:
print("Score not exist")
else :
Game.pop()

Ans 16.
s=[]
num=int(input("Enter number of elements in stack:"))
for i in range(num):
stack = eval(input("Enter a stack :"))
s.append(stack)
print("Original Stack:\n",s)

for i in range (len(s)):


for j in range(len(s)-1):
if s[j] > s[j+1]:
s [j],s[j+1]=s[j+1],s[j]

print("Sorted stack\n",s)

Ans 17.
stack = eval(input("Enter elements in stack separated by comma:"))
queue= eval(input("Enter elements in queue separated by comma :"))
if len(stack) == len(queue) :
print("Stack and Queue are of similar size ")
else :
print("Both are of different size")

stack_element = stack[-1]
print(stack[-1])
queue_element = queue[0]
print(queue_element)
if stack_element == queue_element :
print("Both have same element ")

else :
print("Both have different element ")

Ans 18. Algorithm to add an element into the stack:

(i) START
(ii) Stack=[ ] #Initialize an empty list
(iii) element = input(“Enter the value to be added in the stack :”)
(iv) Stack.append(element) #Adding element into list
(v) END

Algorithm to insert an element into a queue:

1. START
2. Queue= [ ] #initialize an empty list
3. element = input(“Enter the element to be added to the Queue :”)
4. Queue.append(element) #Adding element into the list Queue
5. STOP
Ans 19.
n = int(input("Enter the number of values: "))
odd=[]
for i in range(n):
num = int(input("Enter number : "))
if num%2 != 0:
odd.append(num)
print("Stack with odd numbers",odd)
largestNum = odd.pop()
while(len(odd)>0):
num = odd.pop()
if num>largestNum:
largestNum=num
print("The largest number found is: ",largestNum)

Ans 20.
stack = [ ]
while True :
print("1. Push")
print("2. Pop")
choice = int(input("Enter your choice : "))

if choice == 1:
num = int(input("Enter a number : "))
stack.insert(0,num)

elif len(stack) == 0 :
print("Underflow")

elif choice == 2:
stack.pop(0)
print("Your Stack :-",stack)
c = input ("Do you want to continue: ")
if c == "No" or c== "no":
break

Ans 21.
stack = [ ]
while True :
print("1. Push")
print("2. Pop")
choice = int(input("Enter your choice : "))

if choice == 1:
num = int(input("Enter a number : "))
stack.insert(0,num)

elif len(stack) == 0 :
print("Underflow")

elif choice == 2:
stack.pop(0)
print("Your Stack :-",stack)
c = input ("Do you want to continue: ")
if c == "No" or c== "no":
break

Ans 22.
queue = [ ]
deleteno = 0
while True :
print()

print("1 Insert element ")


print("2 Delete element ")
print("3 Exit ")
choice = int(input("Enter your choice: "))
if choice== 1:
data = int(input("Enter the data: "))
queue.append(data)
elif choice == 2:
if queue == [ ]:
print("UnderFlow")
else :
queue.pop(0)
else :
break
print("Elements in queue are = ",queue)

Ans 23.
def isEmpty(Qu):
if Qu == []:
return True
else:
return False

def Enqueue(Qu, item):


Qu.append(item)
print(Qu)

def Dequeue(Qu):
Qu.pop(0)
Ans 24.
def AddCustomer(Customer):
cust_name=input(“Enter name of the client:”)
Customer.append(cust_name)
print(Customer)

def DeleteCustomer(Customer):
if Customer==[];
print(“Stack is empty”)
else :
Client.pop()
TEACHER’S MANUAL

COMPUTER SCIENCE- XII

CH-7: COMPUTER NETWORKS

Ans 1. Computers are connected through World Wide Web which comprises a large network
and shares a common communication protocol (Transmission Control Protocol-Internet
Protocol, TCP/IP). It allows computers of different types to exchange information and is known
as the internet.
Ans 2. Several devices connected to each other for reliable communication/transfer of
data constitute a network. A network can consist of a computer, fax machine, printer,
camera, cell phone, etc.
Ans 3. There are five types of topologies:
• Mesh topology
• Bus topology
• Star topology
• Ring topology
• Tree topology
Ans 4. The frequency range for radio waves is from 500 kHz to about 1000 MHz.
Ans 5. 18 Gigabit per second is equal to 18,000,000,000 bits per second.
Ans 6.
(a) Bandwidth: The amount of data that can be passed along a communication channel in
a given period of time (1 second) is termed as bandwidth. The measuring unit of
bandwidth is hertz (Hz). It measures the information-carrying capacity of a line or a
network.
(b) Bluetooth: Bluetooth refers to a telecommunication industry specification that defines
how different devices can be connected virtually and transfer information among
themselves. Bluetooth technology is commonly used in various portable devices such as
laptops and PDAs to establish a wireless connection in the form of Wireless LAN
(WLAN).
(c) DNS: Domain Name System is a mechanism that translates human-readable domain
names (for example www.w3schools.com) to their corresponding IP address (for
example 192.34.54.89).
(d) Data Transfer Rate: It is the amount of data transferred in one direction over a link
divided by the time taken to transfer it in bits per second (bps). The various
measuring units are bits per second (bps) and bytes per second (Bps) or baud, kilobits
per second (Kbps),megabits per second (Mbps), gigabits per second (Gbps), terabits
per second (Tbps.)
1 Kbps=210 bps=1024 bps
1 Mbps=220 bps=1024 Kbps

1 Gbps=230 bps=1024 Mbps

1Tbps=240 bps=1024 Gbps

(e) HTTP: Hyper Text Transfer Protocol is used to transfer all files and other data (collectively
called resources) from one computer to another on the World Wide Web. This protocol is
used to transfer hypertext documents over the internet. HTTP defines how the data is
formatted and transmitted over the network.
Ans 7. Wide Area Network(WAN)

Ans 8.
Star topology layout of 5 connecting computers:

Node1 Node2

Hub/Switch

Node5
Node3

Node4

Star topology

Layout of 5 connecting computers in Bus topology:

Node1 Node2 Node3

Terminator Terminator

Node5
Node4

Bus topology
Ans 9. WWW: WWW is an information service that can be used for sending and receiving
information over the internet through interlinked hypertext documents. The World Wide
Web is based upon client-server architecture where a client sends a request and the server
processes that request and sends responses. A WWW client is called a web browser and
a WWW server is called a web server.
Internet: Internet is a network of networks. The computers are connected through World Wide
Web that comprise a large network and share a common communication protocol
(TransmissionControl Protocol-Internet Protocol, TCP/IP). It allows computers of different types
to exchange information and is known as the internet.

Ans 10.

Star topology Bus topology


A central hub is required to connect all computers A long cable known as backbone is used to connect
with each other. all computers with each other.
The data is transmitted from the sender to the The data is transmitted through a long cable from
receiver by passing through the hub. the sender to the receiver.
No collision takes place through transmission of Collision can take place as the data can be
data. transmitted from both ends at the same time.
If the central hub fails, the entire network shuts If there is a break in a cable, no transmission takes
down. place.

Ans 11.

(a) Baud is a unit of measurement for the information-carrying capacity of a communication


channel.
(b) Communication Channel: A channel is a communication path through which the data is
transmitted from the sender device to the receiver device. A communication channel is
also known as communication media or transmission media. Communication media can be
wireless or wired. Wireless media is also known as unguided media while wired media is also
known as guided media.
(c) Hub: It is a multi-port and unintelligent network device that simply transfers data
from one port of the network to another. A hub is a hardware device used to connect
several computers together with different ports. When the packet reaches one port,
it is copied to all other ports of the hub without changing the destination address in
the frame. Rather,it simply copies the data to all of the nodes connected to the hub.
(d) Repeater: A repeater is a device that operates only on the physical layer of the OSI
model. As a signal travels a fixed distance, before attenuation of the signal, a repeater
is used which amplifies and restores signals for long-distance transmission. A repeater
is an electronic device that receives a signal before it becomes too weak and
regenerates the original signal. Also, it is a two-port network device that strengthens
the signal intensity and connects two identical networks. In most twisted pair Ethernet
configurations, repeaters are required for cable runs longer than 100 metres. A repeater
does not change the functionality of the network; instead, it makes the signal strong
before it degrades.
Ans 12. GSM: Global system for mobile communication (GSM) is a wide-area wireless
communications system that uses digital radio transmission to provide voice data and
multimedia communication services. A GSM system coordinates the communication
between mobile telephones, base stations and switching systems.
GPRS: GPRS or General Packet Radio Services provides various features over 2G
phones with respect to high-speed data transfer. A user can send and receive data at the
same time and thus uses the same bandwidth for both purposes. Using GPRS technology, a
user can make a call and at the same time receive a message without disconnecting the
call. However, GPRS usage is charged for the amount of data sent or received.

Services Provided By GPRS


(a) Sending and receiving text messages.
(b) Internet access.
(c) Multimedia Messaging Service (MMS).
(d) Internet applications for smart devices through Wireless Application Protocol
(WAP).
Ans 13. Modem: A MODEM (Modulator DEModulator) is an electronic device that enables a computer
to transmit data over telephone lines. It is a device used to convert digital signals into analog
signals and vice versa. There are two types of modems, namely internal modemand external
modem.

The functioning of internal and external modem:

Internal Modem:
An internal modem is placed inside a computer. It usually comes pre-installed in the computer. The
best thing about internal modem is that it operates with the computer’s power supply and does not
need an additional supply to work.

2. External Modem:
An external modem is quite similar to an internal modem in that it also allows access to the Internet.
The external modem is an external part of the computer. It can be used when a computer is unable
to fit an internal modem inside of it. The modem typically connects to the computer via a serial or
USB cable, and it also needs an external power supply to operate.

Ans 14.

(a) PPP: Point-to-Point Protocol


(b) POP3: Post Office Protocol
(c) VoIP: Voice Over Internet Protocol
(d) IRC: Internet Relay Chat
Ans 15.
(a) Router: A router is a networking device that forwards data packets from the
source machine to the destination machine over a network by using the shortest
path. Routers are used at the network layer, which is the third layer of the OSI model.
A router uses IP address to connect a local area network to the internet.
Compared to a hub or a switch, a router has advanced capabilities as it can
analyze the data being carried over a network, decide/alter how it is packaged,
and send it to another network of a different type.

(b) Bridge: A bridge is a device that works on the physical layer as well as on data link
layer.A network bridge connects multiple network segments (LANs) at the data link
layer (layer 2) of the OSI model. Bridges relay frames between two originally separate
segments that follow the same protocols. When a frame enters a bridge, the bridge
not only regenerates the signal but also checks the physical address of the
destination and forwards the newcopy only to that port. An important advantage
of using a bridge is that it is a smarter hub as it can filter network traffic on the
basis of the MAC addresses.

(c) Gateway: A gateway is a device that connects dissimilar networks. In the internet,
several networksare communicating with each other and each network has a different
configuration. Inorder to make reliable communication, there must be a device that
helps in communicating. Gateway provides necessary translation of data received
from the network into a format or protocol recognized by devices within the internal
network. A gateway is a device that establishes an intelligent connection between a
local area network and external networks with completely different structures.
Ans 16. A Wi-Fi card is used in a desktop computer that enables a user to establish an internet
connection. Wi-Fi cards are known as wireless fidelity cards as they allow the user to set up a
connection without any wire. Wi-Fi cards are widely used in notebook computers due to their
highly portable nature. A Wi-Fi card is either an internal or external Local Area Network adapter
with a built-in wireless radio and antenna. The most common Wi-Fi card used in desktop
computers is PCI-Express Wi-Fi card made to fit the PCI-Express card sloton the motherboard.

Ans 17. Every computer connected to the internet uses the same set of rules for
communication. A set of rules is called a protocol. The communication protocol used by the
internet is TCP/IP. The TCP (Transmission Control Protocol) part is responsible for dividing
the message into packets on the source computer and reassembling them at the destination
computer. The IP (Internet Protocol) is responsible for handling the address of the destination
computer so that the packet is sent to its proper destination. In a communication network,
each device that is part of a network and can receive, create, store or send data to different
network routes is called a node. In the context of data communication, a node can be a device
such as a modem, hub, bridge, switch, router, digital telephone handset, printer, a computer
or a server.

Ans 18. HTTPs (Hypertext Transfer Protocol-secure): HTTPs stands for Hyper Text Transfer
Protocol Secure. It is a protocol for securing the communication between two systems
e.g., the browser and the web server. HTTP transfers data between the browser and
the web server in the hypertext format, whereas HTTPS transfers data in the encrypted
format. Thus, HTTPs prevents hackers from reading and modifying the data during the
transfer between the browser and the web server. Even if hackers manage to intercept
the communication, they will not be able to use it because the message is encrypted.

Ans 19. Ethernet: Ethernet is a LAN architecture developed by Xerox Corp. along with DEC and Intel.
It uses a bus or star topology and supports data transfer rates of up to 10 Mbps.

Ethernet card: It is a hardware device that helps in the connection of nodes within a network. An
Ethernet card is also known as a network card, network adapter or NIC (network interface
card). It is a card that allows computers to communicate over a computer network. On
Ethernet card, a physical address of each communicating computer is mentioned which is
known as MAC address.
Ans 20. Hub: It is a multi-port and unintelligent network device which simply transfers
data from one port of the network to another. A hub is a hardware device used to connect
several computers together with different ports. When the packet reaches one port, it is
copied to all other ports of the hub without changing the destination address in the frame.
Rather,it simply copies the data to all of the nodes connected to the hub. Hubs can be either
active or passive. Hubs can usually support 8, 12 or 24 RJ-45 ports.

Hub

Active Hub: It amplifies the signal as it is transferred from one node to another.
Passive Hub: It allows signals to pass from one node to another without any change.
Ans 21. A server is a powerful computer with all applications and hardware installed in it and
a client is a computer which seeks any resource from another computer. When clients need
access to these resources, they access them from the server.
Ans 22. Fibre Optical cable is very effective as it provides less error rate and very fast
communication in a guided medium.

Ans 23. Fibre Optical cable can be used in a harsh industrial environment.

Ans 24. Unguided media – Satellite

Ans 25.

• Microwave: It is a line-of-sight transmission as the signal travels in a straight line. In


microwave communication, two-directional parabolic antennas are mounted on towers,
buildings or hills to send and receive signals through the air. However, they must be
properly aligned with each other, otherwise the signal will not be focused well at the
receiving antenna. Microwaves have wavelengths of 1 mm (millimetre) to 1m and the
frequency at 1 mm is 300GHz.
• Radio wave: Radio waves use radio frequencies which are allocated to private businesses for
direct voice communication. A radio set-up uses a transmitter and receiver. A transmitter
sends radio waves and encodes them into sine waves which, when received by a receiver,
are decoded and the message is received. Both the transmitter and receiver use antennas to
radiate and fetch radio signals. They are not line-of-sight transmission and, hence, can
penetrate buildings easily. Radio waves have wavelengths of 1 m and the frequency at 1 m is
300 MHz.
Ans 26. Satellite is useful for sparsely populated areas as the transmission medium.

Ans 27. Bus topology is easy to expand by joining cables together.

Ans 28. Gateway

Ans 29. A collection of interconnected computers is called a Computer Network. Two computers or
devices are said to be interconnected if they are capable of sharing and exchanging information by
following a protocol. Networks have several advantages such as:

• Resource Sharing: The primary use of a network is to share among user programs/
applications, data and peripheral devices connected to the network, irrespective of their
physical location.
• Improved Communication: A computer network enables fast, reliable and secure
communication between users. It saves time and offers easy communication
methods.
• Reduced Communication Cost: Sharing resources also reduces communication cost.
Using public networks, we can send a large quantity of data at a low cost.
• Reliability of Data: Reliability means backing up of data, i.e., data can be copied and
stored on multiple computers. In a network system, all computers are connected to each
other. Thus, the information or message, which is shared by each device, is stored on
their respective workstations (computers).
• Central Storage of Data: W ith centralized processing, data is stored and retrieved
from a single central location. Thus, there is no duplication of data and almost no data
redundancy.
Ans 30.

(a) Advantages of Optical Fibres:


(i) Fibre optic cable typically offers better bandwidth and can carry more information at
once.
(ii) As the signal travels in the form of light, there is less attenuation and signal
degradation.
(iii) Optical fibre wires are made of glass, so there is little risk of fire because of an absence
of spark hazards.
(iv) A signal can run for 50 km without requiring regeneration.

Disadvantages of Optical Fibres:

i) Highly skilled labour is required for its installation and maintenance.


ii) It is relatively expensive as compared to other guided media.
iii) As fibre optic is made of glass; it can be easily broken.
iv) As light travels in a straight line, two fibres are needed if we need
bidirectional communication.

(b) Advantages of Coaxial Cables:


(i) Coaxial cable can support greater cable lengths between network devices than
twisted pair cable.
ii) It is useful for transmitting analog as well as digital data across the network.
iii) It is widely used for cable television and internet connections.
iv) Coax are used for transmitting several channels simultaneously, i.e., they are
helpful in broadband transmission.
v) Coaxial cable has excellent noise immunity because of thick covering outside the
insulated wires.
Disadvantages of Coaxial Cables:
(i) A thick coaxial cable does not bend easily and thus is difficult to install.
(ii) It is expensive as compared to twisted pair cable.

(c) Advantages of Twisted Pair Cables:


(i) It is simple to use.
(ii) It is inexpensive and does not require skilled personnel.
(iii) It is less susceptible to electrical interference caused by nearby equipment or
wires in a telephone system.

Disadvantages of Twisted Pair Cables:

i) STP wire is physically larger and more expensive than Unshielded twisted-pair wire.
ii) STP is more difficult to connect to a terminating block.
iii) It easily picks up noise signals which result in higher error rates when the line
length exceeds 100 metres.
(d) Advantages of Radio Waves:
(i) They can be used indoors a s w e l l a s outdoors.
(ii) They are omnidirectional and can travel in any direction.
(iii) Transmitter and receiver antenna do not need to be physically aligned.

Disadvantages of Radio Waves:

(i) Radio wave communication is an insecure mode of communication.


(ii)
Radio wave propagation is susceptible to weather effects like rain,
thunderstorm, etc.
(e) Advantages of Microwaves:
(i) It is a cheaper source of communication as it avoids using cables and
maintaining repeaters.
(ii) Communication through microwave is much easier over difficult terrain.
Disadvantages of Microwaves:

(i) It is an insecure mode of communication.


(ii) Microwave propagation is affected by weather conditions such as rain,
thunderstorm, etc.
(iii) The cost of implementing towers, antennas is relatively high.

(f) Advantages of Satellites:


i) The area covered is quite large.
Computer Networks

ii) No line-of-sight restrictions such as natural mountains, tall buildings, towers,


etc.
Disadvantages of Satellites:
(i) It is very expensive as compared to other transmission mediums.
(ii) Installation is extremely complex.
(iii) Signals sent to the stations can be interrupted by external interference.
Ans 31. HTTP is used to transfer all files and other data (collectively called resources) from
one computer to another on the World Wide Web. This protocol is used to transfer
hypertext documents over the internet. HTTP defines how the data is formatted and
transmitted over the network. Whenan HTTP client (a browser) sends a request to an HTTP
server (web server), the server sends responses back to the client. This transfer of requests
and responses is done by following HTTP protocol.
The main features of an HTTP document are:
1. It is a stateless protocol; this means that several commands are executed
simultaneouslywithout knowing the command which is already executing before
another command.
2. It is an object-oriented protocol that uses client-server model.
3. The browser (client) sends a request to the server, the server processes it and sends
responses to the client.
4. It is used for displaying web pages on the screen.
Ans 32. Hub: It is multi-port and unintelligent network device which simply transfers
data fromone port of the network to another. A hub is a hardware device used to connect
several computers together with different ports. When the packet reaches one port, it
is copied toall other ports of the hub without changing the destination address in the
frame. Rather,it simply copies the data to all of the nodes connected to the hub. it is
not an intelligent device. It shares bandwidth withall the attached devices and broadcasts
the data, i.e., sends data frames to all connected nodes as it does not remember
devices/computers connected to it. Also, it cannot filter the data and cause unnecessary
traffic jams.
Switch: A switch (switching hub) is a network device which is used to interconnect computers or
devices on a network. It filters and forwards data packets only to one or more devices for which
the packet is intended across a network. It is also a multi-port device but with some intelligence
and so the data packets received from one port of the network are refreshed and delivered to
the other port of the network. The main difference between hub and switch is that hub
replicates what it receives on one port on to all the other ports while switch keeps a record of
the MAC addresses of the devices attached to it.

Ans 33. Difference between Circuit and Packet Switching:


1. The circuit switching reserves the required bandwidth in advance whereas packet
switching uses bandwidth as and when required by the packets to be transmitted.
2. Circuit switching is a fast technology as compared to packet switching which is a slow
mechanism of transferring packets from sender to receiver.
3. Circuit switching requires a dedicated path. Once the connection is established, the
communication path is entirely dedicated to it until the data is completely
transferredfrom sender to receiver, whereas in packet switching, packets can use
any dynamic path.
4. In circuit switching, if the path is overloaded, the call is blocked and communication is
delayed. But in packet switching, packets are allocated to different paths.
5. Circuit-switched networks are used for phone calls and packet-switched networks
handle data.
6. Packet switching is more efficient because the cost of the link is shared by many
users.
7. In circuit switching, the telephone message is sent unbroken. The message is
received inthe same order as it is originally sent. In packet switching, the message
is broken intosmall packets which are randomly sent from source and received in
random order at destination, which is then sequentially arranged.

Ans 34. A switch (switching hub) is a network device which is used to interconnect computers or
devices on a network. It filters and forwards data packets only to one or more devices for which
the packet is intended across a network. It is also a multi-port device but with some intelligence
and so the data packets received from one port of network are refreshed and delivered to the
other port of the network. The main difference between hub and switch is that hub replicates
what it receives on one port onto all the other ports, while switch keepsa record of the MAC
addresses of the devices attached to it.

Role of Switch in Networking

Ans 35. MAC address: The MAC address, also known as the physical or hardware address, is a
unique permanent value associated with a network adapter called a NIC. It is used to physically
identify a machine on the network. It cannot be used to track the tentative location of the
machine. Example of MAC address is: 1E:B5:07:64:2E:AC.
IP address: IP address is also known as Internet Protocol address. It is a unique address that can
be used to uniquely identify each node in a network. It can be used to track the tentative
location of the machine on the internet. Unlike MAC address, IP address can change if a node is
removed from one network and connected to another network.

Ans 36.

(a) HTTP: HTTP is used to transfer all files and other data (collectively called resources) from one
computerto another on the World Wide Web. This protocol is used to transfer hypertext
documents over the internet. HTTP defines how the data is formatted and transmitted
over the network. Whenan HTTP client (a browser) sends a request to an HTTP server (web
server), the server sends responses back to the client. This transfer of requests and responses
is done following HTTP protocol.
(b) TCP/IP: The most common one is the Transmission Control Protocol/Internet Protocol or
TCP/IP. A network using TCP/IP is known as a TCP/IP network. The internet is an example of
the TCP/IP network. Therefore, it becomes important that each device should have a unique
address to identify it on a TCP/IP network. This unique address is known as IP address. IP
address is short for Internet Protocol (IP) address. An IP address is an identifier for a
computer or device on a TCP/IP network. Networks using the TCP/IP protocol route
messages based on the IP address of the destination. The format of IP address is a 32-bit
numeric address written as four numbers separated by periods. Each number can be
in therange of 0 to 255. Some examples of IP addresses are: 192.168.1.2, 10.24.1.3 and
109.134.2.2. The IP address of a computer is assigned by the Internet Service Provider
(ISP) whose internet connection is used on that computer.
(c) FTP: File Transfer Protocol
FTP is the simplest and most secure way to exchange files over the internet. The
main objectives of FTP are:
• Transmitting and sharing of files (computer programs and/or data).
• Indirect or implicit use of remote computers.
• To shield a user from variations in file storage systems among different hosts.
• To transfer data reliably and efficiently.
• FTP uses the internet’s TCP/IP protocols to enable data transfer.
FTP is most commonly used to download a file from a server using the internet
or to upload a file to a server (e.g., uploading a web page file to a server).
Ans 37. Wireless computing or communication: Wireless communication is simply data
communication without the use of landlines while Mobile computing means that the computing
device is not continuously connected to the base or central network.

Ans 38. We would prefer--

(i) hubs over repeaters when the distance is less.


(ii) Bridges over hubs when we have to connect multiple networks.
(iii) Switches over other networking devices when we want to segment into
multiple sub-networks to prevent traffic overloading.
Ans 39. The World Wide Web is based upon client-server architecture where a client sends
a request and the server processes that request and sends responses. A WWW client is
called a web browser and a WWW server is called a web server. Google Chrome and
Microsoft Edge are two popular web browsers.
Ans 40. SMTP: Simple Mail Transfer Protocol
TEACHER’S MANUAL

COMPUTER SCIENCE- XII

CH.-8: RELATIONAL DATABASE AND SQL

Ans 1. A candidate key that is not the primary key is called an alternate key. In other words, any
attribute that is a candidate for the primary key, i.e., which is capable of becoming a
primary key but is not a primary key, is an alternate key.

Ans 2. In SQL, a view is a virtual table based on the result-set of an SQL statement. A view contains
rows and columns, just like a real table. The fields in a view are fields from one or more real tables in
the database. Views are a great way to define a table without using extra storage and also help in
accelerating data analysis and can provide the data extra security.

Ans 3.

(a) Relation: In RDBMS, a table is called a relation that consists of rows and columns.
(b) Tuple: Rows of a table are known as a tuple in RDBMS.
(c) Attribute: Columns of a table are called attributes in RDBMS.
(d) Domain: It defines the kind of data represented by the attribute. It is the set of all
possible values that an attribute may contain.
Ans 4. Candidate Key: A candidate key refers to all the attributes in a relation that are
candidates or are capable of becoming a primary key.

Alternate Key: A candidate key that is not the primary key is called an alternate
key. In other words, any attribute that is a candidate for the primary key, i.e.,
which is capableof becoming a primary key but is not a primary key, is an
alternate key.
Candidate Keys – Primary Key = Alternate Key
Ans 5. SQL (Structured Query Language) is a standard language for accessing and manipulating
databases. SQL commands are used to create, transform and retrieve information from Relational
Database Management Systems and are also usedto create an interface between a user and
database. The different categories of commands available in SQL are:
(i) Data Definition Language (DDL)
(ii) Data Manipulation Language (DML)
(iii) Data Query Language (DQL)
(iv) Data Control Language (DCL)
(v) Transaction Control Language (TCL)
Ans 6. A database is defined as an organized collection of data (information) about an
entity (something that exists) or things. It is a shared collection of related
data/information used to support the activities and decision-making of a particular
organization. It also allows the users to enter, access and analyze their data quickly and
easily. It serves as a container which may contain various database objects. Database is
integrated as well as shared. For example, all files belonging toan organization will
be treated as the database of that organization. A database, therefore, isconsidered as a
repository of stored data.
Ans 7. DDL: The DDL part of SQL permits database tables to be created or deleted. It also
defines indices (keys), specifies links between tables and imposes constraints on tables.
It contains necessary statements for creating, manipulating, altering and deleting the
table.
Ans 8.
(a) Database
(b) Metadata
(c) Primary Key
(d) NULL
(e) Candidate Key
(f) MySQL
Ans 9.
(a) In EMPLOYEE table, Candidates Keys can be: AadhaarNumber, EmployeeID
(b) To retrieve details of dependents, DEPENDENT table will be used and the key which
is required to access records is EmployeeID, which will serve as a Foreign Key.
(c) Degree of EMPLOYEE table is 5 and the degree of DEPENDENT table is 3.
Ans 10. Data types are used to identify the type of data a column can hold. Some of the data
types in SQL are Integer, Char, Varchar, Decimal, Date, etc.
Ans11.

Ans 12. Concat() function is used to join two strings in a query result.
Ans13. Select 13 *15;
Ans14. DISTINCT
Ans15. The GROUP BY clause is used in a SELECT statement to collect data across
multiple records and group the results by one or more columns. It groups the rows on the
basis of the values present in one of the columns and then the aggregate functions are
applied on any column of these groups to obtain the result of the query.
Ans16. WHERE clause works in respect to the whole table but HAVING clause works
on Group only. If WHERE and HAVING both are used, then WHERE will be executed
first. Where is used toput a condition on individual row of a table whereas HAVING is
used to put a condition on an individual group formed by GROUP BY clause in a SELECT
statement.
Ans17.
(i) SELECT * FROM PRODUCT WHERE Prod_id >100;
(ii) SELECT * FROM PRODUCT WHERE Prod_Name=’Almirah’;
(iii) SELECT * FROM PRODUCT WHERE PRICE BETWEEN 200 AND 500;
(iv) SELECT Prod_Name FROM PRODUCT WHERE PRICE< AVG(PRICE);
(v) SELECT COUNT(*) FROM PRODUCT;

Ans 18.
(i) Database: A database is defined as an organized collection of data
(information) about an entity (something that exists) or things. It is a shared
collection of related data/information used to support the activities and
decision-making of a particular organization. It also allows the users to enter,
access and analyze their data quickly and easily.
(ii) Data inconsistency: Data inconsistency is a situation where there are
multiple tables within a database that deal with the same data but may
receive it from different inputs. Inconsistency is generally compounded by
data redundancy.
(iii) Primary Key: A primary key is a set of one or more attributes/fields which
uniquely identifies a tuple/row in a table. The salient features of a primary
key are as follows:
(a) It is always unique in nature, i.e., non-redundant. It does not have duplicate
values in a relation.
(b) It arranges the table in its own order.
(c) It cannot be re-declared or left null.
(d) One table can have only one primary key; however, primary key can be a
combination of more than one field.
(iv) Candidate Key: A candidate key refers to all the attributes in a relation that
are candidates or are capable of becoming a primary key.
(v) Foreign Key: A foreign key is a non-key attribute whose value is derived from
the primary key of another table; in other words, a primary key in some other
table having relationship with the current or original table.
Ans 19.
(i) SELECT MIN(SAL), MAX(SAL), AVG(SAL) From EMP
a. WHERE Designation = ‘MANAGER’;
(ii) SELECT COUNT(*) FROM EMP WHERE Designation = ‘CLERK’;
(iii) SELECT EmpName, Sal, DOJ FROM Emp GROUP BY Designation;
(iv) SELECT COUNT(*) FROM Emp WHERE Comm IS NULL;
(v) SELECT AVG(Sal) FROM EMP WHERE COUNT(Designation)>5;
(vi) SELECT * FROM DEPT Group By DeptID;
(vii) SELECT MAX(Salary) FROM EMP GROUP By DeptID;
(viii) SELECT EmpName, designation, DeptName FROM EMP NATURAL
JOIN DeptID;
(ix) SELECT COUNT(*) FROM EMP GROUP BY DEPTID=30;

Ans 20.
(i) SELECT Name FROM STUDENT WHERE Stream=’Science’;
(ii) SELECT count(*) FROM STUDENT WHERE Stream = ‘Commerce’;
(iii) SELECT count(*) FROM TEACHER WHERE GROUP BY Designation;
(iv) SELECT MAX(Pay) FROM TEACHER WHERE Subject = ‘English’;
(v) SELECT COUNT(*) FROM STUDENT WHERE Stream = ‘Commerce’;

Ans 21.
(i) Select * from Store order by LastBuy;
(ii) Select ItemNo, Item from Store Where Rate > 15;
(iii) Select * from Store where Scode = 22 and Qty > 110;
(iv) Select MIN(Rate) from Store Group by Scode;

(v)

COUNT(Distinct Scode)

(vi)

Rate*Qty

880

(vii)

Item Sname

Gel Pen Classic Premium Stationery

(viii)

MAX(LastBuy)

2020-02-02

Ans 22.

(i) Select * from BOOKS where Author_name = “P.Purohit” and


Publishers = “FIRST PUBL”;
(ii) Select Price from BOOKS where Publishers = “FIRST PUBL”;
(iii) Select Price – (Price * 0.05) from BOOKS;
(iv) Select Book_name, Price from BOOKS, ISSUED where
Books.Book_ID= ISSUED.Book_ID and Qty_Issued > 3;
(v) Select SUM(Price) from BOOKS Group by Type;
(vi) Select * from BOOKS having Price = MAX(Price);

Ans 23.
(i) Select * from PRODUCTS where STOCK > 110;
(ii) Select COMPANY from PRODUCTS where WARRANTY > 2;
(iii) Select STOCK + PRICE as ‘Stock’ from PRODUCTS where
COMPANY = “BPL”;
(iv) Select COUNT(PNAME) from PRODUCTS Group by COMPANY;
(v) Select Count(PName) from PRODUCTS where (‘2020/09/20’
– Manufacture )/365 >WARRANTY;
(vi) Select PNAME from PRODUCTS where (sysdate- MANUFACTURE
>= “2020/09/20”;
(vii) (a)

COUNT(distinct
company)
4

(b)

MAX(Price)

39000

Ans 24. DDL is the acronym for the Data Definition Language. DML is the acronym for
Data Manipulation Language. DDL is used to create database schema and also define
constraints as well. DML is used to delete, update and update data in the database.
Ans 25. A primary key is a set of one or more columns that uniquely identify a row
in a table and a candidate key refers to all the attributes in a relation that are capable
of becoming a primary key. A relation can only have one primary key while multiple
candidate keys (two or more) can take place in a table.
Ans 26. Cardinality is defined as the number of rows in a table while a degree is the
number of columns in a table.
Ans 27. Data Definition Language (DDL) allows us to define, modify and delete database
structure or schema while Data Manipulation language (DML command) allows us to
manage the data stored in the database, for example, inserting new data, removal of
existing data or modification of existing data.
Examples of DDL commands are CREATE TABLE, DROP TABLE, ALTER TABLE, etc.
Examples of DML commands are UPDATE, INSERT, DELETE, etc.
Ans 28.
(i) Select * from SchoolBus order by Rtno
where Capacity > Noofstudents;
(ii) Select Area_cover from SchoolBus where Distance > 20 AND
Charges < 80000;
(iii) Select Transporter, Noofstudents from SchoolBus group by
Transporter;
(iv) Select Rtno , Area_Covered , Charges / Noofstudents as
‘Average Cost’ from SchoolBus;
(v) Insert into SchoolBus values (11, "Motibagh", 35, 32, 10,
"kisan tours", 35000);
(vi)
(a)
SUM(Distance)

50

(b)

MIN(Noofstudents
40

(c)

AVG(Charges)

83000.0

(d)

DISTINCT(Transporter)

Shivam travels

Anand travels

Bhalla travels

Yadav travels

Speed travels

Kisan Tours

Ans 29.
(i) Select * from FURNITURE where PRICE > 10000;
(ii) Select ITEM, Price from FURNITURE where DISCOUNT
BETWEEN 10 and 20;
(iii) Delete from FURNITURE where DISCOUNT = 30;
(iv) Select PRICE from FURNITURE where TYPE = “BabyCot”;
(v) Select ITEM, TYPE, PRICE from FURNITURE where ITEM
like “D%” ;
(vi)

TYPE

DoubleBed

BabyCot

OfficeTable

(vii)

Max(Price)

9500

(viii)

Count(*)
3

Ans 30.
(i) Select NAME from GRADUATE order by NAME where RANK=1;
(ii) Select NAME from GRADUATE where AVERAGE > 65;
(iii) Select NAME from GRADUATE where SUBJECT = “COMPUTER”
AND AVERAGE > 60;
(iv) Select NAME from GRADUATE order by NAME;

(v)

SNO NAME STIPEND SUBJECT AVERAGE RANK


4 DIVYA 350 CHEMISTRY 63 1
8 LIZA 450 COMPUTER 68 1
10 NISHA 300 COMPUTER 57 2

(vi)
DISTINCT(RANK)

Ans 31. Candidate Key: A candidate key refers to all the attributes in a relation that are
candidates or are capable of becoming a primary key.
Alternate Key: A candidate key that is not the primary key is called an alternate key. In
other words, any attribute that is a candidate for the primary key, i.e., which is
capable of becoming a primary key but is not a primary key, is an alternate key.
Alternate Key = Candidate Keys – Primary Key
Ans 32.
(i) Select ProductName, Price from PRODUCT where Price between
50 and 150 ;

(ii) Select * from PRODUCT where Manufacture in(“XYZ”, “ABC”) ;


Or
Select * from PRODUCT where Manufacture=“XYZ” or Manufacture=
“ABC”;

(iii) Select ProductName, Manufacture, Price from PRODUCT where


Discount IS NULL ;

(iv) Select ProductName, Price from PRODUCT where ProductName


like “%h”;

(v) Select ClientName, City, P_ID, ProductName From Client


Where City = “Delhi” ;
(vi) P_ID column can be used as a Foreign key in CLIENT table.

Ans 33.

(a) Select Name from HOSPITAL where Dateofadm > “1998/01/15” ;


(b) Select Name from HOSPITAL where
Department=“ENT” and Sex = “F” ;
(c) Select Name, Dateofadm from HOSPITAL order by Dateofadm ;
(d) Select Name, Charges, Age from HOSPITAL where Sex = “F” ;

(e) (i)
Charges

300

250

200

800

400

(ii)

MIN(Age)

16

Ans 34.
(a) ItemNo
(b) Degree = 4 Cardinality = 7
(c) INSERT INTO STORE VALUES(2010, “Note Book”, 25);
(d) DROP TABLE STORE;
(e) Describe STORE;

Ans 35.
Primary Key: 1. Primary key uniquely identifies a record in the table.

2. Primary Key can't accept null values.

3. We can have only one Primary key in a table.

Unique Key:

1. Unique key also identifies uniquely a record in the table.


2. It can accept multiple null values once.
3. We can have more than one unique key in a table.
TEACHER’S MANUAL

COMPUTER SCIENCE- XII

CH.-9: INTERFACE PYTHON WITH SQL

Ans 1.

A. fetchone(): It fetches the next row of a query result set. A result set is an object that is returned
when a cursor object is used to query a table.
B. rowcount: This is a read-only attribute and returns the number of rows that were affected by
an execute() method.
C. fetchall(): It fetches all the rows in a result set and returns a list of tuples. If some rows
have already been extracted from the result set, then it retrieves the remaining rows from the
result set. If no more rows are available, it returns an empty list.
For example:
import mysql.connector as mycon
mydb = mycon.connect(host="localhost",user="root",password="", database =
"Emp")
cur = mydb.cursor()
qry= "select * from Employee order by salary "
cur.execute(qry)
#fetchone() function
data = cur.fetchone()
print(data)

# rowcount attribute
cur.rowcount()

#fetchall() function
data = cur.fetchall()
for i in data :
print(i)
mydb.close()

Ans 2. Connecting Python with MySQL facilitates us to access data from multiple working environments
through the same connection to the database. For database programming, the Python DB-API is a widely-
used module that provides a Database Application Programming Interface. It is a standard for database
interfaces. These APIs are implemented by calling functions in the programs which provide linkage to the
required program to perform a task.

Ans 3.

Ans 4. The basic steps to connect Python script with MySQL are:
1. Open the Python script and import any one package for database connectivity: MySQLdb or
mysql-connector.
2. Create a connection to database using connect() method and provide parameters such as
host, user, password and database name.
3. Create a cursor object.
4. Execute MySQL query.
5. Retrieve data from the resultset variable and display using print() command.
6. Close the connection environment.

Ans 5. (i) commit(): MySQLConnection.commit() method sends a COMMIT statement to the MySQL server,
committing the current transaction.

(ii) rollback: MySQLConnection.rollback reverts the changes made by the current transaction.

(iii) autocommit: MySQLConnection.Autocommit value can be assigned as True or False to enable or disable
the auto-commit feature of MySQL. By default, its value is False.

Ans 6. The role of execute() function is that it allows the execution of MySQL queries such as Create,
Insert, Delete, Select, etc., along with Python interface.
.

Ans 7. commit(): MySQLConnection.commit() method sends a COMMIT statement to the MySQL server,
committing (save any changes) in the current transaction. These changes then remain permanent.

rollback: MySQLConnection.rollback reverts the changes (undo all changes) made by the current
transaction.

Ans 8. The connect() function is used to connect or establish a connection with MySQL database using Python
script.

Ans 9. The execute() method is used for executing an sql query.

Ans10. Python DB API allows us to fetch only a single row. To fetch a single row from a result set we can
use cursor. fetchone().

Ans11.
import mysql.connector as a
mydb = a.connect(host="localhost",user="root",password="", database = "
Emp ")

cur = mydb.cursor()
qry = "select * from Employee order by salary "
cur . execute(qry)
data = cur.fetchall()
for i in data :
print(i)
mydb.close()

Ans 12.
import mysql.connector as a
db = a.connect(host="localhost",user="root",password="", database =
"Emp")
cursor = db.cursor()
cursor.execute("update Employee set salary = salary + 3000 where name =
'MANOJ KUMAR' ")
db.commit()
db.close()

Ans 13.
import mysql.connector as mycon
db = mycon.connect(host="localhost",user="root",password="", database =
"Emp")
cursor = db.cursor()
name = input("Enter Employee name = ")
cursor.execute("delete from Employee where name = { } ".format(name))
db.commit()
db.close()

Ans 14.
import mysql.connector as mycon
db = mycon.connect(host="localhost",user="root",password="", database =
"TESTDB")
cursor = db.cursor()
cursor.execute("Create table EMPLOYEE ( FIRST_NAME char(50), LAST_NAME
char(50), AGE integer, SEX char(1) , INCOME integer )")
db.commit()
db.close()

You might also like