083 - XII - CS - Question Bank 02
083 - XII - CS - Question Bank 02
CHAPTER 4 : RECURSION........................................................................................................ 55
2
HOTS BASED QUESTIONS ......................................................................................................................................... 55
RECURSION ANSWERS........................................................................................................................................ 56
3
Chapter 1 : PROGRAMMING WITH PYTHON
MCQ Questions ( 1 Marks )
4
10. Which of the following cannot be a variable?
(a) __init__ (b) in (c) it (d) on
22. What will be the output of the following Python code snippet? d = {"john":40, "peter":45}
(a) “john”, 40, 45, and “peter” (b) “john” and “peter”
5
(c) 40 and 45 (d) d = (40:”john”, 45:”peter”)
23. What will be the output of the following Python code snippet?
d = {"john":40, "peter":45}
"john" in d
(a) True (b) False (c) None (d) Error
24. What will be the output of the following Python code snippet?
d1 = {"john":40, "peter":45}
d2 = {"john":466, "peter":45}
d1 == d2
(a) True (b) False (c) None (d) Error
25. What will be the output of the following Python code snippet?
d1 = {"john":40, "peter":45}
d2 = {"john":466, "peter":45}
d1 > d2
(a) True (b) False (c) Error (d) None
6
31. What will be the output of the following Python code?
d = {"john":40, "peter":45}
d["john"]
(a) 40 (b) 45 (c) “john” (d) “peter”
34. Which of the following is not the correct syntax for creating a set?
(a) set([[1,2],[3,4]]) (b) set([1,2,2,3,4])
(c) set((1,2,3,4)) (d) {1,2,3,4}
7
40. If a={5,6,7}, what happens when a.add(5) is executed?
(a) a={5,5,6,7} (b) a={5,6,7}
(c) Error as there is no add function for set data type (d) Error as 5 already exists in the set
Answers to MCQs
1 A 6 A 11 B 16 D 21 D 26 B 31 A 36 41 C 46
2 D 7 D 12 C 17 A 22 B 27 B 32 A 37 B 42 47
3 D 8 A 13 C 18 D 23 A 28 C 33 D 38 B 43 48
4 B 9 B 14 A 19 B 24 B 29 C 34 A 39 D 44 49
5 A 10 B 15 A 20 D 25 C 30 C 35 C 40 B 45 50
Explanation:
1. : Case is always significant.
2. : Identifiers can be of any length.
3. : All the statements will execute successfully but at the cost of reduced readability.
4. : Variable names should not start with a number.
5. : As Python has no concept of private variables, leading underscores are used to indicate variables that
must not be accessed from outside the class.
6. : eval can be used as a variable.
7. : True, False and None are capitalized while the others are in lower case.
8. : Variable names can be of any length.
9. : Spaces are not allowed in variable names.
10. : in is a keyword.
11. : Neither of 0.1, 0.2 and 0.3 can be represented accurately in binary. The round off errors from 0.1 and
0.2 accumulate and hence there is a difference of
5.5511e-17 between (0.1 + 0.2) and 0.3.
12. : l (or L) stands for long.
13. : Infinity is a special case of floating point numbers. It can be obtained by float(‘inf’).
14. : ~x is equivalent to -(x+1).
15. : ~x is equivalent to -(x+1).
16. : Numbers starting with a 0 are octal numbers but 9 isn’t allowed in octal numbers.
17. : cmp(x, y) returns 1 if x > y, 0 if x == y and -1 if x < y.
18. : ‘+’ cannot be converted to a float.
8
19. : Python rounds off numbers away from 0 when the number to be rounded off is exactly halfway
through. round(0.5) is 1 and round(-0.5) is -1.
20. : ^ is the Binary XOR operator.
21. : Dictionaries are created by specifying keys and values.
22. : Dictionaries appear in the form of keys and values.
23. : In can be used to check if the key is int dictionary.
24. : If d2 was initialized as d2 = d1 the answer would be true.
25. : Arithmetic > operator cannot be used with dictionaries.
26. : Tuples are represented with round brackets.
27. : Values cannot be modified in the case of tuple, that is, tuple is immutable.
28. : Slicing in tuples takes place just as it does in strings.
29. : Slicing in tuples takes place just as it does in strings.
30. : Execute in the shell to verify.
31. : Execute in the shell to verify.
32. : * operator concatenates tuple.
33. : A set is a mutable data type with non-duplicate, unordered values, providing the usual mathematical
set operations.
34. : The argument given for the set must be an iterable.
35. : A set doesn’t have duplicate items
37. : { } creates a dictionary not a set. Only set() creates an empty set.
38. : a<b returns True if a is a proper subset of b.
39. : The members of a set can be accessed by their index values since the elements of the set are
unordered.
40. : There exists add method for set data type. However 5 isn’t added again as set consists of only non-
duplicate elements and 5 already exists in the set. Execute in python shell to verify.
1. Define Algorithm
Algorithm : It is a sequence of instructions designed in such a way that if the instructions are executed
in the specified sequence, the desired results will be obtained. The instructions in an algorithm should not
be repeated infinitely. The algorithm should be written in sequence.
9
3. What are the building block of algorithm?
The three building block of algorithm are :
Sequence
Selection
Iteration
5. Define Flowchart.
It is a pictorial representation of an algorithm. The flowchart uses different shape symbols to denote the
different appropriate instructions and these instructions can be written within the boxes using clear
statements.
10
11. Write any two disadvantages of flowchart ?
Ans : (i) It is not visual (ii) We do not get a picture of the design.
19. Write the type of tokens from the following: (i) if (ii) roll_no
20. Name the Python Library modules which need to be imported to invoke the following functions:
(i) sin() (ii) randint ()
Answer :- (i) math (ii) random
1. Rewrite the following code in python after removing all syntax error(s). Underline each correction done
in the code.
30=To
for K in range(0,To)
if k%4==0
print (K*4)
else
print (K+3)
12
def Change(P ,Q=30):
P=P+Q
Q=P-Q
print( P,"#",Q)
return (P)
R=150
S=100
R=Change(R,S)
print(R,"#",S)
S=Change(S)
3. What possible outputs(s) are expected to be displayed on screen at the time of execution of the
program from the following code? Also specify the maximum values that can be assigned to each of the
variables FROM and TO.
import random
AR=[20,30,40,50,60,70];
FROM=random.randint(1,3)
TO=random.randint(2,4)
for K in range(FROM,TO+1):
print (AR[K],end=”#“)
(i) 10#40#70# (ii) 30#40#50#
(iii) 50#60#70# (iv) 40#50#70#
13
7. Give the output from the given python code:
import matplotlib.pyplot as plt
import numpy as np
objects = ('Python', 'C++', 'Java', 'Perl', 'Scala', 'Lisp')
y_pos = np.arange(len(objects))
performance = [10,8,6,4,2,1]
plt.bar(y_pos, performance, align='center', alpha=0.5)
plt.xticks(y_pos, objects)
plt.ylabel('Usage')
plt.title('Programming language usage')
plt.show()
8. Find error in the following code(if any) and correct code by rewriting code and underline the correction;-
x= int(“Enter value of x:”)
for in range [0,10]:
if x=y
print( x+y)
else:
Print( x-y)
9. Rewrite the following program after finding and correcting syntactical errors and underlining it.
a,b = 0
if (a = b)
a +b = c
print( z)
10. Rewrite the following code in python after removing all syntax error(s). Underline each correction done
in the code.
250 = Number
WHILE Number<=1000:
if Number=>750
print (Number)
Number=Number+100
else
print( Number*2)
Number=Number+50
11. Rewrite the following code in python after removing all syntax error(s). Underline each correction done
in the code.
Val = int(rawinput("Value:"))
Adder = 0
for C in range(1,Val,3)
Adder+=C
if C%2=0:
Print (C*10)
14
else:
print (C*)
print (Adder)
12. Rewrite the following code in python after removing all syntax error(s). Underline each correction done
in the code.
25=Val
for I in the range(0,Val)
if I%2==0:
print( I+1)
Else:
print (I-1
13. Rewrite the following code in python after removing all syntax error(s). Underline each correction done
in the code.
STRING=""WELCOME
NOTE""
for S in range[0,8]:
print (STRING(S))
14. Rewrite the following code in python after removing all syntax error(s). Underline each correction done
in the code.
a=int{input("ENTER FIRST NUMBER")}
b=int(input("ENTER SECOND NUMBER"))
c=int(input("ENTER THIRD NUMBER"))
if a>b and a>c
print("A IS GREATER")
if b>a and b>c:
Print(" B IS GREATER")
if c>a and c>b:
print(C IS GREATER)
15. Rewrite the following code in python after removing all syntax error(s). Underline each correction done
in the code.
i==1
a=int(input("ENTER FIRST NUMBER"))
FOR i in range[1,11];
print(a,"*=",i,"=",a*i)
16. Rewrite the following code in python after removing all syntax error(s). Underline each correction done
in the code.
a=”1”
while a>=10:
print("Value of a=",a)
a=+1
15
17. Rewrite the following code in python after removing all syntax error(s). Underline each correction done
in the code.
Num=int(rawinput("Number:"))
sum=0
for i in range(10,Num,3)
Sum+=1
if i%2=0:
print(i*2)
Else:
print(i*3 print Sum)
18. Rewrite the following code in python after removing all syntax error(s). Underline each correction done
in the code.
weather='raining'
if weather='sunny':
print("wear sunblock")
elif weather='snow':
print("going skiing")
else:
print(weather)
19 Write the modules that will be required to be imported to execute the following code in Python.
def main( ):
for i in range (len(string)) ):
if string [i] = = ‘’ “
print
else:
c=string[i].upper()
print( “string is:”,c)
print (“String length=”,len(math.floor()))
20. Observe the following Python code very carefully and rewrite it after removing all syntactical errors with
each correction underlined.
DEF execmain():
x = input("Enter a number:")
if (abs(x)=x):
print ("You entered a positive number")
else:
x=*-1
print "Number made positive:"x
execmain()
21. Rewrite the following code in python after removing all syntax error(s). Underline each correction done
in the code
x=integer(input('Enter 1 or 10'))
if x==1:
16
for x in range(1,11)
Print(x)
Else:
for x in range(10,0,-1):
print(x)
22. Rewrite the following code in python after removing all syntax error(s). Underline each correction done
in the code.
30=To
for K in range(0,To) IF k%4==0:
print (K*4) Else:
print (K+3)
Answers
1. Underline and correct errors
To=30
for K in range(0,To) :
if k%4==0:
print (K*4)
else:
print (K+3) (1/2 mark for each correction)
2. Output: SCHOOLbbbbCOM
4. Output 35
15
7. Output
17
8. Underline and correct errors
x= int(input(“Enter value of x:”))
for in range (0,10):
if x==y:
print( x+y)
else:
print (x-y)
18
NOTE=" "
for S in range (0,7) :
print (STRING [S])
Also range(0,8) will give a runtime error as the index is out of range. It should
be range(0,7)
19
print("going skiing")
else:
print(weather)
19. Required Modules
Math module and String module
20
3. Find out the output of the Following –
x=20
x=x+5
x=x-10
print (x)
x,y=x-1,50
print (x,y)
6. Find output
x="one"
y="two"
c=0
while c<len(x):
print(x[c],y[c])
c=c+1
7. Find Output
for i in range(-1,7,2):
for j in range(3):
print(i,j)
8. Find Output
string=”aabbcc”
count=3
while True:
if string[0]=='a':
string=string[2:]
elif string[-1]=='b':
string=string[:2]
else:
count+=1
break
21
print(string)
print(count)
9. Find Output
x="hello world"
print(x[:2],x[:-2],x[-2:])
print(x[6],x[2:4])
print(x[2:-3],x[-4:-2])
10. Find and write the output of the following python code :
Msg1="WeLcOME"
Msg2="GUeSTs"
Msg3=""
for I in range(0,len(Msg2)+1):
if Msg1[I]>="A" and Msg1[I]<="M":
Msg3=Msg3+Msg1[I]
elif Msg1[I]>="N" and Msg1[I]<="Z":
Msg3=Msg3+Msg2[I]
else:
Msg3=Msg3+"*"
print Msg3
11. Find and write the output of the following python code :
def Changer(P,Q=10):
P=P/Q
Q=P%Q
print P,"#",Q
return P
A=200
B=20
A=Changer(A,B)
print A,"$",B
B=Changer(B)
print A,"$",B
A=Changer(A)
print A,"$",B
12. Find and write the output of the following python code: 2
Data = ["P",20,"R",10,"S",30]
Times = 0
Alpha = ""
Add = 0
for C in range(1,6,2):
Times= Times + C
Alpha= Alpha + Data[C-1]+"$"
Add = Add + Data[C]
print Times,Add,Alpha
22
13. Find and write the output of the following python code:
Text1="AISSCE 2018"
Text2=""
I=0
while I<len(Text1):
if Text1[I]>="0" and Text1[I]<="9":
Val = int(Text1[I])
Val = Val + 1
Text2=Text2 + str(Val)
elif Text1[I]>="A" and Text1[I] <="Z":
Text2=Text2 + (Text1[I+1])
else:
Text2=Text2 + "*"
I=I+1
print Text2
14. Find and write the output of the following python code:
TXT = ["20","50","30","40"]
CNT = 3
TOTAL = 0
for C in [7,5,4,6]:
T = TXT[CNT]
TOTAL = float (T) + C
print TOTAL
CNT-=1
21. Find and write the output of the following python code:
def fun(s):
k=len(s) m=" "
for i in range(0,k):
if(s[i].isupper()):
m=m+s[i].lower()
elif s[i].isalpha():
m=m+s[i].upper()
else:
m=m+'bb' print(m)
fun('school2@com')
24
print(R,"#",S)
S=Change(S)
23. Find output
x = "abcdef"
i = "a"
while i in x:
print(i, end = " ")
(b) t2=("sun","mon","tue","wed","thru","fri")
for i in range (-6,2):
print(t2[i])
(c) t3=("sun","mon","tue","wed","thru","fri")
if "sun" in t3:
for i in range (0,3):
print(t2[i])
else:
for i in range (3,6):
print(t2[i])
(d) t4=("sun","mon","tue","wed","thru","fri")
if "sun" not in t4:
for i in range (0,3):
print(t4[i])
else:
for i in range (3,6):
print(t4[i])
(e) t5=("sun",2,"tue",4,"thru",5)
if "sun" not in t4:
for i in range (0,3):
print(t5[i])
else:
for i in range (3,6):
print(t5[i])
(f) t6=('a','b')
t7=('p','q')
t8=t6+t7
print(t8*2)
25
(g) t9=('a','b')
t10=('p','q')
t11=t9+t10
print(len(t11*2))
(h) t12=('a','e','i','o','u')
p,q,r,s,t=t12
print("p= ",p)
print("s= ",s)
print("s + p", s + p)
(i) t13=(10,20,30,40,50,60,70,80)
t14=(90,100,110,120)
t15=t13+t14
print(t15[0:12:3])
(a) t1=(10,20,30,40,50,60,70,80)
t2=(90,100,110,120)
t3=t1*t2
Print(t5[0:12:3])
(b) t1=(10,20,30,40,50,60,70,80)
i=t1.len()
Print(T1,i)
(c) t1=(10,20,30,40,50,60,70,80)
t1[5]=55
t1.append(90)
print(t1,i)
(d) t1=(10,20,30,40,50,60,70,80)
t2=t1*2
t3=t2+4
print t2,t3
(e) t1=(10,20,30,40,50,60,70,80)
str=””
str=index(t1(40))
print(“index of tuple is ”, str)
str=t1.max()
print(“max item is “, str)
26
List Based Question
28. Find the error in following code. State the reason of the error.
(a) aLst = { ‘a’:1 ,’ b’:2, ‘c’:3 }
rint (aLst[‘a’,’b’])
27
31. What will be the output?
d1 ={"john":40, "peter":45}
d2 ={"john":466, "peter":45}
d1 > d2
(a) TRUE (b) FALSE (c) ERROR (d) NONE
33. Find the error in following code. State the reason of the error
aLst={‘a’:1,’b’:2,’c’:3}
print(aLst[‘a’,’b’])
28
sum = 0
for k in my_dict:
sum += my_dict[k]
print (sum)
(a) 7 (b) Syntax error (c) 3 (d) 6
(f) count =1
def dothis():
global count
for I in (1,2,3)
count+=1
dothis()
print count
30
(g) def addem(x,y,z):
print(x+y+z)
def prod(x,y,z):
return x*y*z
a=addem(6,16,26)
b=prod(2,3,6)
print(a,b)
(j) a=10
def call():
global a
a=15
b=20
print(a)
call()
42. Write definition of a method/function getNum(a,b) to display all odd numbers between a and b.
43. Write definition of a method/function AddOdd(VALUES) to display sum of odd values from the list
of VALUES.
44. Write definition of a Method MSEARCH(STATES) to display all the state names from a list of STATES,
which are starting with alphabet M.
For example:
If the list STATES contains
[“MP’,”UP”,”MH”,”DL”,”MZ”,”WB”]
31
["MELBORN","TOKYO","PINKCITY","BEIZING","SUNCITY"]
The following should get displayed :PINKCITY
47. Write a user defined function GenNum(a, b) to generate odd numbers between a and b (including b)
Output
1. Output : (60, -320)
2. Output : uter
‘ComputerComputer’
3. Output : 15
(14,50)
4. Output : 1
1 3 5
1 3 5 7
5. Output : NO OUTPUT
32
6. Output : ot
nw
eo
7. Output :
-1 0
-1 1
-1 2
10
11
12
30
31
32
50
51
52
8 Output : bbcc
4
9. Output : he hello wor ld
w ll
llo wo or
11. Output : 10 # 10
10 $ 20
2 # 2
10 $ 2
1 # 1
1 $ 2
12. Output :
1 20 P$
4 30 P$R$
9 60 P$R$S$
Outputs(Tuples)
24.(a) wed
24.(b) sun
mon
tue
wed
thru
fri
sun
mon
24.(c) sun
mon
tue
24(d). wed
thru
fri
24(e) 4
thru
5
34
24(f) ('a', 'b', 'p', 'q', 'a', 'b', 'p', 'q')
24(g) 8
24(h) p= a
s= o
s + p oa
24(i) 10,40,70,100
Error Tuples
25(c) (i) 'tuple' object does not support item assignment in line 2
(ii) Append() Method is not with tuple
26. [‘p’,’b’,’l’,’e’,’m’]
[‘p’,’b’]
27. 1
2
[13,18,11,16,13,18,13,3]
28(a) The above code will produce KeyError, the reason being that there is no key same as the list [‘a’,’b’]
28(b) list1 + list 2 = : [1998, 2002, 1997, 2000, 2014, 2016, 1996, 2009]
list1 * 2 = : [1998, 2002, 1997, 2000, 1998, 2002, 1997, 2000]
28(c) List1:[0,2,3,4,5]
35
29. (a) Explanation: [x for x in[data] returns a new list copying the values in the list data and the outer
for statement prints the newly created list 3 times.
30. (a)
33. The above code produce KeyError, the reason being that there is no key same as the list[‘a’,’b’] in
dictionary aLst
34. (b) 35. (a) 36. (b) 37. (d) 38. (b)
FUNCTIONS(Error)
40. Output: 20
39
32
57
41(b). Output : 25
41(c) Output : 25
41(f) Output : 4
41(g) Output : 48
(None, 36)
36
41(h) Output : python
Easyeasyaesy
41(i) Output : 33
32
53
41(j) Output : 15
42 def getNum(a,b):
for i in range(a,b+1):
if i%2==1:
print(i)
37
General Questions
48. a. len(str) b. str.capitalize() c. str.upper() d. ch.isalnum()
49. Default arguments are used in function definition, if the function is called without the argument, the
default argument gets its default value.
50. . Recursion is a way of programming or coding a problem, in which a function calls itself one or more times
in its body. Usually, it is returning the return value of this function call. If a function definition fulfils the
condition of recursion, we call this function a recursive function.
Example:
4! = 4 * 3!
3! = 3 * 2!
2! = 2 * 1
Def factorial(n):
If n ==1:
return 1
else:
return n*factorial(n-1)
51. Built in functions can be used directly in a program in python, but in order to use modules, we have to
use import statement to use them.
52.
SR.NO. LOCAL VARIABLE GLOBAL VARIABLE
1 It is a variable which is declared within a It is a variable which is declared
function or within a block. outside all the functions.
2 It is accessible only within a function/ It is accessible throughtout the
block in which it is declared. program.
For example,
def change():
n=10 # n is a local variable
x=5 # x is a global variable
print( x)
53. i) using the function is easier as we do not need to remember the order of the arguments.
ii) we can specify values of only those parameters which we want to give, as other parameters have
default argument values
54. Scope of variables refers to the part of the program where it is visible, i.e, the area where you can use it
55. The round() function is used to convert a fractional number into whole as the nearest next whereas the
floor() is used to convert to the nearest lower whole number. E.g. round(5.8) = 6 and floor(5.8)= 5
56. Actual parameters are those parameters which are used in function call statement and formal parameters
are those parameters which are used in function header (definition).
38
e.g. def sum(a,b): # a and b are formal parameters
returna+b
x,y=5,10
res=sum(x,y) # x and y are actual parameters
57. (i) 58. ( i) Keyword ii) identifier 59. i) iv) vi) viii) 60. ii) and iv)
39
CHAPTER 2: USING PYTHON LIBRARIES
Multiple Choice Questions
4. Which of the following is false about “import module name” form of import?
(a) The namespace of imported module becomes part of importing module.
(b) This form of input prevents name clash.
(c) The namespace of imported module becomes available to importing module.
(d) The identifiers in module are accessed as: module name. identifier
7. Which operator is used in the python to import all modules from packages?
(a) .(dot) operator (b) * operator (c) -> symbol (d) , operator
40
8. Which file must be part of the folder containing python module file to make it importable python
package?
(a) init.py (b) ____steup__.py (c) __init ___.py (d) setup.py
10. Which is the correct command to load just the tempc method from a module called usable?
(a) Import usable,tempc (b) Import tempc from usable
(c) From usable import tempc (d) Import tempc
Answers
1 b 2 d 3 b 4 a 5 b 6 c 7 b 8 c 9 b 10 c 11 d
Explaination:
Ans1 Design and implementation of specific functionality to be incorporated into a program
1. How can you locate environment variable for python to locate the module files imported into a
program?
(a) [2,4,6]
(b) [1,4,9]
(c) [2,4,6][1,4,9]
(d) There is a name clash
41
3. What happens when python encounters an import statement in a program? What would happen, if there
is one more important statement for the same module ,already imported in the same program?
Answers :
1. Pythonpath command is used for the same. It has a role similar to path.This variable tells the python
interpreter where to locate the module files imported into a program.It should include the python source
library ,directory containing python source code.
2. (d)
4. In the “from –import” from of import, the imported identifiers (in this case factorial ()) become part of
the current local namespace and hence their module’s name aren’t specified along with the module
name. Thus, the statement should be:
print (factorial (5))
42
5. There is a name clash. A name clash is a situation when two different entities with the same name become
part of the same scope. Since both the modules have the same function name ,there is a name clash,
which is an error.
1. Observe the following code and answer the question based on it.
# the math_operation module
deff add (a,b):
return a+b
def subtract(a,b):
return a-b
Fill in the blanks for the following code:
(a) Math _operation
#get the name of the module.
(b) print (_______)
#output:math_operation
# Add 1and 2
(c) print(_______(1,2) )
# output 3
2. Consider the code given in above and on the basis of it, complete the code given below:
# import the subtract function
#from the math_operation module
(a).________________________
#subtract 1from 2
(b). print(_______(2,1) )
# output : 1
# Import everything from math____operations
(c)._______________________________
print (subtract (2,1) )
# output:1
Print (add (1,1) )
# output:2
Answers
1. (a). input
(b). math_operation_name_
(c). math.operation.add
44
RELATIONSHIP BETWEEN A MODULE, PACKAGE AND LIBRARY IN PYTHON
A module is a file containing python definitions,variables and classes and statement with .py extension
A Python package is simply a directory of python modules
A library in python is collection of various packages. Conceptually there is no difference between package and
python Library.
Advantages of Python Modules
1)Putting code into modules is useful because of the ability to import the module functionality.
2)Reusability:A module can be used in some other python code. Hence it provide facility of code reusability
3)A module allows us to logically organize our python code.
4)Grouping related code into a module makes the code easier to understand and use.
5)Categorisation: Similar types of attributes can be placed in a single module.
Creation of Module : the following point must be noted before creating a module
A module name should always end with .py extension
We will not able to import module if it does not end with .py
A module name must not be a Python keyword
A module is simply a python file which contains functions,classes and variables
Let us consider the following example of a module name area.py which contains three functions name
area_circle(r),area_square(s),area_rect(l,b)
import math
def area_circle(r):
return math.pi*r*r
def area_square(s):
return s*s
def area_rect(l,b):
return l*b
45
2)Using from Statement :To import some particular Function(s) from module we will use import statement
2.1 To import Particular Function
Syntax:
From <module name> import <write name of Function(s)>
Or
From <module name> import *
(This statement will import all the functions from modules)
To use a function inside a module you have to directly call function if your are importing the modules using from
statement
Example : Let us consider the following code.In this program we import the module with the help of from
statement and directly use the function instead of specifying Module name
from area.py import area_rect
area_rect(5,4)
Alias name of Module :providing another name to module is known as alias name.When we provide an alias
name ,then alias name is used for calling function
Syntax:import modulename as <alias name>
example import area as A now we will call function area_circle using alias name A of module area like as
A.area_circle(5)
Note :we can also provide alias name to function of modules whenever we are using it with python from
statement and whenever we have to call any statement then we have to provide function alias name instead of
function original name ‘Example:
From area import area_Circle as C
C(6) # C is the alias name of function area_circle of module area
Current
the not found Each directory in shells not found Checks default path where
directory variable PYTHONPATH python is installed
46
CHAPTER 3 : FILE HANDLING
Very short Answer Questions : 1 Mark
5. How many file objects would you need to manage the following situations ?
(a) to process four files sequentially. (b) To process two sorted files into third file
6. When do you think text files should be preferred over binary files?
Answers
1. w mode opens a file for writing only. it overwrites if file already exist but 'a mode appends the existing
file from end. It does not overwrite the file.
2. binary file are easier and faster than text file.binary files are also used to store binary data such as
images, video files, audio files.
3. f1=open(“c:\school\sample.dat’,’r’)
4. (d) f.readlines()
5. (a) 4 (b) 3
6. Text file should be preferred when we have to save data in text format and security of file is not
important.
1. Write a single loop to display all the contents of a text file file1.txt after removing leading and trailing
WHITESPACES.
6. In which of the following file modes the existing data of the file will not be lost?
i) rb
ii) w
iii) a+b
iv) wb+
v)r+
vi)ab
vii) w+b
viii)wb
ix)w+
8. Suppose a file name test1.txt store alphabets in it then what is the output of the following code
f1=open("test1.txt")
size=len(f1.read())
print(f1.read(5))
48
Answers
3. The file would now contains “Bye”only because when an existing file is openend in write mode. it
truncates the existing data in file.
5. Line1
Line3
Line 6
Line 4
8. No Output
Explanation: the f1.read() of line 2 will read entire content of file and place the file pointer at the end of
file. for f1.read(5) it will return nothing as there are no bytes to be read from EOF and, thus, print statement
prints nothing.
1. Write a user defined function in python that displays the number of lines starting with 'H' in the file
para.txt.
2. Write a function countmy() in python to read the text file "DATA.TXT" and count the number of times "my"
occurs in the file. For example if the file DATA.TXT contains-"This is my website.I have diaplayed my
preference in the CHOICE section ".-the countmy() function should display the output as:"my occurs 2
times".
3. write a method in python to read lines from a text file DIARY.TXT and display those lines which start
with the alphabets P.
4. Write a method in python to read lines from a text file MYNOTES.TXT and display those lines which start
with alphabets 'K'
5. Write a program to display all the records in a file along with line/record number.
49
6. Consider a binary file employee.dat containing details such as empno:ename:salary(seperator ':') write a
python function to display details of those employees who are earning between 20000 and 30000(both values
inclusive)
7. Write a program that copies a text file "source.txt" onto "target.txt" barring the lines starting with @ sign.
8. Write a program in python to write and read structure, dictionary to the binary file.
Answer
Ans.1
def count H ():
f = open (“para.txt” , “r” )
lines =0
l=f. readlines ()
for i in L:
if i [0]== ‘H’:
lines +=1
print (“No. of lines are: “ , lines)
Ans.2
def countmy ():
f=open (“DATA.txt” ,”r”)
count=0
x= f.read()
word =x.split ()
for i in word:
if (i == “my”):
count =count + 1
print (“my occurs” ,count, “times”)
Ans.3
def display ():
file=open(‘DIARY.txt ‘ , ‘r’)
lines= file.readline()
while line:
if line[0]== ‘p’ :
print(line)
line=file.readline ()
file.close()
Ans.4
def display ():
file=open(MYNOTES.TXT’ , ‘r’)
lines=file.readlines()
while line:
if line[0]==’K’ :
print(line)
line=file.readline()
file.close()
50
Ans5.
f=open(“result.dat” , “r”)
count=0
rec=””
while True:
rec=f.readline (0)
if rec == “ “ :
break
count=count+1
print (count,rec)
f.close()
Ans.6
def Readfile():
i=open( “Employee.dat” , “rb+”)
x=i .readline()
while(x):
I= x.split(‘:’)
if ( (float (I[2]) >=20000) and (float I[2])<=40000):
print(x)
x= i.readline()
the above program saves a dictionary in binfile.dat and prints it on console after reading it from the file
binfile.dat
51
Notes on File Handling
A file in itself is a bunch of bytes stored on some storage device like hard disk, thumb drive etc.
TYPES OF FILE
TEXT FILE : A text file stores information in ASCII or unicode characters and each line of text is terminated,
(delimited) with a special character known as EOL
BINARY FILE : A binary file is just a file that contains information in the same format in which the information is
held in memory i.e the file content that is returned to you is raw. There is no delimiter for a line.
No translation occurs in binary file. Binary files are faster and easier for a program to read and
write than are text files. Binary files are the best way to store program information.
(i) The os module provides functions for working with files and directories ('os' stands for operating
system). os.getcwd returns the name of the current directory
import os
cwd=os.getcwd()
print(cwd)#cwd is current working directory
(ii) A string like cwd that identifies a file is called path. A relative path starts from the current
directory whereas an absolute path starts from the topmost directory in file system.
52
FILES MODE : it defines how the file will be accessed
54
Chapter 4 : Recursion
HOTS Based Questions
1. Which among the following function will be recursive function?
(a) def A() {
B()
(b) def A():
A()
(c) def B():
B()
(d) def B():
A()
(e) def recure():
resure()
2. Why the following function stops after some time.
def func1():
print(“ Hello func2”)
func2()
def func2():
print(“ yes func1”)
func1()
3. Recursion and Iteration are both similar things i.e. anything that we can do with a loop can be done by
recursion. If you, are a programmer which one will be used by you while making a program.
4. Write a recursive program in python to calculate pow(x,n).
5. Write a recursive program in python to print multiplication table of 12 using recursion.
6. Write a recursive function in python to return the sum of the given series.
7. Recursive function to find the sum of even elements from the array.
8. Program to calculate e^x by Recursion : ex = 1+x/1!+x2/2!+x3/3!+……..
9. Python program to calculate length of a string using recursion.
10. Write a function “perfect()” that determines if parameter number is a perfect number. Use this function
in a program that determines and prints all the perfect numbers between 1 and 1000.
[An integer number is said to be “perfect number” if its factors, including 1(but not the number itself), sum to the
number. E.g., 6 is a perfect number because 6=1+2+3].
11. What is tail recursion?
12. What is the complexity of Binary search?
13. What is the space complexity of the above recursive implementation to find the nth fibonacci number?
(a) O(1) (b) O(2*n) (c) O(n2) (d) O(2n)
14. Which of the following recursive formula can be used to find the factorial of a number?
(a) fact(n) = n * fact(n) (b) fact(n) = n * fact(n+1)
(c) fact(n) = n * fact(n-1) (d) fact(n) = n * fact(1)
15. What is the time complexity of the above recursive implementation to find the factorial of a number?
(a) O(1) (b) O(n) (c) O(n2) (d) O(n3)
16. Why is <__init__.py> module used in Python?
17. Write a Python program of recursion list sum.
55
RECURSION ANSWERS
1. (a) not a recursive function , as after def colon (:) is not present
(b) Yes, it is a recursive function.
(c) Yes, it a recursive function.
(d) No, it is not a recursive function, as they are two different function.
(e) No, it is not a recursive function, as they are two different function.
3. As a programmer I will prefer to use both recursion and iteration depending on the need,
As, iteration is used by a programmer for most recursive events, iteration does not involves the use of
additional cost of RAM as compared to using recursion.
Recursion is important as it makes the program shorter, and more simplified.
4. defpower(x, y):
if(y ==0):
return1
elif(int(y %2) ==0):
return(power(x, int(y /2)) * power(x, int(y /2)))
else:
return(x *power(x, int(y /2)) * power(x, int(y /2)))
x =2; y =3
print(power(x, y))
5. deftable(n,i):
printn*i
i=i+1
if i<=10:
table(n,i)
table(12,1)
6. defsum(n):
If n ==1:
return1
else:
# Recursive call
Return pow(n, n) +sum(n -1)
56
n =2
print(sum(n))
7. defcSumOfEven(arr, i, sum):
if(i < 0):
print(sum);
return;
if((arr[i]) %2==0):
sum+=(arr[i]);
SumOfEven(arr, i -1, sum);
if__name__ =='__main__':
arr =[ 1, 2, 3, 4, 5, 6, 7, 8];
n =len(arr);
sum=0;
SumOfEven(arr, n -1, sum);
8. p =1.0
f =1.0
defe(x, n) :
globalp, f
if(n ==0) :
return1
r =e(x, n -1)
p =p *x
f =f *n
return(r +p /f)
x =4
n =15
print(e(x, n))
9. str="GeeksforGeeks"
defrecLen(i) :
globalstr
if(i ==len(str)) :
return0
else:
return1+recLen(i +1)
print(recLen(0))
57
10. def perfect(n):
sum=0
for I in range(1,n):
if n%i==0:
sum=sum+i
if sum==n:
return True
else:
return False
for I in range(1,1001):
if perfect(i):
print i
11. A function where the recursive call is the last thing executed by the function.
return total
print( recursive_list_sum([1, 2, [3,4],[5,6]]))
58
CHAPTER 5 : Idea of Algorithmic Efficiency
1. What is Algorithm?
2. What are the factors on which performance of a program depends?
3. What are the Internal and External factors?
4. What is Computational Complexity?
5. Write a program to Calculate sum of n natural numbers with time taken.
6. What is the time complexity of following algorithms?
(i). Binary Search (ii). linear Search
6.
def LSearch(List,x):
for i in List:
if i==x:
return True
return False
List=[10,20,30,40,50,60]
59
print(LSearch(List,30))
print(LSearch(List,35))
print(LSearch(List,40))
Binary Search
def binsearch(ar,key,low,high):
if low>high:
return -999 #Base Case
mid=int((low+high)/2)
if key==ar[mid]:
return mid #Base Case
elif key<ar[mid]:
high=mid-1
return binsearch(ar,key,low,high)
else:
low=mid+1
return binsearch(ar,key,low,high)
ary=[13,15,17,19,21,23,34,36,45]
item=int(input("Enter no. to search:"))
res=binsearch(ary,item,0,len(ary)-1)
if res>=0:
print(item,"Found at index",res)
else:
print("Number not found”)
If we see both algorithms then we come to know that binary search is better because the number of operations
in this algorithm are very less. It searches item very fast and in very less operations.
60
Chapter 6 : Data Visualization Using Pyplot
9. Write a Python program to plot two or more lines and set the line markers.
10. Write a Python Program to plot line chart for values x=[1,2,3,4,5]y=[65,45,76,26,80]
11.Write a Python Program to Plot a line chart for equation Y=2X+5 where x=[-5,-4,………4,5]
12. Write a Python Program to Plot a line chart for a particular colour for equation Y=sin(X) where
x=[0,0.1,0.2…….5,5.1,…………10]
13 To add legends, titles and labels to a line plot with multiple lines.
14 Write a Python Program to Plot a bar chart for values cities and population.
15 Write a Python Program to plot a bar chart with width.
16 Write a Python Program to plot a bar chart horizontally
17. Write a Python Program to plot a pie chart for the popular languages among students.
('Python', 'C++', 'Java', 'Perl', 'Scala', 'Lisp')
2. import matplotlib.pyplot
62
plt.title("Graph for an Algebraic Y=2*X+5")
plt.show()
12.
import matplotlib.pyplot as plt
import numpy as np
x=np.arange(0,10,0.1)
y=np.sin(x)
plt.plot(x,y)
plt.xlabel("X")
plt.ylabel("Y")
plt.title("Graph for Y=sin(X)")
plt.show()
13.
import matplotlib.pyplot as plt
x=[1,2,3] y=[5,7,4]
plt.plot(x,y,label='First Line',color='red')
x2=[1,2,3]
y2=[10,11,14]
plt.plot(x2,y2,label='Second Line',color='black')
plt.xlabel('Plot Number')
plt.ylabel('Variables')
plt.title('New Graph')
plt.legend()
plt.show()
14.
import matplotlib.pyplot as plt
import numpy as np
city=['Delhi','Mumbai','Chennai','Hyderabad‘]
p=[1500,2000,1800,1200]
plt.bar(city,p)
plt.xlabel("City")
plt.ylabel("Population in Lacs ")
plt.title("Population of different cities")
plt.show()
15.
import matplotlib.pyplot as plt
import numpy as np
y_axis=[20,50,30]
x_axis=range(len(y_axis))
plt.bar(x_axis,y_axis,width=.5,color='orange')
plt.show()
16.
import matplotlib.pyplot as plt
import numpy as np
ob=('Python','C++','Java','Perl','Scala','Lisp')
63
y_pos=np.arange(len(ob))
performance=[10,8,6,4,2,1]
plt.barh(y_pos,performance,align='center',color='r')
plt.yticks(y_pos,ob)
plt.xlabel("Usage")
plt.title('P.L.Usage')
plt.show()
17.
import matplotlib.pyplot as plt
labels='Python','C++','Ruby','java'
sizes=[215,130,245,210]
colors=['gold', 'yellowgreen','lightcoral','lightskyblue']
explode=(0.1,0,0,0)
plt.pie(sizes,explode=explode,labels=labels,colors=colo rs, shadow=True,startangle=140)
plt.axis('equal')
plt.show()
64
CHAPTER 7 : DATA STRUCTURE-I (LINEAR LIST)
QUESTIONS ON DATA STRUCTURE ( Questions for 2 marks)
Answer
4. Def PushOn(Book):
a=input(“enter book title :”)
Book.append(a)
Def Pop(Book):
If (Book==[]):
print(“Stack empty”)
else:
print(“Deleted element :”)
Book.pop()
OR
class Stack:
Book=[]
Def PushOn(self):
a=input(“enter book title:”)
Stack.Book.append(a)
Def Pop(self):
if (Stack.Book==[]):
print(“Stack empty”)
else:
print(“Deleted element :”,Stack.Book.pop())
Definition: The logical or mathematical model of a particular organization of data is called data structure. It is a
way of storing, accessing, manipulating data.
TYPES OF DATA STRUCTURE:
There are two types of data structure:
1. Linear data structure: It is simple data structure. The elements in this data structure creates a sequence.
Example: Array, linked list, stack, queue.
2. Non-Linear data structure: The data is not in sequential form. These are multilevel data structures.
Example: Tree, graph.
Output:
10
20
30
40
50
b. Inserting Element in a list: In this case, enter the element at any position using insert( ) function or add
the element in the last of the array using append( ) function.
Example:
L=[15,8,25,45,13,19]
L.insert(3, 88) # insert element at the index 3
print(L)
Output:
[15, 8, 25, 88, 45, 13, 19]
c. Deletion of an element from a List:
To delete an element from a list we can use remove( ) or pop( ) method.
Example:
L=[10,15,35,12,38,74,12]
print("List Before deletion of element: ", L)
val=int(input("Enter the element that you want to delete: "))
L.remove(val)
print("After deletion the element", val,"the list is: ", L)
OUTPUT:
List Before deletion of element: [10, 15, 35, 12, 38, 74, 12] Enter the element that you want to delete: 12
After deletion the element 12 the list is: [10, 15, 35, 38, 74, 12]
d. Searching in a List:
There are two types of searching techniques we can use to search an element in a list. These are:
(i) Linear Search
(ii) Binary Search
67
Output:
Enter the elements: 56,78,98,23,11,77,44,23,65 Enter the element that you want to search : 23 Element
found at the position : 4
OUTPUT:
Enter the elements in sorted order: [12,23,31,48,51,61,74,85] Enter the element that you want to
search : 61
61 Found at the position : 6
easy Tricky
Efficient for small array. Efficient for larger array
e. Sorting: To arrange the elements in ascending or descending order. There are many sorting techniques.
Here we shall discuss two sorting techniques:
(i) Bubble sort
(ii) Insertion sort
68
(i) BUBBLE SORT: Bubble sort is a simple sorting algorithm. It is based on comparisons, in which each
element is compared to its adjacent element and the elements are swapped if they are not in proper
order.
PROGRAM:
L=eval(input("Enter the elements:"))
n=len(L)
for p in range(0,n-1):
for i in range(0,n-1):
if L[i]>L[i+1]:
L[i], L[i+1] = L[i+1],L[i]
print("The sorted list is : ", L)
OUTPUT:
Enter the elements:[60, 24, 8, 90, 45, 87, 12, 77]
The sorted list is : [8, 12, 24, 45, 60, 77, 87, 90]
(ii) INSERTION SORT: Sorts the elements by shifting them one by one and inserting the element at
ight position.
PROGRAM:
L=eval(input("Enter the elements: "))
n=len(L)
for j in range(1,n):
temp=L[j]
prev=j-1
while prev>=0 and L[prev]>temp: # comparison the elements L[prev+1]=L[prev]
# shift the element forward prev=prev-1
L[prev+1]=temp #inserting the element at proper position
69
Chapter: 8 Computer Network
Multiple Choice Questions : 1 Marks
70
(a) Broadcast device (b) Unicast device (c) Multicast device (d) None of the above
15. In this type of cloud ,the cloud is fully owned and used by an organization.
(a) Private (b) Public (c) Protected (d) Hybrid
16. In this type of cloud an organization rents cloud services from cloud providers on demand basis.
(a) Private (b) Public (c) Protected (d) Hybrid
17. In this type of cloud ,the cloud is composed of multiple internal or external clouds.
(a) Private (b) Public (c) Protected (d) Hybrid
18. Computer communication signal which is in form of continuous wave is called
(a) Digital Signal (b) Modulation Signal (c) Analog Signal (d) Binary Signal
19. Which of the following devices translate hostname into IP address?
(a) DNS Server (b) Hub (c) DHCP Server (d) Firewall
20. HTTP resources are located by
(a) Unique resource locator. (b) Unique resource identifier
(c) Hostname aliases (c) All of the mentioned
True/False Question
1. HTTP is HyperText Transfer protocol.
2. Secure Socket protocol is not a security protocol in WWW.
3. A LAN is connected to large geographical area.
4. A client is the computer that asks for the action in a Network.
5. A computer is identified by 64 bit IP Address.
6. Every object on the Internet has a unique URL.
7. DNS is a network service type.
8. Big networks can be of peer-to-peer types.
9. MAC address is a 48 bit address.
10. A switch can work in place of switch.
11. A gateway is like a modem.
12. The cloud is a generic term used for Internet.
13. CSMA/CD can be used by wireless network.
14. TCP is a connection oriented protocol.
15. UDP is a connection oriented protocol.
16. NSLOOKUP is a network type.
71
17. PING checks if a computer is connected to a network or not.
18. HTTP,TCP/IP,UDP are internet protocols.
19. HTTPS is a secure protocol.
20. WHOIS is a protocol.
72
LONG ANSWER QUESTION
1. Gopal Software Solution has set up its new centre at Jabalpur for its office and Web based activities. It
has four buildings as shown in the diagram below:
Gama
Alpha
Theta
Beta
2. Lantastic corporation caters to many high profile clients and has 6 buildings where it runs its operations
(shown below) 4
73
The distance between buildings is shown through distance in above diagram. The numbers
in indicate number of computers in each building i.e.,
Building Pro has 55 computers
Building Greycell has 185 computers
Building Wizard has 60 computers
Building Robo has 55 computers
Building Master has 70 computers
Answer the following questions on the basis of above given information:
(a) Suggest the possible cable layouts for the buildings.
(b) Where would you suggest the placement of server?
(c) Suggest the cable type that should be used.
(d) The management wants that the network traffic should be minimized. For this which network
device would you suggest out of the following devices and why?
(i) hub
(ii) repeater
(iii) Bridge.
3. Great Sudies University is setting up its Academic school at Sunder Nagar and planning to set up a network.
The university has 3 academic schools and one administration center as shown in the diagram bellow. [4]
Law school to Business school 60m
Law school to Technology School 90m
Law school to Admin Center 115m
Business school to Technology School 40m
Business school to Admin Center 45m
Technology school to Admin Center 25m
Law school 25
Technology school 50
Admin center 125
Business school 35
(i) Suggest the most suitable place( i.e school/center) to install the server of this university Sugewith
a suitable reason.
(ii) Suggest an ideal layout for connecting these school/center for a wired connectivity.
(iii) Which device will you suggest to be placed/installed in each of these school/center to efficiently
connect all the computers within these school/center.
(iv) The university is planning to connect its admission office in the closest big city,which is more than
350 km from the university.Which type of network out of LAN,MAN or WAN will be formed?Justify
your answer.
74
4. Ram Goods Ltd. has following four buildings in Ahmedabad city. [4]
Computers in each building are networked but buildings are not networked so far. The company has now
decided to connect building also.
(a) Suggest a cable layout for these buildings.
(b) In each of the buildings, the management wants that each LAN segment gets a dedicated
bandwidth i.e. bandwidth must not be shared. How can this be achieved?
(c) The company also wants to make available shared Internet access for each of the buildings. How
can this be achieved?
(d) The company wants to link its head office in GV1 building to its another office in Japan.
(i) Which type of transmission medium is appropriate for such a link?
(ii) What type of network would this connection result into
75
Chapter 9 : DATA MANAGEMENT
Very Short Answer Question : 1 Mark
76
Answers to Very Short Answer Questions
(1.) Dual (2) Distinct (3) -% and _ (4) Tuple (5) (c) Describe
(6). (d) BETWEEN (7). (a) Use (8) IN (9) Primary Key (10) count(*)
(11). SELECT <column-names> FROM <table-name> WHERE <column-name> IS NULL;
(12). LIKE (13). WHERE (14). is_connected() (15) Degree-3 Cardinality-10
(16). (b)SELECT (17). (a)14 (18) Ascending Order/ ASC (19) GROUP BY
(20) Data Dictionary contains data about data or metadata. It represents structure or schema of a database.
(21). Duplication of data is known as Data Redundancy.
(22). Cursor. execute(sql query) (23). Mysql.connector (24). No
(25). Result set refers to a logical set of records that are fetched from the database by executing a query.
77
4. Compare Alter and Update command.
Ans -
Alter Update
(i)It is a DDL Command. (i)It is a DML Command
(ii) It is used for changing the structure of the existing (ii) It is used for changing the contents of the
table i.e. for adding column, dropping column etc. Table.
(iii) Alter table emp add age int; (iii) Update emp set age=34 Where empid=5;
5. What are the differences between DELETE and DROP commands of SQL?
Ans : DELETE is DML command while DROP is a DDL command. Delete is used to delete rows from a table
while DROP is used to remove the entire table from the database.
Advantages
(i) Reduced data redundancy
(ii) Controlled data inconsistency
(iii) Shared data
(iv) Secured data
(v) Integrated data
78
11. Write a small python program to insert a record in the table books with attributes (title,isbn)
Ans import mysql.connector as Sqlator
conn sqlator.connect(host=”localhost”,user=”root”,passwd=””,database=”test”)
cursor=con.cursor()
query=”INSERT into books(title,isbn) values(‘{}’{})”.format(‘Neelesh’,’5143’) `
cursor.execute(query)
con.close()
Candidate keys are defined as the set of fields from which primary key can be selected. Candidate key is
a set of one or more fields/columns that can identify a record uniquely in a table. There can be multiple
candidate keys in one table.
e.g.: in the table stud(id,rollno,fname,lname,email) id,rollno and email are candidate key because both
can uniquely identify the stud record in the table.
14. Can you add more than one column in a table by using the ALTER TABLE command?
Ans. Yes, we can add more than one column by using the ALTER TABLE command. Multiple column names
are given, which are separated by commas, while giving with ADD. For example, to add city and pin code
in a table employee, the command can be given as:
ALTER table employee ADD (city CHAR(30), PINCODE INTEGER);
15. Write a small python program to retrieve all record from the table books with attributes (title ,isbn).
Ans- import mysql.connector as Sqlator
conn sqlator.connect(host=”localhost”,user=”root”,passwd=””,database=”test”)
cursor=con.cursor()
query=”select * from query”
cursor.execute(query)
data=cursor.fetchall()
for row in data:
print(row)
conn.close()
79
Table based Questions (3+4)
1. (a) Write a output for SQL queries (i) to (iii), which are based on the table: ACTIVITY given below:
Table: ACTIVITY
ACode ActivityName ParticipantsNu PrizeMoney ScheduleDat
m e
(b) Write SQL queries for (i) to (iv), which are based on the table : ACTIVITY given in the question
(i) To display the name of all activities with their Acodes in descending order.
Ans : select ActivityName, Acodes from ACTIVITY order by Acodes desc;
(ii) To display sum of PrizeMoney for each of the Number of participants groupings (as
shown in column ParticipantsNum 10,12,16).
Ans: SELECT SUM(PrizeMoney),ParticipantsNum FROM ACTIVITY GROUP BY ParticipantsNum;
(iii) To display the Schedule Date and Participants Number for the activity Relay 100x4
Ans : select ScheduleDate, ParticipantsNum FROM ACTIVITY where ActivityName=’ Relay 100x4’
2. (a) Write SQL queries for (i) to (iv) based on the following tables.
Table: TRAVEL.
NO NAME TDATE KM CODE NOP
101 Janish 2015-02-18 100 101 32
102 Vedika 2014-06-06 65 101 45
103 Tarun 2012-10-09 32 104 42
104 John 2015-10-30 55 105 40
105 Ahmed 2015-12-15 47 103 16
106 Raveena 2016-02-26 82 103 9
NO is Traveller Number, KM is Kilometers travelled
NOP is number of travellers in a vehicle DATE is Travel Date
VCODE Vehicle Code
80
Table: VEHICLE
CODE VTYPE PERKM
101 VOLVO BUS 160
102 AC BUS 150
104 ORDINARY BUS 80
103 CAR 25
105 SUV 40
(i) To display NO, NAME,TDATE from the table Travel in the descending order of NO.
(ii) To display the NAME of all the travellers from the table TRAVEL who are travelling by vehicle
with code 101 or 102.
(iii) To display the NO and NAME of those travellers from the table TRAVEL who travelled between
2015-12-31 and 2015-04-01.
(iv) Display maximum and minimum kilometres travelled by passengers.
(b) Write output of the following questions based on the above tables.
(i) SELECT COUNT (*), CODE FROM TRAVEL GROUP BY CODE HAVING COUNT(*)>1;
(ii) SELECT DISTINCT CODE FROM TRAVEL;
(iii) SELECT A.CODE,NAME,VTYPE FROM TRAVEL A,VEHICLE B WHERE A.CODE=B.CODE AND KM<80;
3(a) Write a output for SQL queries ( i ) to (iii) , which are based on the tables: TRAINER and COURSE
TRAINER
81
COURSE
CID CNAME FEES STARTDATE TID
C201 AGDCA 12000 2018-07-02 101
C202 ADCA 15000 2018-07-15 103
C203 DCA 10000 2018-10-01 102
C204 DDTP 9000 2018-09-15 104
C205 DHN 20000 2018-08-01 101
C206 O LEVEL 18000 2018-07-25 105
(i) SELECT TID, TNAME, FROM TRAINER WHERE CITY NOT IN(‘DELHI’, ‘MUMBAI’);
(ii) SELECT TID ,COUNT(*), MIN(FEES) FROM COURSE GROUP BY TID HAVING COUNT(*)>1;
(iii) SELECT COUNT(*), SUM(FEES) FROM COURSE WHERE STARTDATE<’2018-09-15’;
(b) Write SQL queries for (i) to (iv) , which are the based on the tables : TRAINER and COURSE given
in the question :
(i) Display the Trainer Name, City & Salary in descending order of their Hiredate.
Ans: SELECT TNAME,CITY,SALARY FROM TRAINER ORDER BY HIREDATE;
(ii) To display the TNAME and CITY of trainer who joined the institute in the month of
December 2001.
Ans: SELECT TNAME,CITY FROM TRAINER WHERE HIREDATE BETWEEN ‘2001-12-01’ AND
‘2001-12-31’;
(iii) To display TNAME, HIREDATE, CNAME, STARTDATE from tables TRAINER and COURSE of
all Those courses whose FEES is less than or equal to 10000.
Ans : SELECT TNAME, HIREDATE,CNAME,STARTDATE FROM TRAINER, COURSE WHERE
TRAINER.TID=COURSE.TID AND FEES<=10000;
(iv) To display number of trainers from each city.
Ans: SELECT CITY, COUNT(*) FROM TRAINER GROUP BY CITY
4. Consider these two tables and write output for (I to iii) and SQL query for (iv to vi).
Table : ITEMS
ID PNAME PRICE MDATE QTY
T001 Soap 12.00 11/03/2007 200
T002 Paste 39.50 23/12/2006 55
T003 Deodorant 125.00 12/06/2007 46
T004 Hair Oil 28.75 25/09/2007 325
T005 Cold Cream 66.00 09/10/2007 144
T006 Tooth Brush 25.00 17/02/2006 455
82
TABLE : COMPANY
ID COMP City
T001 HLL Mumbai
T008 Colgate Delhi
T003 HLL Mumbai
T004 Paras Haryana
T009 Ponds Noida
T006 Wipro Ahmedabad
(i) SELECT SUM(QTY) FROM ITEMS WHERE PNAME LIKE ‘H%’ OR PNAME LIKE ‘T%’
(ii) SELECT COUNT(*) FROM ITEMS WHERE QTY > 100;
(iii) SELECT QTY FROM ITEMS WHERE ID>’TOO3’;
(iv) To display PNAME, PRICE * QTY only for the where price is greater than 100
(v) To display company name & city for ID= T001 and T008
(vi) To delete the items produced before 2007.
(vii) To increase the quantity by 20 for soap and paste.
Ans: (i) 780 (ii) 4 (iii) 325
144
455
(iv) Select PNAME, PRICE * QTY from ITEMS where Price>100
(v) Select comp,city from company where ID IN(‘T001’ AND ‘T008’
(vi) DELETE * from ITEMS where year(MDATE)<2007.
(viii) Update ITEMS Set QTY=QTY+20 where Items in (‘soap’,’paste)
83