CS 12 TM
CS 12 TM
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.
• 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 )
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 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
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
CH-2 FUNCTIONS
➢ Ans 1.
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 19.
def vol( l = 1, w = 1 , h = 1 ) :
return l * w * h
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)
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
Ans 23.
def g_c_d(a , b) :
if b == 0 :
return a
else :
return g_c_d (b, a % b)
Ans 24.
Ans 25.
Ans 26.
def prime(a):
for i in range (2,a) :
if a % i == 0 :
return "This is not prime number"
return "Prime number"
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 ")
Ans 28.
string = ("-").join(x)
print("Sequence After sorting :- ", string)
Ans 29.
Advantage:
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.
(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.
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
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:
return m * g * h
return (u * t) + (1 / 2 * a * t **2)
return (d / t)
3. On the Python shell import the module My_module by typing the statement:
import My_module
My_module.energy(10, 4,8)
My_module.distance(1000,12,60)
My_module.speed(5000,15)
Ans 3.
def vol(r):
def area(r):
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:
import <module_name>
(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.
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,
a = 144
print( math.sqrt(a) )
(ii)
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 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,
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 x * one_mille_in_km
def km_to_mile(x) :
return x / one_mille_in_km
def feet_to_inches( x ):
return x / one_feet_in_inche
def inches_to_feet(x) :
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
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
def pound_to_kg(z):
pk = z/kg_in_pound
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:
Ans 29.
newstr = “”
for ch in string:
if ch != char:
newstr+=ch
return newstr
print(deleteChar(string, char))
Ans 30.
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
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.
file=open(“C:\Myfiles\text1.dat”,’rb’)
file=open(“C:\Myfiles\text1.dat”,’wb’)
Ans 5. In the file modes ’rb’, ‘ab’, ‘a+b’ and ‘r+’, data will not be lost.
(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.
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.
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 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.
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.
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
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
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 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='')
(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
(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)
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 ")
(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
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()
Ans 23.
def isEmpty(Qu):
if Qu == []:
return True
else:
return False
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
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
(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
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.
Ans 11.
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.
(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 25.
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.
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.
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.
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 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
(viii)
MAX(LastBuy)
2020-02-02
Ans 22.
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)
(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 ;
Ans 33.
(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.
Unique Key:
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.
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()