0% found this document useful (0 votes)
51 views23 pages

MLM Term 1

The document contains a series of questions and exercises related to Python programming, covering topics such as data types, control structures, functions, and error handling. It includes code snippets for evaluation, debugging tasks, and knowledge-based questions about Python syntax and behavior. The content is structured for educational purposes, likely aimed at students preparing for a computer science examination.
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)
51 views23 pages

MLM Term 1

The document contains a series of questions and exercises related to Python programming, covering topics such as data types, control structures, functions, and error handling. It includes code snippets for evaluation, debugging tasks, and knowledge-based questions about Python syntax and behavior. The content is structured for educational purposes, likely aimed at students preparing for a computer science examination.
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/ 23

VELAMMAL VIDYALAYA, ALAPAKKAM

SENIOR SECONDARY COMPARTMENT


COMPUTER SCIENCE (083)
MINIMUM LEARNING MATERIAL

All Chapters

1. What is the data type of Numbers = ( 4,[ 8, [9], 2.6], 5 ) ? _________________


2. What is the length of [10,[20,[30,[40,[50],60],70],80],90] ? _________________
3. What is the output
s=“CBSE 2025” S1=”my” a=56 c1='A' print(4.00/(2.0+2.0))
print(s[::-1]) S2=”string” b=a//7//4 c2='a' print(32% 3.0 )
print(s[::-2]) print print(b) diff= ord(c1)-ord(c2)
print(s[::3]) (int(s1+s2)) print(diff)
4.Evaluate the following expression and identify the correct answer.
a. 16 // (4 + 2) * 5 + 2**3 * 4 b. n 13+12%14 c. 6*2/5+5*2 d) (3-10**2+99/11)
e) not 12 > 6 and 7 < 17 or not 12 < 4 f) 2 ** 3 ** 2 g) 7 // 5 + 8 * 2 / 4 – 3
h) True and not False or False g) False and bool(15/5*10/2+1)
5. Find output for following given program
a=10 a=12 a=56 word = 'green vegetables'
b=20 print(notIDLE stands for b=a//7//4 print(word.find('g',2))
c=1 print(b) print(word.find('veg',2))
print(a !=b and not c) print(word.find('tab',4,15
))
6. What will be the value of x?
x= int(12.5 + 4/2)
7. In Python, indentation defines a block of statements.
8. L = [“abc”,[6,7,8],3,”mouse”] Perform following operations on the above list L.
i)L[3:] ii) L[: : 2] iii)L[1:2] iv) L[1][1]
9. An empty /null statement in Python is Pass
10. The break statement terminates the execution of the loop
11. Which of the following option is a core data type in the python language?
A. Dictionary B. List C. String D. d. All of the above
12. If we change one datatype to another, then it called Type casting
13. IDLE stands for Integrate Development and Learning Environment
14. Which one is not the feature of Python? Not a case-sensitive
1. Cross-platform 2. Interpreted 3. Free and Open source 4. Not a
case-sensitive
15. A program written in a high-level language is called Source code
16. Python uses a/an inverter to convert source code to object code
17. extension of the python file id .py
18. Mutable data types are list, dictionart,set
19. Immutable are integer, string, tuple
20. In Python, indentation defines a block of statements.
21. What stops the current iteration of the loop and continues to next iteration? Continue
22. A literal used in the absence of a value is None
23. The input() function always returns a value oftype. string
24. Which is valid keyword? (a) Int (b) WHILE (c) While (d) if
25. Predict the output of the following: (i) >>>print(10 or 40) (ii) >>> print(22.0//5)
26. Identify the invalid variable name from the following. Adhar@Number, none,
70outofseventy, mutable
27. Find the invalid identifier from the following
1. (a) Marks@12 (b) string_12 (c)_bonus (d)First_Name
2. (a) KS_Jpr (b) false (c) 3rdPlace (d) _rank
3. (a) Tot$balance (b) TRUE (c) 4thdata (d) break
28. Mona has written a code to input a positive integer and display all its even numbers in
descending order. Her code is having errors. Rewrite the correct code and underline the
corrections made.
n=input("Enter a positive integer: ")
for i in range(n):
if i%2:
if n%i==0:
print(i,end=' ')
29. 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)
30. Sona has written the following code to check whether number is divisible by 3. She could
not run the code successfully. Rewrite the code and underline each correction done in the
code.
x=10
for I range in
if i%3=0:
print(I)
else
pass
31. Rewrite the following code in Python after removing all syntax error(s). Underline each
correction done in the code.
Value=30
for VAL in range(0,Value)
if val%4==0:
print (VAL*4)
Elseif val%5==0:
print (VAL+3)
else
print(VAL+10)

32. Suppose str1= ‘welcome’. All the following expression produce the same result except one.
Which one?
(a) str[ : : -6] (b) str[ : : -1][ : : -6] (c) str[ : :6] (d) str[0] + str[-1]
33. Which of the following statement(s) would give an error during execution?
S=["CBSE"] # Statement 1 EM ="Blue Tick will cost $8" # statement
S+="Delhi" # Statement 2 1
S[0]= '@' # Statement 3 print( EM) # Statement
S=S+"Thank you" #Statement 4 2
(a) Statement 1 (b) Statement 2 ME = "Nothing costs more than Truth"
(c) Statement 3 (d) Statement 4 #Statement 3
EM *= 2 #
Statement 4
EM [-1: -3 : -1] += ME[ : 7] # Statement 5
(a) Statement 3 (b) Statement 4
(c) Statement 5 (d) Statement 4 and 5

33. What is the output of the following code?


S1="Computer2023” txt="cbse. sample paper 2022" s="I#N#F#O#R#M#A#T#I#C#S"
S2="2023" print(txt.capitalize()) L=list(s.split("#"))
print(S1.isdigit(), print(L)
S2.isdigit())
S="Hello World!" mystr = ‘Python programming is fun!’
print(S.find("Hello")) mystr = mystr.partition('pro')
mystr='$'.join(mystr)

34. Predict the output of the following code:


Mydict={ } Mydict[(1,2,3)]=12 S="UVW" L=[10,20,30] D={ } D={ }
Mydict[(4,5,6)]=20 N=len(S) T=("Raj","Anu","Nisha","Lisa")
Mydict[(1,2)]=25 total=0 for i in range(N): for i in range(1,5):
for i in Mydict: D[L[i]]=S[i] D[i]=T[i-1]
total=total+Mydict[i] for K,V in D.items(): print(D)
print(total) print(K,V,sep="*",end=",")
print(Mydict)
d1 = {"name": "Aman", "age": D1= {"A":12, "B": 6, "C" : 50, "D" : 70} d1 = {"name": "Aman", "age":
26} print (50 in D1,"C" in D1,sep="#") 26}
d2 = {27:'age','age':28} d2 = {27:'age','age':28}
d1.update(d2) d1.update(d2)
print(d1.values()) print(d1.values())
FUNCTIONS

35. A variable created or defined in a function body is known as… local

36. When you use multiple type argument in function then default argument take place At
end
37. A Function that does not have any return value is known as void or non fruitful
38. The values being passed through a function call statements are called Actual parameter
39. If a function doesn’t have a return statement, which of the following does the function
return? None
40. How many types of arguments are there in function? 3
41. Predict the output of the Python code given below:
def inner_1(a, b): def hello():
X=a+b a=['MDU','MS','CGL','TBM']
b=b+a k=-1
print(a, "@", b) for i in ['MDU','MS','CGL','TBM'][:-2]:
return a if i in ['A','E','I','O','U']:
def inner_2(a, b): a[k]=['MDU','MS','CGL','TBM'][k]
X = 100 k+=1
X=a+b else:
a=a+b a[k]=['MDU','MS','CGL','TBM'][k]
b=a-b k-=1
print(a, "@", b) print(a)
return b hello()
def process_strings():
def OUTER(Y, ch):
words = ['Python', 'Java', 'C++', 'JavaScript']
global X, NUM
result = ['', '', '', '']
Y=Y+X
index = 0
X=X+Y
for word in words:
print(X, "@", Y)
if word[-1] in ['n', 't']:
if ch == 1:
result[index] = word.upper() index += 1
X = inner_1(X, Y)
else:
print(X, "@", Y)
result[index] = word.lower() index -= 1
elif ch == 2:
print(result)
NUM = inner_2(X, Y)
process_strings()#calling function

X, NUM = 100, 1
OUTER(NUM, 1)
OUTER(NUM, 2)
print(NUM, "@", X)
L = [5,10,15,1] def Facto(x):
G=4 a,b =None, None
def Change(X): for i in range(2,x//2):
global G if x%i==0:
N=len(X) if a is None:
for i in range(N): a=i
X[i] += G else:
Change(L) b = i break
for i in L: return a,b
print(i,end='$') S=Facto(4)
print(S)

42. Predict the output of the code given below:


def Convert(Old): def div5(n):
l=len(Old) if n%5==0:
New=" " return n*5
for i in range(0,1): else:
if Old[i].isupper(): return n+5
New=New+Old[i].lower() def output(m=5):
elif Old[i].islower(): for i in range(0,m):
New=New+Old[i].upper() print(div5(i),'@',end=" ")
elif Old[i].isdigit(): print('\n')
New=New+"*"
else: output(7)
New=New+"%" output()
return New output(3)

Older="InDIa@2022";
Newer=Convert(Older)
print("New String is: ", Newer)
def Quo_Mod (L1): def determine(s):
L1.extend([33,52]) d={"UPPER":0,"LOWER":0}
for i in range(len(L1)): for c in s:
if L1[i]%2==0: if c.isupper( ):
L1[i]=L1[i] /5 d["UPPER"]+=1
else: elif c.islower( ):
L1[i]=L1[i]%10 d["LOWER"]+=1
L=[100,212,310] else:
print(L) pass
Quo_Mod(L) print("Original String:",s)
print(L) print("Upper case count:", d["UPPER"])
print("Lower case count:", d["LOWER"])
determine("These are HAPPY Times")
Knowledge based questions
43. What is the output of the below program?
def sayHello():
print('Hello World!')
sayHello()
sayHello()
a)Hello World! and Hello World!
b)‘Hello World!’ and ‘Hello World!’
c) Hello and Hello
d)None of the mentioned

44. What is the output of the below program?


def printMax(a, b):
if a > b:
print(a, 'is maximum')
elif a == b:
print(a, 'is equal to', b)
else:
print(b, 'is maximum')
printMax(3, 4)
a) 3 b) 4 c) 4 is maximum d) None of the mentioned

45. What is the output of the below program ?


x = 50
def func(x):
print('x is', x)
x=2
print('Changed local x to', x)
func(x)
print('x is now', x)
a) x is now 50 b) x is now 2
c) x is now 100 d) None of the mentioned
46. What is the output of the below program?
x = 50
def func():
global x
print('x is', x)
x=2
print('Changed global x to', x)
func()
print('Value of x is', x)
a)x is 50
Changed global x to 2 Value of x is 50
b)x is 50
Changed global x to 2 Value of x is 2
c) x is 50
Changed global x to 50 Value of x is 50
d)None of the mentioned
47. What is the output of below program?
def say(message, times = 1):
print(message * times)
say('Hello')
say('World', 5)
a)Hello WorldWorldWorldWorldWorld
b)Hello and World 5
c) Hello and World,World,World,World,World
d)Hello and HelloHelloHelloHelloHello
48.What is the output of below program?
def maximum(x, y):
if x > y:
return x
elif x == y:
return 'The numbers are equal'
else:
return y
print(maximum(2, 3))
a) 2 b) 3 c) The numbers are equal d) None of the mentioned

49. What is the output of the below program?


def C2F(c):
return c * 9/5 + 32
print C2F(100)
print C2F(0)
a) 212 and 32 b) 314 and 24
c) 567 and 98 d) None of the mentioned

50.What is the output of the below program?


def power(x, y=2):
r=1
for i in range(y):
r=r*x
return r
print power(3)
print power(3, 3)
a) 212 and 32b) 9 and 27 c) 567 and 98 d) None of the mentioned
51. What is the output of the following code?
def display(b, n):
while n > 0:
print(b,end="")
n=n-1
display('z',3)
a)zzz b)zz
c)An exception is executed d)Infinite loop
52What is the output of the following code?
def foo(k):
k[0] = 1
q = [0]
foo(q)
print(q)
a) [0]. ) [1]. c) [1, 0]. d) [0, 1].

53.What is the output of the code shown below?


def san(x):
print(x+1)
x=-2
x=4
san(12)
a) 13 b) 10 c) 2 d) 5
54. What is the output of the following code?
def foo():
return total + 1
total = 0
print(foo())
a) 0 b) 1 c) error d) none of the mentioned
55. What is the output of the following code?
def foo():
total += 1
total = 0
print(foo())
a) 0 b) 1 c) error d) none of the mentioned
56. What is the output of the following code?
a=10
b=20
def change():
global b
a=45
b=56
change()
print(a)
print(b)
a)10 and 56 b)45 and 56
c)10 and 20 d)Syntax Error
57.What is the output of the following code?
def cube(x):
return x * x * x
x=cube(3)
print(x)

a) 9 b) 3 c) 27 d) 81
58.What will be the output of the following program?
def counta(string):
count=0
for s in string:
if (s=="a"):
count +=1
return count
print("No of a =",counta("abcbabacaaa'")

a) 1 b) 3 c) 6 d) 5
59.What will be the possible output option after the execution or tne
following statements?
def abc():
global x
x=23
x=10
abc()
print(x)

a) 10 b) 23 c) Error d) None

Theory based questions


60.Define function and its advantages.
A function is a block of code which only runs when it is called. def is the keyword for
defining a function. The function name is followed by parameter(s) in (). The colon : signals
the start of the function body, which is marked by indentation.
61.Define positional, default, keyword argument
Default arguments In Python, default arguments are the values that are automatically
assigned to a function
parameter if no argument is provided during the function call.
Keyword arguments: when we call the function and explicitly assign an argument to the
parameter, the arguments are called keyword arguments. With keyword arguments, the order
in which we pass the arguments does not matter since we explicitly assign the arguments to
the variable.
Positional arguments:when you call a function and provide arguments based on the position
of the parameters, the arguments are called positional arguments.
62.Differentiate void and non void functions with an example.
Void functions are those functions that do not return any value or don't have a return
statement.
Non-void functions always return a value.
63.Differentiate local and global scope of variables with an example.
Global variable Local variable

Definition
Global variable declared local variable declared within
outside the functions the functions

They are created the They are created when the


execution of the program function starts its execution
begins and are lost when the and are lost when the
program is ended function ends

FILE HANDLING

64. The files are used to store large data such as images, video files, audio files etc.
65.Which type of the file executes faster? (a) Text File (b) CSV File (c) Binary FilE
66.. Another name of file object is File handle
67. In text file each line is terminated by a special character called ? EOL
68. . To open a file c:\ test.txt for appending data, we can give the statement:
(a) fobj = open(“c:\\test.txt”,”a”) (b) fobj = open(“c:\\test.txt”,”rw”)
(c) fobj = open(file=“c:\test.txt”,”w”) (d) fobj = open(file=“c:\\ test.txt”,”w”)
69. Which of the following statements is/are true?
(a) when we open a file for reading, if the file does not exist, an error occurs.
(b) when we open a file for writing, if the file does not exist, a new file is created.
(c) when we open a file for writing, if the file exists, the existing file is overwritten with the
new file.
(d) All of these
70. . Identify which statement may raise an error in the following program code.
1. f = open ("workfile.txt', 'r+')
2. f.write('0123456789abcdef')
3. f.write('xyz8466')
4. f.close()
5. f.seek (0)
6. f.read()
71. . To read the entire contents of the file as a string from a file object fobj, the command
should be:
(a) fobj.read(2) (b) fobj.read() (c) fobj.readline() (d) fobj.readlines()
72. What will be the output of the following snippet?
f=None
for i in range(5):
with open(“data.txt” , ”w”) as f:
if i>2:
break
print(f.close())
(a)True (b) False (c) None (d) Error
73. To read the next line of the file from a file object fobj, we use :
(a) fobj.read(2) (b) fobj.read() (c) fobj.readline() (d)
fobj.readlines()
74. To read the remaining lines of the file from object fobj, we use:
(a) fobj.read(2) (b) fobj.read() (c) fobj.readline() (d)
fobj.readlines()
75. The readlines() method returns:
(a) String (b) A list of integers (c) A list of single characters
(d) A list of strings
76. Suppose content of ‘mytext.txt’ file is:
"The key to success is focus on goals,not obstacles."
What will be the output of the following code?
file = open("mytext.txt","r")
txt = file.read()
print(file.read(10))
77.Which statement is used to change the file position to an offset value from the start?
(a) fp.seek(offset,0) (b) fp.seek(offset,1) (c) fp.seek(offset,2) (d) None
of these
78. The difference between r+ and w+ modes is expressed as?
(a) No difference
(b) In r+ mode, the pointer is initially placed at the beginning of the file and the pointer is at
the end for w+
(c) In w+ mode, the pointer is initially placed at the beginning of the file and the pointer is at
the end for r+
(d) Depends on the operating system
79.. Which of the following modes is used for both writing and reading from a binary file ?
(a) wb+ (b) w (c) wb (d) w+
80. Which statement is used to retrieve the current position within the file?
(a) fp.seek() (b) fp.tell() (c) fp.loc (d) fp.pos
81.. What happens if no arguments are passed to the seek () method?
(a) file position is set to the start of file (b) file position is set to the end of
file
(c) file position remains unchanged (d) results in an error
82. Consider the file "Rhythm.txt":
Power to Empower
What will be the output of the following code?
fileobj = open('forest.txt', 'r')
R1 = (fileobj.readline().split())
for word in R1:
for ch in range(len(word)-1,-1,-1):
print(word[ch],end='')
print(end='')
fileobj.close()

83 import pickle
Names = ["First", "second", 'third', 'fourth', 'Fifth']
lst = []
for i in range(-1, -5, -1):
lst.append(Names[i])
with open("test.dat", 'wb') as fout:
pickle.dump(lst, fout)
with open("test.dat", 'rb') as fin:
nlist = pickle.load(fin)
print(nlist)
84. What is the output of following code ?
fh = file ("poem.txt", "r")
size = len(fh.read())
print (fh.read (5))
85. It is necessary to always create the file in the same default folder where Python has been
installed. (True / False)
86. In binary file, there is no delimiter for a line. (True / False)
87. A binary file stores information in ASCII or Unicode characters. (True/False)
88. What is a data file in python?
A bunch of bytes / data stores on some storage device referred by the filename.
89. Differentiate between a text file and a binary file.
A text file stores data as ASCII/UNICODE characters where as a binary file stores data in
binary format (as it is stored in memory). Internal conversion is required in text file and
hence slower but binary file does not need any translation and faster.
90. What is the significance of a file object or a file handle?
A file object or file handle establishes a link or a reference to a file
91 .What is the use of flush( )?
Forcefully write data from buffer to file.
92. Name the methods used for reading and writing data from text file.
read( ), readline( ), readlines( ) for reading data from file and write( ), writelines( ) to write
data to a file
93. What are the various file opening modes?
r – read only, w – write only, a – append
rb – read in binary mode, w – write in binary mode, a – append in binary mode
r+ , rb+ : read and write, w+, wb+ , a+ , ab+ : write/append and read
94..What is the significance of close( )?
When a file is closed data from buffer gets written onto the file on the disk and link from file
is removed. It ensures that data is saved in the fle
95.. Write a python code to write some text to a file Lines.txt.
f=open(‘Lines.txt’,’w’)
s=input(‘Enter text ‘)
f.write(s)
f.close( )
96. Write a python code to find the size of the file in bytes, number of lines and number of
words.
f=open(‘Lines.txt’,’r’)
r=f.read( )
size=len(r)
print(‘size of file n bytes’,size)
word=r.split( )
print(‘Number of words ’,len(word))
f.seek(0)
L=f.readlines( )
print(‘Number of lines ’,len(L))
f.close( )

97.. Explain pickling and unpickling


Binary files can store more structed python objects like list, tuple, dictionary by converting
these objects into byte stream is called serialization/pickling
The process of converting byte stream to python object stream while reading the file is called
unpickling or deserialization.
98.. Assume you are reading from a text file from the beginning and you have read 10
characters. Now you want to start reading from the 50th character from the beginning. Which
function will you use to do the same?
99. Write the output of the following:
f=open("test.txt","w+")
f.write("File-Handling")
f.seek(0)
a=f.read(5)
print(a)
100. The syntax of seek() is: file_object.seek(offset [, reference_point]) What is
reference_point indicate?
(a) Reference_point indicates the starting position of the file object.
(b) Reference_point indicates the ending position of the file object.
(c) Reference_point indicates the current position of the file object.
(d) All of the above.

EXCEPTION HANDLING
101.. Errors resulting out of violation of programming language’s grammar rulesare known as
…………………….
(a) Compile time error (b) Logical error (c) Runtime error
(d) Exception
102 . An unexpected event that occurs during runtime and causes program disruption, is
called ………………………
(a) Compile time error (b) Logical error (c) Runtime error
(d) Exception
103. The errors encountered when a user violates the syntax of a programming language
while writing a code are termed as ____
(a) Compile time error (b) Logical error (c) Runtime error
(d) Exception
104. An interrupt or forced disruption that occurs when a program is run or executed is
termed as …………………………………
(a) Compile time error (b) Exception (c) Runtime error (d) Logical error

105. Which of the following keywords are not specific to exception handling?
(a) try (b) except (c) else (d) finally
106 Which block is a mandatory block in exception handling process?
(a) try (b) except (c) finally (d) else
107 Forced exceptions are indicated using which of the following keywords?
(a) try (b) except (c) finally (d) raise
108. ……………………… exception is raised when input() hits an EOF without reading any
data
109. ……………………… exception when a local or global name is not found.
110. ….………………. Exception is raised when an operation is applied to an object of wrong
type.
111. When denominator of a division expression is zero, …………. Exception is raised.
112. While accessing a dictionary, if the given key is not found, ………………. exception is
raised.
113 The code which might raise an exception is kept in ……………… block.
114 …………………… Exception is raised when the module given with import statement is
not found.
115. …………………… Exception is raised when the result of an arithmetic operation is too
large to be represented.
116. ………………………… Exception is raised when Esc , Del or Ctrl + C is pressed during
program execution and normal program flow gets disturbed.
117 …………….. and ………………. Statement is used when we think that the code might fail.
118. Exception and error are the same. (True/False)
119. All type of errors can be found during compile time (True/False)
120. A program running properly but producing wrong output is an exception. (True/False)
121. Unexpected rare condition occurring during runtime which disrupts a program’s
execution is an exception. (True/False)
122. The except block deals with the correct order of blocks in exception
handling(True/False)
123. try , except , finally is the correct order of blocks in exception handling (True/False)
124. An exception may be raised even if the program is syntactically correct. (True/False)
125. Value Error occurs due to wrong indentation in a program (True/False)
126. Which statement is/are true about exception handling?
i. There can be try block without catch block but vice versa is not possible
ii. There is no limit on the number of catch block corresponding to try block
iii. The object must be created of a specific class of which the error has occurred otherwise
runtime error will occur
127v. To execute a code with each and every run of program, the code is written in finally
block
(a) i and ii, iv (b) only iii (c) ii and iv only (d) only iiexception, if it
occurs. (True/False)
128.What is the use of a raise statement? Write a code to accept two numbers and display the
quotient. Appropriate exception should be raised if the user enters the second number
(denominator) as zero (0).
Answer

The raise statement is used to throw an exception during the execution of a program.

numerator = float(input("Enter the numerator: "))


denominator = float(input("Enter the denominator: "))
if denominator == 0:
raise ZeroDivisionError("Error: Denominator cannot be zero.")
else:
quotient = numerator / denominator
print("Quotient:", quotient)

129.Consider the code given below and fill in the blanks.


print("Learning Exceptions...")
try:
num1 = int(input("Enter the first number"))
num2 = int(input("Enter the second number"))
quotient = (num1/num2)
print("Both the numbers entered were correct")
except ...............: # to enter only integers
print("Please enter only numbers")
except ...............: # Denominator should not be zero
print("Number 2 should not be zero")
else:
print("Great .. you are a good programmer")
...............: # to be executed at the end
print("JOB OVER... GO GET SOME REST")
130..Predict the output
import math

try:
result = math.pow(2, 3, 4, 5) # pow() expects 2 arguments,
# but 4 are provided
except TypeError:
print("TypeError occurred with math.pow()")
else:
print("Result:", result)

try:
result = math.sqrt(9, 2) # sqrt() expects 1 argument,
# but 2 are provided
except TypeError:
print("TypeError occurred with math.sqrt()")
else:
print("Result:", result)

131.

What is the use of finally clause ?

The statements inside the finally block are always executed, regardless of whether an
exception has occurred in the try block or not. It is a common practice to use the finally
clause while working with files to ensure that the file object is closed.

print("Learning Exceptions...")
try:
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
quotient = (num1 / num2)
print(quotient)
print("Both numbers entered were correct")
except ValueError:
print("Please enter only numbers")
except ZeroDivisionError:
print("Number 2 should not be zero")
else:
print("Great.. you are a good programmer")
finally:
print("JOB OVER... GO GET SOME REST")
SQL
1. A pool of values wherefrom a field can draw values is called ____
2. A raw in a relation is called _______
3. The number of attribute in a relation is called its _______
4. . Collection of logically related data tables is called ________
5. A non-key attribute derived from the primary key of some other relation is called
_______
TRUE / FALSE QUESTIONS
6. The duplication of data is known as data redundancy.
7. . A table in a relational database can store empty values.
8. . Common attribute of two tables is called a foreign key.
9. The DDL commands are used to define or redefine schema objects.
10. . A primary key can store empty values in it.
11. . Which of the following is/are the DDL Statement ?
(a) Create (b) Drop (c) Alter (d) All of these [ ]
12. A Table can have __________
(a) Many primary keys and many unique keys. (b) One primary key and one unique key
(c) One primary key and many unique keys. (d) Many primary keys and one unique key.
13. Which of the following types of table constraints will prevent the entry of duplicate
rows?
(a) Unique (b) Distinct (c) Primary Key (d) Null [ ]
14. Consider the following SQL Statement. What type of statement is this ?
15. INSERT INTO instructor VALUES (10211, ‘SHREYA’ , ‘BIOLOGY’, 69000);
(a) Procedure (b) DML (c) DCL (d) DDL [ ]
16. Which of the following statements will delete all rows in a table namely mytable
without deleting the table’s structure.
(a) DELETE FROM mytable;’ (b) DELETE TABLE mytable;
(c) DROP TABLE mytable; (d) None of these. [ ]
17. Which of the following query will drop a column from a table ?
(a) DELETE COLUMN column_name; (b) DROP COLUMN column_name;
(c) ALTER TABLE table_name DROP COLUMN column_name; (d) None of these [ ]
18. Logical operator used in SQL are:
(a) AND, OR, NOT (b) &&, ||, ! (c) $,|,!
(d) None of these [ ]
19. Which of the following requirement can be implemented using a CHECK constraint?
(a) Student must be greater than 18 years old.
(b) Student must be form a BRICS Country (Brazil, Russia, India, China)
(c) Student’s roll number must exist in another table(say, namely Eligible)
d) None of these [ ]
20. The statement in SQL which allows to change the definition of a table is
(a) Alter (b) Update (c) Create (d) select
21. The statement in SQL which allows to change the definition of a table is
(a) Alter (b) Update (c) Create (d) select
22. Key to represent relationship between tables is called
(a)Primary key (b) Secondary Key (c) Foreign Key (d) None
of these
23. _____ produces the relation that has attributes of R1 and R2
(a) Cartesian product (b) Difference (c) Intersection (d) Product
24. It is better to use files than a DBMS when there are
(a)Stringent real-time requirements. (b) Multiple users wish to access the
data.
c) Complex relationships among data. (d) All of the above.
25. The conceptual model is
(a)dependent on hardware. (b)dependent on software.
(c)dependent on both hardware and software . (d)independent of both hardware
and software.
26. What is a relationship called when it is maintained between two entities?
(a) Unary (b) Binary (c) Ternary (d) Quaternary
27. Which of the following operation is used if we are interested in only
certain columns of a table?
(a) PROJECTION (b) SELECTION (c) UNION (d) JOIN
28. Which of the following is a valid SQL type?
(a) CHARACTER (b) NUMERIC (c) FLOAT (d) All of the above
29. The RDBMS terminology for a row is
(a)tuple (b) relation (c) attribute (d) degree.
30. State whether the following statement is True or False :
In MYSQL, you can write multiple statements in a single line.
31. State whether the following statement is True or False :
In MYSQL, you can change the column name using UPDATE command.
32. State whether the following statement is True or False :
In MYSQL, PRIMARY KEY and UNIQUE KEY both are the same.
33. State whether the following statement is True or False :
By default, the result of an order by clause is always displayed in ascending order.
34. Fill in the blank :
________ operator checks whether the particular condition record exists
in the table or not.
35. SELECT is a type of _________ SQL command.
36. Which MySQL function is used to get the current date and time?
(a) DATETIME( ) (b) TODAY( ) (c) DATE( )
(d) NOW( )
37. Which clause is used with "aggregate function?
a) Group by b) Select c) where d) both a
and c
38. A ____ is a query that retrieves rows from more than one table or view?
a) Start b) End c) Join d) All of these
39. Aggregate function can be used in the select list or the ___ clause of a select statement .
They cannot be used in a ____ clause?
a) Where , having b) Having, where c) Group by, having. d) Group
by, where
40. A Cartesian product is returned when ?
a) A join condition is omitted. b) A join condition is
invalid.
c) All the rows in the first table are joined to all the rows in second table.
d) All of these.
41. All Aggregate function ignore NULLs except for ____ function?
a) Distinct b) count (*) c) Average d) None of these
42. SQL applies condition on the groups through _____ clause after groups have been
formed ?
a) Group by b) with c) where d) having
43. Which of the following group function ignore NULL values?
a) MAX b) COUNT c) SUM d) All of these
44. Which SQL function is used to count the number of rows in a SQL query?
a) COUNT ( ) b) Number ( ) c) SUM( ) d)
COUNT (*)
45. . Function count ( ) is an ____ function ?
a) Single row b) Multiple rows c) Aggregate d) None
of these
46. Which of the following is not an aggregate function?
a) Avg b) Sum c) With d) Min
47. Which of the following is a SQL aggregate function?
a) Left b) Avg c) Join d)Len
48. The Sum ( ) if used in condition is used with ____ clause ?
a) Group by b) With c) Where d) Having
49. . The Where and Having clause can be used interchangeable in SELECT queries?
a) True b) False c) only in view d ) with order by
50. . What is the meaning of HAVING clause in select query?
a) To filter out the summary groups. b) To filter out the column groups.
c) To filter out the row and column values. d) None of the above.
51. For the HAVING clause which of the following phase is/are ture ?
a) Act EXACTLY like a WHERE clause.
b) Act like a WHERE clause but is used for columns rather than groups.
c) Act like a WHERE clause but is used for groups rather than rows.
d) Act like a WHERE clause but is used for rows rather than columns.
52. Consider the following statement and tell if it Ture for all cases or in specific cases.
53. Having clause is processed after the GROUP BY clause and any aggregate
functions.
a) True for all cases b) False for all cases
c) True when there is no WHERE clause. d) True only with where
clause
54. The following SQL is which type of join:
SELECT CUSTOMER.CUST_ID, ORDER.CUST_ID, NAME, ORDER _ID FROM CUSTOMER,
ORDER
Where CUSTOMER.CUST_ID = ORDER.CUST_ID;
a) Equal-join b) Natural join c) Outer join d) Cartesian
product
55. . .The following SQL is which type of join:
Select customer.cust_id, order.cust_id,name, order_id
From CUSTOMER, ORDER ;
56. a) Equal-join b) Natural join c) Outer join d) Cartesian
Product
57. Which product is returned in a join query having no join condition?
a) Equal-join b) Cartesian product c) Both (a) and (b) d) none of the
mentioned
58. .which is a Join condition that contains an equality operator ?
a)Equijoin b) Cartesian Product c) Both a and b d) None of the mentioned.
59. To compare an aggregate value in a condition,______ clause is used.
60. To create a summary of records based on the common value in a field in different rows
of the table ______ clause is used.
61. . In equi join, the join condition joins the two tables using ________operator
62. . The equi join uses ______ operator in the join condition.
63. . Aggregate function cannot be used in ______ clause of the select query.
64. In order to open a connection with MYSQL database from within Python using
65. mysql.connection package,____ function is used ?
(a) open ( ) (b) database( ) (c) connect( ) (d) connectdb( )
66. A database______ controls the connection to an actual datadabe, established
67. from within a python program?
(a) database object (b) connection object (c) fetch object (d) object
68. The set of records retrieved after executing an SQL query over an established
database connection is called ?
(a) table (b) sqlresult (c) result (d) resultset
69. A database _______ is a special control structure that facilities the rows by the row
processing of records in the retrieved resultset. ?
(a) fetch (b) table (c) cursor (d) query
70. Which of the following is not legal method for fetching records from database from
within a python program ?
(a) fetchone( ) (b) fetchwo ( ) (c) fetchall( ) (d)fetchmany( )
71. To fetch one records retrieved you may use <cursor> ______ method.
(a) fetch( ) (b) fetchone ( ) (c)fetchtuple() (d)fetchmany()
72. To fetch All records retrieved you may use <cursor> ______ method.
(a) fetch( ) (b) fetchone ( ) (c)fetchall() (d)fetchmany()
73. To run an SQL query from python program you may use <cursor> method.
(a) query() (b) execute () (c) run() (d) all of these
74. To reflect the changes made in the database permanently, you need to
<connection>._______ method.
(a) done() (b) reflect() (c) commit() (d) final()
75. Which of the following libraries may be used for connecting with a MySQL database
from a Python program?
(a) mysql.connector (b) pymysql (c) mMySQLServer (d)MySQLClient
76. After importing the connection library, first thing you do is: establish MySQL database.
(a) Cursor (b) setup (c) Resultset (d) connection
77. Identify the name of connector to establish bridge between Python and MySQL
(a) mysql.connection (b) connector (c) mysql.connect
(d)mysql.connector
78. Which function of connection is used to check whether connection to mysql is
successfully done or not?
79. import mysql.connector as msq
80. con = msq.connect( #Connection String ) # Assuming all parameter
81. required as passed
82. if _______________:
a. print(“Connected!”)
83. else:
a. print(“ Error! Not Connected”)
(a) con.connected() (b) con.isconnected()
(c) con.is_connected() (d) con.is_connect()
84. Which of the following component act as a container to hold all the data
returned from the query and from there we can fetch data one at a time?
(a) ResultSet (b) Cursor (c) Container (d) Table
85. Identify the correct statement to create cursor:
86. import mysql.connector as msq
87. con = msq.connect( #Connection String ) # Assuming all parameter
88. required as passed
89. mycursor = _________________
(a) con.cursor() (b) con.create_cursor() (c) con.open_cursor() (d)
con.get_cursor()
90. Which attribute of of cursor is used to get number of records stored in cursor
(Assuming cursor name is mycursor)?
(a) mycursor.count (b) mycursor.row_count (c) mycursor.records (d)
mycursor.rowcount
91. Which of the Symbols are used for passing parameterized query for execution to
cursor?
(a) % (b) { } (c) $ (d) Both a and b
92. Which function is used to fetch n number of records from cursor?
(a) fetch() (b) fetchone() (c) fetchmany() (d) fetchall()
93. . Which cursor function is used to send query to connection?
(a) query() (b) execute() (c) run() (d) send()
94. Fill in the blank:
95. After importing mysql.connector, first of all____ _____ is established using connect().
96. After establishing database connection, database______ is created so that the sql query
may be executed through it to obtain resultset.
97. The _________ returns how many rows have been fetched to far using various fetch
methods.
98. The running of sql query through database cursor results into all the records returned
in the form of _________.
99. A connectivity package such as________ must be imported before writing database.
connectivity Python code.

100.
STACK
45. Inspecting the value at the stack’s top without removing it. (a) peak operation
46. Choose correct output for the following sequence of operations.push(5) push(8) pop
push(2) push(5) pop pop pop push(1) pop
(a) 8 5 2 51 (b) 8 5 5 2 1 (c) 8 2 5 5 1 (d) 8 1 2 5 5
47. If a user tries to pop an empty stack, which of the mentioned condition will arise?
Underflow
48. Which of the following exception results when we try to add an element to a full stack?
Overflow
49. Which pointer is associated with a stack? Top
50. Assume a stack has size 4. If a user tries to push a fifth element to a stack, which of the
mentioned condition will arise? (a) Underflow (b) Overflow (c)Crash (d)
Successful Insertion
51. LIFO -- Last in First Out
52. Which of the following is not an application of stack in real-life?
(a) Pile of clothes in an almirah
(b) Multiple chairs in a vertical pile
(c) Persons buying movie tickets from a counter
(d) on wrist
53. What is the name of a data structure in which insertion and deletion is done from one end
only, usually referred to as TOP. (a) QUEUE (b) STACK (c) LISTS (d)
DICTIONARY
54. Which of the following are two basic operations performed on a stack for insertion and
deletion of elements?
(a) INSERT and DELETE (b) ADD and REMOVE (c) PUSH and POP (d) APPEND and
DELETE
55. Predict the output of the following Python code.
V = list( )
V.append('Cha')
V.append('Bala')
V1 = V.pop()
V2 = V.pop()

V3 = V.pop()

print(V1, V2, V3)

You might also like