0% found this document useful (0 votes)
13 views82 pages

083 - XII - CS - Question Bank 02

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

083 - XII - CS - Question Bank 02

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

TABLE OF CONTENTS

CHAPTER 1 : PROGRAMMING WITH PYTHON ............................................................................ 4


MCQ QUESTIONS ( 1 MARKS ).................................................................................................................................... 4
ANSWERS TO MCQS.................................................................................................................................................. 8
EXPLANATION: .......................................................................................................................................................... 8
PROBLEM SOLVING AND PYTHON PROGRAMMING : 1 MARKS .......................................................................... 9
PROBLEM SOLVING AND PYTHON PROGRAMMING : 2 MARKS ........................................................................ 12
ANSWERS .............................................................................................................................................................. 17
OUTPUT FINDING QUESTIONS ........................................................................................................................... 20
QUESTIONS BASED ON TUPLE .................................................................................................................................... 25
LIST BASED QUESTION.............................................................................................................................................. 27
QUESTION BANK ON OUTPUT AND ERROR BASED QUESTIONS ON FUNCTIONS IN PYTHON ............................ 29
GENERAL THEORY QUESTIONS ........................................................................................................................... 32
OUTPUT ................................................................................................................................................................ 32
OUTPUTS(TUPLES) .................................................................................................................................................. 34
ERROR TUPLES ........................................................................................................................................................ 35
ANSWERS BASED ON LIST ......................................................................................................................................... 35
FUNCTIONS(ERROR) ............................................................................................................................................. 36
GENERAL QUESTIONS ............................................................................................................................................... 38

CHAPTER 2: USING PYTHON LIBRARIES ................................................................................ 40


MULTIPLE CHOICE QUESTIONS ................................................................................................................................... 40
ANSWERS .............................................................................................................................................................. 41
SHORT ANSWER QUESTIONS : 2 MARKS ....................................................................................................................... 41
ANSWERS :............................................................................................................................................................. 42
LONG ANSWER QUESTIONS : 3 MARKS ........................................................................................................................ 43
ANSWERS .............................................................................................................................................................. 44
RELATIONSHIP BETWEEN A MODULE, PACKAGE AND LIBRARY IN PYTHON....................................................... 45
CREATION OF LIBRARY/PACKAGE ( 2 MARKS)....................................................................................................... 46

CHAPTER 3 : FILE HANDLING .................................................................................................. 47


VERY SHORT ANSWER QUESTIONS : 1 MARK ................................................................................................................ 47
ANSWERS .............................................................................................................................................................. 47
SHORT ANSWER QUESTIONS : 2 MARKS ...................................................................................................................... 47
ANSWERS .............................................................................................................................................................. 49
LONG ANSWER QUESTIONS : 3 MARKS........................................................................................................................ 49
ANSWER ................................................................................................................................................................ 50
NOTES ON FILE HANDLING ........................................................................................................................................ 52

CHAPTER 4 : RECURSION........................................................................................................ 55
2
HOTS BASED QUESTIONS ......................................................................................................................................... 55
RECURSION ANSWERS........................................................................................................................................ 56

CHAPTER 5 : IDEA OF ALGORITHMIC EFFICIENCY ................................................................. 59


ANSWERS: IDEA OF ALGORITHMIC EFFICIENCY ................................................................................................. 59

CHAPTER 6 : DATA VISUALIZATION USING PYPLOT .............................................................. 61


ANSWERS : DATA VISUALIZATION USING PYPLOT ( 3 MARKS QUESTIONS ) ...................................................................... 61

CHAPTER 7 : DATA STRUCTURE-I (LINEAR LIST) ....................................................................... 65


QUESTIONS ON DATA STRUCTURE ( QUESTIONS FOR 2 MARKS) ............................................................................. 65
ANSWER ................................................................................................................................................................ 65
NOTES ON DATA STRUCTURE ..................................................................................................................................... 66

CHAPTER: 8 COMPUTER NETWORK ...................................................................................... 70


MULTIPLE CHOICE QUESTIONS : 1 MARKS ................................................................................................................... 70
FILL IN THE BLANKS .................................................................................................................................................. 71
TRUE/FALSE QUESTION ............................................................................................................................................ 71
VERY SHORT ANSWER QUESTIONS..................................................................................................................... 72
SHORT ANSWER QUESTIONS.............................................................................................................................. 72
LONG ANSWER QUESTION ................................................................................................................................. 73

CHAPTER 9 : DATA MANAGEMENT ...................................................................................... 76


VERY SHORT ANSWER QUESTION : 1 MARK ................................................................................................................. 76
ANSWERS TO VERY SHORT ANSWER QUESTIONS ........................................................................................................... 77
SHORT ANSWER QUESTIONS : 2 MARKS ...................................................................................................................... 77
TABLE BASED QUESTIONS (3+4) ................................................................................................................................ 80

3
Chapter 1 : PROGRAMMING WITH PYTHON
MCQ Questions ( 1 Marks )

1. Is Python case sensitive when dealing with identifiers?


(a) Yes (b) No (c) Machine dependent (d) None of the mentioned

2. What is the maximum possible length of an identifier?


(a) 31 characters (b) 63 characters (c) 79 characters (d) none of the mentioned

3. Which of the following is invalid?


(a) _a = 1 (b) __a = 1 (c) __str__ = 1 (d) none of the mentioned

4. Which of the following is an invalid variable?


(a) my_string_1 (b) 1st_string (c) foo (d) _

5. Why are local variable names beginning with an underscore discouraged?


(a) they are used to indicate a private variables of a class
(b) they confuse the interpreter
(c) they are used to indicate global variables
(d) they slow down execution

6. Which of the following is not a keyword?


(a) eval (b) assert (c) nonlocal (d) pass

7. All keywords in Python are in _________


(a) lower case (b) UPPER CASE (c) Capitalized (d) None of the mentioned

8. Which of the following is true for variable names in Python?


(a) unlimited length
(b) all private members must have leading and trailing underscores
c) underscore and ampersand are the only two special characters allowed
d) none of the mentioned

9. Which of the following is an invalid statement?


(a) abc = 1,000,000 (b) a b c = 1000 2000 3000
(c) a,b,c = 1000, 2000, 3000 (d) a_b_c = 1,000,000

4
10. Which of the following cannot be a variable?
(a) __init__ (b) in (c) it (d) on

11. What is the output of print 0.1 + 0.2 == 0.3?


(a) True (b) False (c) Machine dependent (d) Error

12. Which of the following is not a complex number?


(a) k = 2 + 3j (b) k = complex(2, 3) (c) k = 2 + 3l (d) k = 2 + 3J

13. What is the type of inf?


(a) Boolean (b) Integer (c) Float (d) Complex

14. What does ~4 evaluate to?


(a) -5 (b) -4 (c) -3 (d) +3

15. What does ~~~~~~5 evaluate to?


(a) +5 (b) -11 (c) +11 (d) -5

16. Which of the following is incorrect?


(a) x = 0b101 (b) x = 0x4f5 (c) x = 19023 (d) x = 03964

17. What is the result of cmp(3, 1)?


(a) 1 (b) 0 (c) True (d) False

18. Which of the following is incorrect?


(a) float(‘inf’) (b) float(‘nan’) (c) float(’56’+’78’) (d) float(’12+34′)

19. What is the result of round(0.5) – round(-0.5)?


(a) 1.0 (b) 2.0 (c) 0.0 (d) None of the mentioned

20. What does 3 ^ 4 evaluate to?


(a) 81 (b) 12 (c) 0.75 (d) 7

21. Which of the following statements create a dictionary?


(a) d = {} (b) d = {“john”:40, “peter”:45}
(c) d = {40:”john”, 45:”peter”} (d) All of the mentioned

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

26. Which of the following is a Python tuple?


(a) [1, 2, 3] (b) (1, 2, 3) (c) {1, 2, 3} (d) {}

27. Suppose t = (1, 2, 4, 3), which of the following is incorrect?


(a) print(t[3]) (b) t[3] = 45 (c) print(max(t)) (d) print(len(t))

28. What will be the output of the following Python code?


>>>t=(1,2,4,3)
>>>t[1:3]
(a) (1, 2) (b) (1, 2, 4) (c) (2, 4) (d) (2, 4, 3)

29. What will be the output of the following Python code?


>>>t=(1,2,4,3)
>>>t[1:-1]
(a) (1, 2) (b) (1, 2, 4) (c) (2, 4) (d) (2, 4, 3)

30. What will be the output of the following Python code?


>>>t = (1, 2, 4, 3, 8, 9)
>>>[t[i] for i in range(0, len(t), 2)]
(a) [2, 3, 9] (b) [1, 2, 4, 3, 8, 9] (c) [1, 4, 8] (d) (1, 4, 8)

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”

32. What will be the output of the following Python code?


>>>t = (1, 2)
>>>2 * t
(a) (1, 2, 1, 2) (b) [1, 2, 1, 2] (c) (1, 1, 2, 2) (d) [1, 1, 2, 2]
33. Which of these about a set is not true?
(a) Mutable data type (b) Allows duplicate values
(c) Data type with unordered values (d) Immutable data type

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}

35. What will be the output of the following Python code?


nums = set([1,1,2,3,3,3,4,4])print(len(nums))
(a) 7 (b) Error, invalid syntax for formation of set (c) 4 (d) 8.

36. What will be the output of the following Python code?


a = [5,5,6,7,7,7]
b = set(a)def test(lst):
if lst in b:
return 1
else:
return 0for i in filter(test, a):
print(i,end=" ")
(a) 556 (b) 567 (c) 556777 (d) 56777

37. Which of the following statements is used to create an empty set?


(a) {} (b) set() (c) [] (d) ()

38. What will be the output of the following Python code?


>>> a={5,4}>>> b={1,2,4,5}>>> a<b
(a) {1,2} (b) True (c) False (d) Invalid operation

39. If a={5,6,7,8}, which of the following statements is false?


(a) print(len(a)) (b) print(min(a)) (c) a.remove(5) (d) a[2]=45

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

41. What will be the output of the following Python code?


>>> a={4,5,6}>>> b={2,8,6}>>> a+b
(a) {4,5,6,2,8} (b) {4,5,6,2,8,6}
(c) Error as unsupported operand type for sets
(d) Error as the duplicate item 6 is present in both sets

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.

PROBLEM SOLVING AND PYTHON PROGRAMMING : 1 Marks

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.

2. What are the properties of algorithm?


It is written in simple English.

Each step of an algorithm is unique and should be self-explanatory.

An algorithm must have at least one input.

An algorithm must have at least one

output. An algorithm has finite number of steps.

9
3. What are the building block of algorithm?
The three building block of algorithm are :
 Sequence
 Selection
 Iteration

4. What is meant by sequence , selection control structures?


Sequence : A sequence is one of the basic logic structures in computer programming. In a sequence
structure, an action, or event, leads to the next ordered action in a predetermined order.
Selection : A selection (also called a decision) is also one of the basic logic structures in computer
programming. In a selection structure, a question is asked, and depending on the answer, the program
takes one of two courses of action, after which the program moves on to the next event.

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.

6. Write the Characteristics of Pseudo code.


Named variables represent data and identifiers denote higher level functions.
Composed of a sequence of statements or steps.

Statements are often numbered sequentially.


Operational (Imperative) statements include assignment, input, and output
Control structures provide iterative and conditional execution.
Indentations used for grouping

7. What is need for flowchart symbol?


The need for flowchart symbols because each symbols of different shapes denotes different types of
instructions. The program logic through flowcharts is made easier through the use of symbol that has
standardized planning.

8. Write some rules for drawing a flowchart.

9. What do you understand by the term Iteration?


Repetition of statement/s finite number of times is known as Iteration

10. What are the advantages of using a flowchart.


Ans : Communication, Effective, Proper Documentation, Efficient Coding, Proper Debugging, Efficient
Program Maintenance.

10
11. Write any two disadvantages of flowchart ?
Ans : (i) It is not visual (ii) We do not get a picture of the design.

12. What is Pseudo code?


―Pseudo‖ means imitation of false and ―code‖ refers to the instruction written in a programming
language. Pseudo code is programming analysis tool that is used for planning program logic.

13. Write the Characteristics of Pseudocode.


Named variables represent data and identifiers denote higher level functions.
Composed of a sequence of statements or steps.
Statements are often numbered sequentially.
Operational (Imperative) statements include assignment, input, and
output.
Control
execution.
Indentations used for grouping blocks of statement

14. What are the rules for writing pseudo code?


 Write one statement
 per line. Capitalize
 initial keywords.
 Indent to show hierarchy.
 End multiline structure.
 Keep statements language independent.

15. Write any two advantages of pseudo code.


- It can be done easily in any word processor.
- It can be written easily.
- It can be easily modified as compared to flowchart.

16. Write any two disadvantages of flowchart?


- It is not visual,
- we do not get a picture of the design.

17. Differentiate Algorithm and Pseudo code


Algorithm Pseudo code
It is a well-defined procedure that It is a simple way of writing programming code
allows a computer to solve a problem. in English.
Algorithms can be described in Pseudo code describes how you would
various ways, from pure mathematical implement an algorithm without getting into
formulas to complex graphs Syntactical details.
11
18. What is the difference between algorithm and flowchart.
Algorithm Flow Chart
Step by Step formation Box by box formation
Mostly run to complete or manage a Can be used in general terms to solve any

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

22. Which is the correct form of declaration of dictionary?


(i) Day={1:’monday’,2:’tuesday’,3:’wednesday’} (ii) Day=
(1;’monday’,2;’tuesday’,3;’wednesday’) (iii) Day=
[1:’monday’,2:’tuesday’,3:’wednesday’] (iv) Day={1’monday’,2’tuesday’,3’wednesday’]
Answer:- (i) Day={1:’monday’,2:’tuesday’,3:’wednesday’}

PROBLEM SOLVING AND PYTHON PROGRAMMING : 2 Marks

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)

2. 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')

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#

4. Find and write the output of the following python code:


a = 10
def call():
global a
a=15
b=20
print (a+b)
call()
print (a)

5. Explain global and local variable.


Answer:- A global variable is a variable that is accessible globally. A local variable is one that is only accessible to
the current scope, such as temporary variables used in a single function definition. A variable declared outside of
the function or in global scope is known as global variable. This means, global variable can be accessed inside or
outside of the function where as local variable can be used only inside of the function. We can access by declaring
variable as global A.
6. A bar chart is drawn(using pyplot) to represent sales data of various models of cars, for a month. Write
appropriate statements in Python to provide labels Month - June and Sale done to x and y axis respectively.

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

3. Output : (ii) 30#40#50# Maximum value FROM,TO is 3,4)

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)

9. Underline and correct errors


a,b = 0,0
if (a = =b) :
c=a +b
print(c)

10. Underline and correct errors


Number = 250
while Number<=1000:
if Number >= 750:
print (Number)
Number = Number+100
else:
print (Number*2)
Number = Number+50

11. Underline and correct errors


Val = int(raw_input("Value:")) # Error 1
Adder = 0
for C in range(1,Val,3) : # Error 2
Adder+=C
if C%2==0: # Error 3
print( C*10 ) # Error 4
else: # Error 5
print (C ) # Error 6
print Adder

12. Underline and correct errors


Val = 25 #Error 1
for I in range(0,Val): #Error 2 (the) and Error 3
if I%2==0:
print (I+1)
else: #Error 4
print (I-1)

13. Underline and correct errors


STRING= "WELCOME"

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)

14. Underline and correct errors


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. Underline and correct errors


i=1
a=int(input("ENTER FIRST NUMBER"))
for i in range(1,11):
print(a,"*=",i,"=",a*i)

16. Underline and correct errors


a=1
while a<=10:
print("Value of a=",a)
a+=1

17. Underline and correct errors


Num=int(input("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. Underline and correct errors


weather='raining'
if weather=='sunny':
print("wear sunblock")
elif weather=='snow':

19
print("going skiing")
else:
print(weather)
19. Required Modules
Math module and String module

20. Underline and correct errors


def execmain():
x= input("Enter a number:") (indentation)
if(abs(x)== x):
print("You entered a positive number")
else:
x *= -1(indentaion)
print("Number made positive:" , x)
execmain()

21. Underline and correct errors


x=int(input('Enter 1 or 10'))
if x==1:
for x in range(1,11):
print(x)
else:
for x in range(10,0,-1):
print(x)(indentation)

22. Underline and correct errors


To=30
for K in range(0,To) :
ifk%4==0:
print (K*4)
else:
print (K+3)

OUTPUT FINDING QUESTIONS

1. Find output generated by the following code:


p=10
q=20
p*=q//3
q+=p-q**2
print(p,q)

2. Find output generated by the following code:


Str=”Computer”
Str[-4:]
Str*2

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)

4. Find out the output of the Following –


for a in range(3,10,3):
for b in range(1,a,2):
print(b, end=’ ‘)
print ()

5. Find Output of Following


x=10
y=5
for i in range(x-y*2):
print("%",i)

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

15. Find Output


line = "I'll come by then."
eline = ""
for i in line:
eline += chr(ord(i)+3)
print(eline)

16. Find Output


line = "What will have so will"
L = line.split('a')
for i in L:
print(i, end=' ')
17. Find output
p=5/2
q=p*4
r=p+q
p+=p+q+r
q-=p+q*r
print(p,q,r)

18. find output


23
a=(2+3)**3-6/2
b=(2+3)*5//4+(4+6)/2
c=12+(3*4-6)/3
d=12%5*3+(2*6)//4
print(a,b,c,d)

19. Find the output of the following:


def main ( ) :
Moves=[11, 22, 33, 44]
Queen=Moves
Moves[2]+=22
L=Len(Moves)
for i in range (L):
print “Now@”, Queen[L-i-1], “#”, Moves [i]

20. Find the output of the following


L1 = [100,900,300,400,500]
START = 1
SUM = 0
for C in range(START,4):
SUM = SUM + L1[C]
print(C, ":", SUM)
SUM = SUM + L1[0]*10
print(SUM)

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')

22. Find the output of the given program.


def Change(P ,Q=30):
P=P+Q
Q=P-Q
print( P,"#",Q)
return (P)
R=150
S=100
R=Change(R,S)

24
print(R,"#",S)
S=Change(S)
23. Find output
x = "abcdef"
i = "a"
while i in x:
print(i, end = " ")

Questions Based on Tuple

24. Find the output of following codes


(a) t1=("sun","mon","tue","wed")
print(t1[-1])

(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])

25. Find the errors

(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

26. Give the output of the following code:-


list=['p','r','o','b','l','e','m']
list[1:3]=[]
print(list)
list[2:5]=[]
print(list)

27. Give the output of the following code:-


l1=[13,18,11,16,13,18,13]
print(l1.index(18))
print(l1.count(18))
l1.append(l1.count(13))
print(l1)

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’])

(b) list1 =[1998, 2002, 1997, 2000]


list2 =[2014, 2016, 1996, 2009]
print"list1 + list 2 = : ", list1 +list2 #statement 1
print"list1 * 2 = : ", list1 *2 #statement 2

(c) list1 = [1, 2, 3, 4, 5]


list2 =list1
list2[0] =0;
print("list1= : ", list1)

29. What is the output of the following:


data =[2, 3, 9]
temp =[[x forx in[data]] forx inrange(3)]
print(temp)
(a) [[[2, 3, 9]], [[2, 3, 9]], [[2, 3, 9]]] (b) [[2, 3, 9], [2, 3, 9], [2, 3, 9]]
(c) [[[2, 3, 9]], [[2, 3, 9]]] (d) None of these

30. What is the output ?


temp =['Geeks', 'for', 'Geeks']
arr =[i[0].upper() for i in temp]
print(arr)
(a) [‘G’, ‘F’, ‘G’] (b) [‘GEEKS’]
(c) [‘GEEKS’, ‘FOR’, ‘GEEKS’] (d) Compilation error

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

32. What will be the error of the following code Snippet?


Lst =[1,2,3,4,5,6,7,8,9]
Lst[::2]=10,20,30,40,50,60
Print[Lst]

33. Find the error in following code. State the reason of the error
aLst={‘a’:1,’b’:2,’c’:3}
print(aLst[‘a’,’b’])

34. What Will Be The Output Of The Following Code Snippet?


a =[1,2,3,4,5]
print(a[3:0:-1])
(a) Syntax error (b) [4, 3, 2] (c) [4, 3] (d) [4, 3, 2, 1]

35. What Will Be The Output Of The Following Code Snippet?


fruit_list1 = ['Apple', 'Berry', 'Cherry', 'Papaya']
fruit_list2 = fruit_list1
fruit_list3 = fruit_list1[:]
fruit_list2[0] = 'Guava'
fruit_list3[1] = 'Kiwi'
sum = 0
for ls in (fruit_list1, fruit_list2, fruit_list3):
if ls[0] == 'Guava':
sum += 1
if ls[1] == 'Kiwi':
sum += 20
print (sum)
(a) 22 (b) 21 (c) 0 (d) 43

36. What Will Be The Output Of The Following Code Snippet?


a = {(1,2):1,(2,3):2}
print(a[1,2])
(a) Key Error (b) 1 (c) {(2,3):2} (d) {(1,2):1}

37. What Will Be The Output Of The Following Code Snippet?


my_dict = {}
my_dict[1] = 1
my_dict['1'] = 2
my_dict[1.0] = 4

28
sum = 0
for k in my_dict:
sum += my_dict[k]
print (sum)
(a) 7 (b) Syntax error (c) 3 (d) 6

38. What Will Be The Output Of The Following Code Snippet?


my_dict = {}
my_dict[(1,2,4)] = 8
my_dict[(4,2,1)] = 10
my_dict[(1,2)] = 12
sum = 0
for k in my_dict:
sum += my_dict[k]
print (sum)
print(my_dict)
(a) Syntax error
(b) 30
{(1, 2): 12, (4, 2, 1): 10, (1, 2, 4): 8}
(c) 47
{(1, 2): 12, (4, 2, 1): 10, (1, 2, 4): 8}
(d) 30
{[1, 2]: 12, [4, 2, 1]: 10, [1, 2, 4]: 8}

QUESTION BANK ON OUTPUT AND ERROR BASED QUESTIONS ON FUNCTIONS IN PYTHON

39. Identify the errors, underline it and correct the errors


(a) Def Sum(a=1,b)
return a+b
print (“The sum =” Sum(7,-1)

(b) def main ( )


print ("hello")

(c) def func2() :


print (2 + 3)
func2(5)

40 Find the output of the following numbers:


Num = 20
Sum = 0
for I in range (10, Num, 3):
Sum+=i
if i%2==0:
print i*2
else:
print i*3
29
41. Find the output of the following
(a) text="gmail@com"
L=len(Text)
ntext=" "
for i in range (0,L):
if text[i].isupper():
ntext=ntext+text[i].lower()
elif text[i].isalpha():
ntext=ntext+text[i].upper()
else:
ntext=ntext+'bb'
print ntext

(b) def power (b , p):


r = b ** p
return r
power(5,2)

(c) def calcSquare(a):


a = power (a, 2)
return a
n=5
result = calcSquare(n)
print (result )

(d) import math


print (math. floor(5.5))

(e) def gfg(x,l=[]):


for i in range(x):
l.append(i*i)
print(l)
gfg(2)
gfg(3,[3,2,1])
gfg(3)

(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)

(h) def Func(message,num=1):


print(message*num)
Func(‘python’)
Func(‘easy’,3)

(i) def Check(n1=1,n2=2):


n1=n1+n2
n2+=1
print(n1,n2)
Check()
Check(2,1)
Check(3)

(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”]

The following should get displayed


MP
MH
MZ
45. Write a python function generatefibo(n) where n is the limit, using a generator function Fibonacci (max)
(where max is the limit n) that produces Fibonacci series.
46. Write a definition of a method COUNTNOW(PLACES) to find and display those place names, in which
There are more than7 characters. For example :If the list PLACES contains.

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)

GENERAL THEORY QUESTIONS

48. Which string method is used to implement the following:


(a) To count the number of characters in the string
(b) To change the first character of the string in capital letter
(c) To change lowercase to uppercase letter
(d) To check whether the given character is letter or a number
49. What are default arguments ?
50. What is a recursive function ?
51. What is the difference between built-in functions and modules?
52. What is the difference between local variable and global variable?
53. What are the advantages of writing functions with keyword arguments?
54. What do you mean by scope of variables ?
55. Differentiate between the round() and floor() functions with the help of suitable example.
56. What is the difference between actual and formal parameters ?

57. Which of the following is valid arithmetic operator in Python:


(i) // (ii) ? (iii) < (iv) and
58. Write the type of tokens from the following:
(i) if (ii) roll_no
59. Which of the following are valid operators in Python:
(i) ** (ii) */ (iii) like (iv) ||
(v) is (vi) ^ (vii) between (viii) in
60. Which of the following can be used as valid variable identifier(s) in Python?
(i) 4thSum (ii) Total (iii) Number# (iv) _Data

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

10. Output : G*L*TME

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$

13. Output : ISSCE*3129

14. Output : 47.0


35.0
54.0
26.0
15. Output : L*oo#frph#e|#wkhq1

16. Output : Wh t will h ve so will


33
17. Output : (27.5 - 142.5 12.5)

18. Output : (122.0 11.0 14.0 9)

19. Output : Now @ 44 # 11


Now @ 55 # 22
Now @ 22 # 55
Now @ 11 # 44

20. Output : 1:900


1900
3200
3:3600
4600

21. Output : SCHOOLbbbbCOM

22. Output : 250 #150


250 #100
130 #100

23. Output aaaaaa OR infiniteloop

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(a) (i) ti*t2 cant multiply


(ii) P is in uppercase in print command
(iii) t5 is not defined

25(b). (i) len() is used wrongly


(ii) P is in uppercase in print command
(iii) T1 is not defined

25(c) (i) 'tuple' object does not support item assignment in line 2
(ii) Append() Method is not with tuple

25(d). (i) line 3 cannot concatenate with int


(ii) Parenthesis is missing in line 4

25(e) (i) Syntax error in index function


(ii) Syntax error in max function

Answers based on LIST

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)

31. (b) False

32. ValueError: attempt to assign sequence of size 6 to extended slice of size 5

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)

39(a). def sum(a=1,b) :__


return a+b (indentation)
print (“The sum =”, Sum(7,-1))

39(b). def main ( ):


print ("hello")

39(c). def func2() :


print (2 + 3) func2() no parameter is to be passed

40. Output: 20
39
32
57

41(a) Output: GMAILbbCOM

41(b). Output : 25

41(c) Output : 25

41(d) Output : 5.0

41(e) Output : [0,1]


[3,2,1,0,1,4]
[0,1,0,1,4]

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)

43. def AddOdd(NUMBERS):


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

44. def MSEARCH(STATES):


for i in STATES:
if i[0]==’M’:
print i

45. def Fibonacci (max):


a, b = 0, 1
while a <=max:
yield a,
a,b = b,a+b
def generatefibo(n):
for i in Fibonacci (n):
print( i)

46. def countno(m):


length=len(m)
for i in range(0,length):
if len(m[i])>7:
print(m[i])

47. def GenNum(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

1. Which of these definitions correctly describe a module?


(a) Denoted by triple quotes for providing the specifications of certain program elements.
(b) Design and implementation of specific functionality to be incorporated into a program
(c) Defines the specifications of how it is to be used.
(d) Any program that reuses code.

2. Which of the following is not true about main modules?


(a) When a python file is directly executed, it is considered main module of a program
(b) Main modules may import any number of modules
(c) Special name given to main modules is: _main_
(d) Other main modules can import main modules

3. Which of the following is not a valid namespace?


(a) global namespace
(b) public namespace
(c) built in namespace
(d) local namespace

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

5. What is the order of namespaces in which python looks for an identifier?


(a) python first searches the global namespace, then the local namespace and finally the built in
namespace.
(b) python first searches the local namespace, then the global namespace and finally the built in
namespace
(c) python first searches the built in namespace, then the global namespace and finally the local
namespace.
(d) python first searches the built in namespace , then the local namespace and finally the global
namespace

6. Which of these is not an advantage of using the modules?


(a) Provides a means of reusing program code.
(b) Provides a means of dividing up tasks.
(c) Provides a means of reducing the size of the program.
(d) Provides a means of testing individual parts of the program.

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

9. In python which is the correct method to load a module math?


(a) include math (b) import math (c) #include<math.h> (d) using math

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

11. What is the extension of the python library module?


(a) .mod (b) .lib (c) .code (d) .py

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

Short answer questions : 2 Marks

1. How can you locate environment variable for python to locate the module files imported into a
program?

2. What is the output of the following piece of code?


#mod1
def change (a):
b=[x*2 for x in a]
print (b)
#mod2
def change (a) :
b =[x*x for x in a]
print (b)
from mode 1 import change
from mode 2 import change
#main
S= [1,2,3]
Change (s)
Note: Both the modules mod1 and mod 2 are placed in the same 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?

4. What is the problem in the following piece of code?


from math import factorial
print (math.factorial (5))

5. What is the output of the following piece of code?


#mod1
def change (a):
b=[x*2 for x in a]
print (b)
#mod 2
def change (a):
b=[x*x for x in a]
print (b)
from mod 1 import change
from mod 2 imoprt change
#main
S=[1,2,3]
Changes(s)

6. What would be the output produced by the following code :


Import math
Import random
print ( math.ceil (random.random()))
Justify your answer.

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)

3. When python encounters an important statement, it does the following:


 The code of imported module is interpreted and executed.
 Defined functions and variables created in the module are now available to the program that imported
module.
 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

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.

6. The output Produced would be 1.0

Long Answer questions : 3 Marks

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

3. Consider a module ‘simple’ given below:


#module simple.py
“ “ “Greets or scold on call” “ “
def greet():
“ “ “ Greet anyone you like :-)” “ “
Print (“Helloz”)
def scold ():
“ “ “ Use me for scolding ,but scolding is not good:-( “ “ “
Print (“Get lost”)
Count =10
43
Print (“greeting or scolding- is it simple?”)
Another program ‘test.py’ imports this module.The code inside test.py is :
#test.py
import simple
print(simple.count)
What would be the output produced ,if we run the program test.py? justify your answer.

4. Consider the following code:


Import math
Import random
print(str(int(math.pow( random.randint (2,4),2) )), end = ‘ ’)
print(str( int ( math.pow(random.randint(2,4), 2))) , end= ‘ ’)
print ( str ( int (math.pow( random .randint (2,4),2))))

What would be possible outputs out of the given four choices?


(i) 234
(ii) 944
(iii) 16 16 16
(iv) 249
(v) 494
(vi) 444

Answers

1. (a). input
(b). math_operation_name_
(c). math.operation.add

2. (a). from__operation import subtract


(b). subtract
(c). from math___ operation import*

3. The output produced would be:


Greeting or scolding – is it simple ?
10
The reason being ,import module’s main block is executed upon import, so its important statement
cause it to print:
Greting or scolding- is it simple?
And print (simple.count) statement causes output’s next line ,i.e., 10

4. The possible outputs could be (ii), (iii) (v) and (vi).


The reason being that randint () would generate an integer between range 2…4, which is then raised to
power 2.

44
RELATIONSHIP BETWEEN A MODULE, PACKAGE AND LIBRARY IN PYTHON

A python program consist of three main components


1)Library or package
2)Module
3)Function/Sub Modules

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

importing Modules:There are two ways to import a modules


1) Using import statement: we can import single as well as multiple modules
1.1 For importing Single module
Syntax:
import modulename
1.2 For importing Multiple modules
Syntax:
import modulename1,modulename2,modulename3
To Use function inside module
Syntax
modulename.function name

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

CREATION OF LIBRARY/PACKAGE ( 2 marks)

Steps to create and import the package


1)Create a directory named XYZ and add all the modules in the directory XYZ
Import os.mkdir(“XYZ”
2)Create a file _init_.py in the directory XYZ. _init_.py file is used to make a directory as package.This file is used
to initialse the package
3)Import the package named XYZ and use the attributes in some other program
Locating Modules
Python interpreter searches for module in the following sequences

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

1. What is the difference between 'w' and 'a' modes ?


2. What are the advantages of using binary file? (BINARY file is unreadable and open and close through a
function only.)
3. Write a statement to open a binary file name sample.dat in read mode and the file sample.dat is placed
in a folder ( name school) existing in c drive.
4. Which of the following function returns a list datatype
(a) d=f.read() (b) d=f.read(10) (c) d=f.readline() (d) d=f.readlines()

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.

Short Answer Questions : 2 Marks

1. Write a single loop to display all the contents of a text file file1.txt after removing leading and trailing
WHITESPACES.

2. What is the output of the following code fragment? Explain.


out=open('output.txt','w')
out.write('hello,world!\n')
out.write('how are you')
out.close()
open('output.txt').read()

3. Read the code given below and answer the questions


f1=open('main.txt','w')
f1.write('bye')
f1.close()
if the file contains 'GOOD' before execution, what will be the content of the file after execution of the
code
47
4. Observe the following code and answer the follow
f1=open("mydata","a")
______#blank1
f1.close()
(i) What type of file is mydata
(ii) Fill in the blank1 with statement to write "abc" in the file "mydata"

5. A given text file data.txt contains :


Line1\n
\n
line3
Line 4
\n
line6
What would be the output of following code?
f1=open('data.txt')
L=f1.readlines()
print(L[0])
print(L[2])
print(L[5])
print(L[1])
print(L[4])
print(L[3])

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+

7. What would be the data types of variables data in following statements?


(i) Data=f.read( )
(ii) Data=f.read(10)
(iii) Data=f.readline()
(iv) Data=f.readlines()

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

1. for line in open(“file1.txt”):


print(line.strip())
2. The output will be
Hello,world!
How are you?
The first line of code is opening the file in write mode,the next two line writes text t file .the last line opens
the file and from that reference reads the file content.file() performs the same functions as
open().Thus,the file(“output.txt”)will give the references to open the file on which read() is applied.

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.

4. (i) Text file


(ii) f1.write(“abc”)

5. Line1
Line3
Line 6
Line 4

6. ab and a+b mode

7. (a) string (b) string (c) string (d) list

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.

Long Answer Questions : 3 Marks

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()

Ans.7 def filter (oldfile, newfile):


fin =open (oldfile, “r”)
fout= open (newfile, “w”)
while True:
text =fin.readline ()
if len(text)==0:
break
if text[0]== “@”:
continue
fout.write(text)
fin.close()
fout.close()
filter(“source.txt” , “target.txt”)

Ans. 8. import pickle


d1={'jan':31,'feb':28,'march':31,'april':30}
f=open('binfile.dat','wb+')
pickle.dump(d1,f)
d2=pickle.load(f)
print(d2)
f.close()

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.

Steps to process a FILE


(i) Determine the type of file usage: in this section we determine whether file need to be open or
not.
(ii) open the file and assign its references to a file object or file handle.
(iii) Process as required.
(iv) close the file

OPENING AND CLOSING FILES


(i) open() function is used to open a file
Syntax:
file variable/file handle=open(file_name,access mode)
Example
F= open('abc.txt,'w')
this statement opens abc.txt in write mode
Note : if file mode is not mentioned in open function then default file mode i.e 'r'
is used
(ii) close() : method of a file object flushes any unwritten information and close the file object after
which no more writing can be done
Syntax: fileobject.close()

RELATIVE AND ABSOLUTE PATH

(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.

(iii) Example of Absolute path:E:\project\myfolder\data.txt

52
FILES MODE : it defines how the file will be accessed

Text FileBinary Descr- Notes


Mode File iption
Mode
‘r’ ‘rb’ Read File must exist already ,otherwise python raises I/O error
only
‘w’ ‘wb’ Write*If the file does not exist ,file is created.
only *If the file exists, python will truncate existing data and overwrite in
tne file. So this mode must be used with caution.
‘a’ ‘ab’ append *File is in write only mode.
*if the file exists, the data in the file is retained and new data being
written will be appended to the end.
*if the file does not exist ,python will create a new file.
‘r+’ ‘r+b’ Read *File must exist otherwise error is raised.
or and *Both reading and writing operations can take place.
‘rb+’ write
‘w+’ ‘w+b’ Write *File is created if doesn’t exist.
or and *If the file exists, file is truncated(past data is lost).
‘wb+’ read *Both reading and writing operations can take place.
‘a+’ ‘a+b’ Write *File is created if does not exist.
or and *If file exists, files existing data is retained ; new data is appended.
‘ab+’ read *Both reading and writing operations can take place.

TEXT FILE HANDLING


Methods to read data from files
S. NO. Method Syntax Description
1 Read() <filehandle>.read( [n] ) Reads at most n bytes ;If no n is specified, reads the entire file.
Returns the read bytes in the form of a string .
In [11]:file 1=open(“E:\\mydata\\info.txt”)
In [12]:readInfo=file1.read(15)
In [13]:print(readInfo)#prints firt 15 #characters of file
In [14]:type(readInfo)
Out[14]:str
2 Readline( ) <filehandle>.readline([n]) Reads a line of input ;if in is specified reads at most n bytes.
Returns the read bytes in the form string ending with
in(line)character or returns a blank string if no more bytes are
left for reading in the file.
In [20]:file1 = open(“E:\\mydata\\info.txt”)
In [20]: readInfo =file1.readline()
In [22]:print (readInfo)
3 readlines() <filehandle>.readlines() Read all lines and returns them in a list
In [23]:file1 =open(“E:\\mydata\\info text”)
In [24]:readInfo =file1.readlines()
In [25]:print (readInfo)
In [26]:type (readInfo)
53
Out[26]:list
Writing data into files

S. NO Name Syntax Description


1 Write() <filehandle>.write(str1) Write string str1 to file referenced
by<filehandle>
2 Writelines() <filehandle>.writelines (L) Writes all strings in list L as lines to file
referenced by <filehandle>

BINARY FILE HANDLING


(i) In binary file data is in unreadable format and to work on binary file we have to convert the data
into readable form for read as well as write operation
(ii) Pickling refers to the process of converting the structure to a byte stream before writing to a
file.while reading the content of the file a reverse process called unpickling is used to convert the
byte stream back to the original strstrstructure
(iii) We have to import pickle module for binary file handling.
(iv) Two main method of pickle modules are- dump() and load().
(v) Syntax of dump():- dump(object,fileobject)
(vi) Syntax of load():-load(fileobject)

STANDARD FILE STREAM


We have to import module sys for standard I/O stream, the standard stream available in python are :
(i) standard input stream(sys.stdin)
(ii) standard output stream(sys.stdout)
(iii) standard error stream(sys.stderr)

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.

2. As the given output is:-


Hello func2
yes func1
Hello func2
Yes func1
………… and so on .
Reason:- as the function will go on all the memory will be used up, and the system will eventually show
Run time error.

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.

12. log(n) 13. a 14. c 15. b

16. The <__init__.py> module can help in fulfilling following objectives.


It makes Python interpret directories as containing packages by excluding the ones with a common
name such as string.
It grants a programmer with the control to decide which directory is a package and which is not.
However, the <__init__.py> can also be an empty file. It can then help in executing the initialization code
for a package or setting the <__all__> variable.

17. def recursive_list_sum(data_list):


total = 0
for element in data_list:
if type(element) == type([]):
total = total + recursive_list_sum(element)
else:
total = total + element

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

ANSWERS: IDEA OF ALGORITHMIC EFFICIENCY

1. An algorithm is a step-by-step method of solving a problem.


2. Performance of an algorithm depends on many internal and external factors
3. Internal factors : (a) Time required to run (b) Space required to run
External factors: (a) Size of the input to the program (b) Speed of the computer
(c) Quality of the compiler
4. Computation means to solve problems using an algorithm and Complexity involves the study of factors
to determine how much resource is sufficiently necessary for this algorithm to run efficiently .
5. import time
def natural_sum(n):
start=time.time()
sum=0
for x in range(1,n+1):
sum=sum+x
end=time.time()
time_taken=end-start
print("Sum is",sum)
print("Time Taken:",time_taken)
natural_sum(100000)
import time
start=time.time()
def natural_sum(n):
return(n*(n+1)/2)
end=time.time()
print(natural_sum(100000))
time_taken=end-start
print("Time Taken:",time_taken)

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

1. What is Data Visualization?


2. Write the syntax to import Pyplot library?
3. Name some commonly used chart types?
4. Name the functions that are used to create line chart
5. Name the functions that are used to create Bar chart
6. Name the functions that are used to create Pi chart
7. Write a Python program to draw a line with suitable label in the x axis, y axis and a title.
8. Write a Python program to draw a line using given axis values with suitable label in the x axis , y axis and
a title.

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')

ANSWERS : Data Visualization Using Pyplot ( 3 marks questions )


1. General term that describe any effort to help people understand significance of data by placing it in
visual context

2. import matplotlib.pyplot

3. Line chart,Bar chart ,Pi chart


4. matplotlib.pyplot.plot()
5. matplotlib.pyplot.bar()
6. matplotlib.pyplot.pie()

7. import matplotlib.pyplot as plt


61
X =range(1,50)
Y =[value *3for value in X]
print("Values of X:")
print(*range(1,50))
print("Values of Y (thrice of X):")
print(Y)
plt.plot(X, Y)
plt.xlabel('x - axis')
plt.ylabel('y - axis')
plt.title('Draw a line.')
plt.show()
8.
import matplotlib.pyplot as plt
x =[1,2,3]
y =[2,4,1]
plt.plot(x, y)
plt.xlabel('x - axis')
plt.ylabel('y - axis')
plt.title('Sample graph!')
plt.show()
9.
import matplotlib.pyplot as plt
x =[1,4,5,6,7]
y =[2,6,3,6,3]
plt.plot(x, y, color='red', linestyle='dashdot', linewidth =3,
marker='o', markerfacecolor='blue', markersize=12)
plt.ylim(1,8)
plt.xlim(1,8)
plt.xlabel('x - axis')
plt.ylabel('y - axis')
plt.title('Display marker')
plt.show()
10.
import matplotlib.pyplot as plt
import numpy as np x=[1,2,3,4,5] y=[65,45,76,26,80]
plt.plot(x,y) plt.xlabel("X axis")
plt.ylabel("Y axis ")
plt.title("Graph for x=[1,2,3,4,5] y=[65,45,76,26,80]")
plt.show()
11.
import matplotlib.pyplot as plt
import numpy as np
x=np.arange(-5,6,1) y=2*x+5
plt.plot(x,y)
plt.xlabel("X axis")
plt.ylabel("Y axis ")

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)

1. Write a program for linear search in a list.


2. Write a program for bubble sort.
3. Write InsertQ(Customer) and DeleteQ(Customer) methods/functions in Python to add a new Customer
and delete a Customer from a list of Customer names, considering them to act as insert and delete
operations of the Queue
4. Write PushOn(Book) and Pop(Book) methods/functions in Python to add a new Book and delete a Book
from a list of Book titles, considering them to act as push and pop operations of the Stack data
structure.

Answer

1. Write a program for linear search in a list.


L=eval(input("Enter the elements: "))
n=len(L)
item=eval(input("Enter the element that you want to search : "))
for i in range(n):
if L[i]==item:
print("Element found at the position :", i+1) ues
break
else:
print("Element not Found")

2. Write a program for bubble sort.


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]:
t=L[i]
L[i]=L[i+1]
L[i+1]=t
print("The sorted list is : ", L)

3. Program to insert Queue.


def InsertQ(queue):
a=input(“Enter customer name :”)
queue.append(a)
def DeleteQ(queue):
if (queue==[]):
print (“Queue is empty…..”)
else:
print(“Deleted element is”, queue[0])
65
del queue[0]

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())

Notes on Data Structure

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.

OPERATION ON DATA STRUCTURE:


There are various types of operations can be performed with data structure:
1. Traversing: Accessing each record exactly once.
2. Insertion: Adding a new element to the structure.
3. Deletion: Removing element from the structure.
4. Searching: Search the element in a structure.
5. Sorting: Arrange the elements in ascending and descending order.
6. Merging: Joining two data structures of same type. (not covered in syllabus)

LISTS IN DATA STRUCTURE: ( 2 marks )


a. Traversing 1-D array (List):
L=[10,20,30,40,50]
66
n=len(L)
for i in range(n): print(L[i])

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

(i) Linear Search: It is a simple searching technique.


Program:
L=eval(input("Enter the elements: ")) n=len(L)
item=eval(input("Enter the element that you want to search : ")) for i in range(n):
if L[i]==item:
print("Element found at the position :", i+1)
break
else:
print("Element not Found")

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

(ii) Binary Search:


Program:
def BinarySearch(LIST,n,item): LB=0
UB=n-1
while LB<=UB:
mid=int((LB+UB)/2)
if item<LIST[mid]:
UB=mid-1
elif item>LIST[mid]:
LB=mid+1 else:
return mid
else:
return -1
L=eval(input("Enter the elements in sorted order: "))
size=len(L)
element=int(input("Enter the element that you want to search :")) found=BinarySearch(L,size,element)
if found>=0:
print(element, "Found at the position : ",found+1)
else:
print("Element not present in the list")

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

Linear Search Vs Binary Search: ( questions for 2 marks)


Linear Search Binary Search
Access of elements sequentially. Access of elements randomly.
Elements may or may not be in sorted order. Elements must be in sorted order i.e. ascending
or descending order
Takes more time to search an element. Takes less time to search an element.

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

print("The sorted list is :",L)


OUTPUT:
Enter the elements: [45, 11, 78, 2, 56, 34, 90, 19]
The sorted list is : [2, 11, 19, 34, 45, 56, 78, 90]

DATA STRUCTURE-II (STACK AND QUEUE)


STACK IN PYTHON:

• Stack is a linear data structure.


• Stack is a list of elements in which an element may be inserted or deleted only at one end, called the
TOP of the stack.
• It follows the principle Last In First Out (LIFO).
• There are two basic operations associated with stack:
 Push : Insert the element in stack
 Pop : Delete the element from stack

69
Chapter: 8 Computer Network
Multiple Choice Questions : 1 Marks

1. Which of the following is used in star topology?


(a) Hub (b) Gateway (c) Both (d) None of the above
2. Which of the following is the most expensive?
(a) Fibre optics (b) Twisted Pair (c) Coaxial (d) None of the above
3. Which of the following works even if one of the nodes fail?
(a) Star (b) Bus (c) Ring (d) None of the above
4. Which of the following is confined to a building or a smaller location?
(a) LAN (b) WAN (c) MAN (d) None of the above
5. Computer Network is
(a) Collection of Hardware components and computers
(b) Interconnected by Communication channels
(c) Sharing of resources and information
(d) All of the above
6. Protocols are
(a) Agree on how communication components and devices are to communicate.
(b) Logical communication channels for transferring data.
(c) Physical communication channels used for transferring data.
(d) None of above
7. Two devices are in network if
(a) A process in one device is able to exchange information with a process in another device.
(b) A process is running on both devices.
(c) The process running of different devices are of same type.
(d) None of the mentioned
8. In Peer to Peer network ,each computer in a network is referred as
(a) Server (b) Client (c) Peer (d) Sender
9. Which of these is the correct definition of a router?
(a) Forwards data packets along a network
(b) Corrects errors that are found in data packets
(c) A type of transmission media that provides the greatest bandwidth.
(d) A server within a network
10. Which of the following is the fastest media of data transfer?
(a) Co-axial Cable (b) Untwisted wire (c) Telephone lines (d) Fibre Optic
11. A Device that forwards data packet from one network to another is called a
(a) Bridge (b) Router (c) Hub (d) Gateway
12. A …………………………….is a network point that acts as an entrance to another network.
(a) Repeater (b) Hub (c) Gateway (d) Bridge
13. Hub is a
(a) Broadcast device (b) Unicast device (c) Multicast device (d) None of the above
14. Switch is a

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

Fill in the blanks


1. WAN stands for……………………………
2. …………..is a protocol that allows to send /upload email message from local computer to an email server.
3. ………….is a protocol that allows user to download E Mail message from mail server to local computer.
4. FTP stands for…………………
5. Every Computer on the Internet has a unique……………………….
6. CSMA/CA stands for………………………….
7. A Network card attached to a host so as to establish network connections , is called ……………
8. A……………is a Computer on Network ,dedicated to processing client requests.
9. The Physical address assigned by NIC manufacturer is called …………………address.
10. Special condition in a Network where more data packets are coming to network devices than they can
handle ,is called……………………

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.

VERY SHORT ANSWER QUESTIONS

1. Define a Computer Network.


2. What are the uses of Microwave signal?
3. What is Gateway?
4. What is Bridge?
5. Define the following:(i) Hub (ii) Switch
6. What is Ethernet?
7. What is E-mail ? what are its advantages?
8. What are repeaters?
9. What are routers?
10. What is the purpose of using FTP?
11. Name two transmission media for networking?
12. What is MAC address?
13. What is IoT?
14. What is Bridge?
15. What is internetwork?
16. What is CSMA/CA?
17. What is TCP?
18. What is congestion?
19. What is DNS?
20. What is the use of Whois networking command?

SHORT ANSWER QUESTIONS

1. What are major types of networks ? Explain.


2. What are the enabling technologies of IoT system?
3. What is the difference between working of switches and routers?
4. What is collision in a network? How does it impact the performance of a network?
5. What are the basic methods of checking errors in the data being transmitted over networks?
6. What are checksum?
7. What are protocols ?What is the significance of protocols in network?
8. Write a short notes on IPv4 addressing.
9. Discuss how IPv4 is different from IPv6.
10. What is Ping network tool?
11. What is VoIP?
12. What do you mean by IP address ? How is it useful in computer Security?
13. What is Server? What is its role/
14. What are the functions of Bridge?
15. What are the metrics used in determining the best path for a routing 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

Center to center distances between various Computer blocks:


Alpha to Beta 50 m
Beta to Gama 150 m
Gama to Theta 25 m
Alpha to Theta 170 m
Beta to Theta 125 m
Alpha to Gama 90 m

Number of Computer in:


Alfa 25
Beta 20
Gama 40
Theta 60

(f1) Suggest a cable layout to connect the Computer Block.


(f2) Suggest the most suitable place to house the server.
(f3) Suggest the placement of Hub/Switch with justification.
(f4) The organization is planning to link its office to a hilly region where cable connection is not feasible.
Suggest an economic way to connect it with reasonably high speed

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

1. MySQL provides a dummy table named................................ .


2. Mr.Ramesh has created a table SUPPLIER in the database. One of the fields in the table is city. Write the
command to display city by avoiding duplicate values.
3. Patterns in MySQL are described using two special wild card characters such as................................
and.................................
4. The rows of the table (relation) are referred to as.................................
5. .................... Command helps to see the structure of a table/relation.
(a)Show (b) Select (c) Describe (d) Order by
6. ................. is known as range operator in MYSQL.
(a) IN (b) DISTINCT (c) IS (d) BETWEEN
7. .................. command helps to open an existing database
(a) Use (b) Open (c) Distinct (d) Select
8. Which operator is used to impose Condition Based on a list
9. Identify the key which is a set of one or more attributes that can uniquely identify tuples within the
relation
10. Which function returns the total number of rows including duplicates and NULL values?
11. Write a query to Search NULL in a table
12. Which keyword is used to select rows containing columns that match a wildcard pattern?
13. Which clause is used to select specific rows in a table?
14. Which function is used to check whether mysql python connection is successfully established?
15. A table "Animals" in a database has 3 columns and 10 records. What is the degree and cardinality of this
table?
16. Which of the following is NOT a part of DDL Commands in MySql
(a) DROP (b) SELECT (c) MODIFY (d) CREATE
17. A table ACCOUNTS in a database has 14 columns and 4 records. What is its degree if 2 more rows are
added into the table?
(a) 14 (b) 16 (c) 8 (d) None of these
18. What is the default sort order of ORDER BY clause?
19. Which clause is used to combine all the records of a table that have identical values in a particular
field?
20 What is Data Dictionary?
21. What do you mean by data redundancy?
22. Which function do use for executing a SQL query?
23. Which package must be imported to create a database connectivity application?
24. Can a table have multiple primary keys?
25. What is resultset?

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.

Short Answer Questions : 2 Marks

1. What is the difference between commit and rollback command ?


Ans : COMMIT command permanently saves the changes made during the transaction execution. ROLLBACK
command undoes the changes made during transaction execution.

2. Differentiate char and varchar data types?


Ans-
Char Varchar
(i)It specifies a fixed length character string. (i)It specifies variable length string
(ii) The CHAR datatype can store a (ii) The VARCHAR datatype can store a
maximum of 0 to 255 characters. maximum number up to 65,535.
(iii) If a value entered is shorter than its (iii) No blanks are added if the length is shorter
length x, then blanks are added. than the maximum length, x.
(iv) Search operation is faster with CHAR (iv) Search operation works slower in VARCHAR
datatype column. datatype column as compared to CHAR type.

3. Write the difference between DDL and DML commands.


Ans –
DDL DML
1. DDL stands for Data Definition Language. 1. DML stands for Data Manipulation
Language.
2.These commands allow us to perform 2. These commands are used to manipulate
tasks related to data definition, i.e., related data, i.e., records or rows in a table or
to the structure of the database objects relation.
(relations/databases).
3. The examples of DDL commands are 3. The examples of DML commands are
Create, Alter, Drop, Grant, Revoke, etc. Insert into, Update, Delete, Select, etc.
4. DDL is not further classified 4.DML commands are further classified into
two types:
Procedural DMLs
Non-Procedural DMLs

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.

6. Differentiate between WHERE and HAVING clause?


Ans : WHERE clause is used to select particular rows that satisfy the condition where having clause is used in
connection with the aggregate function GROUP BY clause. FOR EXAMPLE-
select * from student where marks >80;
Select * from student group by stream having marks>90;

7. What is a database system? Write its advantages?


Ans : A database is a collection of interrelated data and a database system is basically a computer based
record keeping system.

Advantages
(i) Reduced data redundancy
(ii) Controlled data inconsistency
(iii) Shared data
(iv) Secured data
(v) Integrated data

8. Explain views and also writes its utility.


Ans : A view is a virtual table that doses not really exists rather it is generated from an already existing table. It is
a kind of table whose contents are taken upon other tables depending upon a given query condition. It provides
an excellent way to users show some useful information not all information of the table.

9. Differentiate primary key and unique key constraints.


Primary key constraints Unique key constraints
(i)Only one primary key constraints allowed (ii) Unique constraints can be more than
for a table one
(ii) Does not allow null values (ii) allow null values

10. Differentiate between fetchone() and fetchall()


Ans: 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.
fetchall() − It fetches all the rows in a result set. If some rows have already been extracted from the result
set, then it retrieves the remaining rows from the result set.

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()

12. Differentiate between Primary key and Foreign Key.


Ans: Primary key uniquely identify a record in the table. It is a field in the table that is primary key in another
table.
(ii) Primary Key can't accept null values. Foreign key can accept multiple null value
(iii) By default, Primary key is clustered index and foreign key do not automatically create an index data in
the database table is physically organized in the sequence of clustered index. clustered or non-clustered.
You can manually create an index on foreign key.
(iv) We can have only one Primary key in a table. We can have more than one foreign key in a table.

13. Differentiate between Alternate key and candidate?


Ans : Alternate key is a key that can be work as a primary key. Basically it is a candidate key that currently is not primary
key. e.g. in the table stud(id,rollno,fname,lname,email) rollno and email becomes alternate keys when we define id
as primary key.

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

1001 Relay 100x4 16 10000 23-Jan-2004


1002 High jump 10 12000 12-Dec-2003
1003 Shot Put 12 8000 14-Feb-2004
1005 Long Jump 12 9000 01-Jan-2004
1008 Discuss Throw 10 15000 19-Mar-2004

(i) select count(distinct participantsnum) from activity;


(ii) select max(scheduledate),min(scheduledate) from activity;
(iv) select sum(prizemoney) from activity;
Ans : (i) 3
(ii) 19-Mar-2004 12-Dec-2003
(iii) 54000

(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’

(v) To increase PrizeMoney by 500 for High jump activity.


Ans: Update ACTIVITY set PrizeMoney = PrizeMoney + 500 where ActivityName=’ High jump’

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.

Ans: (i) Select NO, NAME,TDATE from Travel order by NO desc;


(ii) Select Name from Travel where code=101 or code=102;
(iii) Select No,Name from Travel where Tdate between ‘2015-12-31’ and ‘2015-04-01’;
(iv) Select Max(KM),min(KM) from Travel;

(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;

Ans: i) 101 (ii) 101 (iii) 101 Vedika Volvo Bus


104 104 Tarun Ordinary Bus
105 105 John SUV
103 103 Ahmed CAR

3(a) Write a output for SQL queries ( i ) to (iii) , which are based on the tables: TRAINER and COURSE
TRAINER

TID TNAME CITY HIREDATE SALARY


101 SUNAINA MUMBAI 1998-10-15 90000
102 ANAMIKA DELHI 1994-12-24 80000
103 DEEPTI CHANDIGARH 2001-12-21 82000
104 MEENAKSHI DELHI 2002-12-25 78000
105 RICHA MUMBAI 1996-01-12 95000
106 MANIPRABHA CHENNAI 2001-12-12 69000

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’;

(i) TID TNAME


103 DEEPTI
106 MANIPRABHA

(ii) TID COUNT(*) MIN(FEES)


101 2 12000

(iii) COUNT(*) SUM(FEES)


4 65000

(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

You might also like