Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Download as pdf or txt
Download as pdf or txt
You are on page 1of 123

Python MCQ

1) What is the maximum possible length of an identifier?

a. 16
b. 32
c. 64
d. None of these above

Answer: (d) None of these above

Explanation: The maximum possible length of an identifier is not defined in the python language. It can be of any
number.

2) Who developed the Python language?

a. Zim Den
b. Guido van Rossum
c. Niene Stom
d. Wick van Rossum

Answer: (b) Guido van Rossum

Explanation: Python language was developed by Guido van Rossum in the Netherlands.

3) In which year was the Python language developed?

a. 1995
b. 1972
c. 1981
d. 1989

Answer: (d) 1989

Explanation: Python language was developed by Guido van Rossum in 1989.


4) In which language is Python written?

a. English
b. PHP
c. C
d. All of the above

Answer: (b) C

Explanation: Python is written in C programming language, and it is also called CPython.

5) Which one of the following is the correct extension of the Python file?

a. .py
b. .python
c. .p
d. None of these

Answer: (a) .py

Explanation: ".py" is the correct extension of the Python file.

6) In which year was the Python 3.0 version developed?

a. 2008
b. 2000
c. 2010
d. 2005

Answer: (a) 2008

Explanation: Python 3.0 version was developed on December 3, 2008.

7) What do we use to define a block of code in Python language?

a. Key
b. Brackets
c. Indentation
d. None of these

Answer: (c) Indentation


Explanation: Python uses indentation to define blocks of code. Indentations are simply spaces or tabs used as an
indicator that is part of the indent code child. As used in curly braces C, C++, and Java.

8) Which character is used in Python to make a single line comment?

a. /
b. //
c. #
d. !

Answer: (c) #

Explanation: "#" character is used in Python to make a single-line comment.

9) Which of the following statements is correct regarding the object-oriented programming concept in Python?

a. Classes are real-world entities while objects are not real


b. Objects are real-world entities while classes are not real
c. Both objects and classes are real-world entities
d. All of the above

Answer: (b) Objects are real-world entities while classes are not real

Explanation: None

10) Which of the following statements is correct in this python code?

class Name:
def __init__(javatpoint):
javajavatpoint = java
name1=Name("ABC")
name2=name1
a. It will throw the error as multiple references to the same object is not possible
b. id(name1) and id(name2) will have same value
c. Both name1 and name2 will have reference to two different objects of class Name
d. All of the above
Answer: (b) id(name1) and id(name2) will have same value

Explanation: "name1" and "name2" refer to the same object, so id(name1) and id(name2) will have the same value.

11) What is the method inside the class in python language?

a. Object
b. Function
c. Attribute
d. Argument

Answer: (b) Function

Explanation: Function is also known as the method.

12) Which of the following declarations is incorrect?

a. _x = 2
b. __x = 3
c. __xyz__ = 5
d. None of these

Answer: (d) None of these

Explanation: All declarations will execute successfully but at the expense of low readability.

13) Why does the name of local variables start with an underscore discouraged?

a. To identify the variable


b. It confuses the interpreter
c. It indicates a private variable of a class
d. None of these

Answer: (c) It indicates a private variable of a class

Explanation: Since there is no concept of private variables in Python language, the major underscore is used to
denote variables that cannot be accessed from outside the class.
14) Which of the following is not a keyword in Python language?

a. val
b. raise
c. try
d. with

Answer: (a) val

Explanation: "val" is not a keyword in python language.

15) Which of the following statements is correct for variable names in Python language?

a. All variable names must begin with an underscore.


b. Unlimited length
c. The variable name length is a maximum of 2.
d. All of the above

Answer: (b) Unlimited length

Explanation: None

16) Which of the following declarations is incorrect in python language?

a. xyzp = 5,000,000
b. x y z p = 5000 6000 7000 8000
c. x,y,z,p = 5000, 6000, 7000, 8000
d. x_y_z_p = 5,000,000

Answer: (b) x y z p = 5000 6000 7000 8000

Explanation: Spaces are not allowed in variable names.

17) Which of the following words cannot be a variable in python language?

a. _val
b. val
c. try
d. _try_

Answer: (c) try


Explanation: "try" is a keyword.

18) Which of the following operators is the correct option for power(ab)?

a. a ^ b
b. a**b
c. a ^ ^ b
d. a ^ * b

Answer: (b) a**b

Explanation: The power operator in python is a**b, i.e., 2**3=8.

19) Which of the following precedence order is correct in Python?

a. Parentheses, Exponential, Multiplication, Division, Addition, Subtraction


b. Multiplication, Division, Addition, Subtraction, Parentheses, Exponential
c. Division, Multiplication, Addition, Subtraction, Parentheses, Exponential
d. Exponential, Parentheses, Multiplication, Division, Addition, Subtraction

Answer: (a) Parentheses, Exponential, Multiplication, Division, Addition, Subtraction

Explanation: PEMDAS (similar to BODMAS).

20) Which one of the following has the same precedence level?

a. Division, Power, Multiplication, Addition and Subtraction


b. Division and Multiplication
c. Subtraction and Division
d. Power and Division

Answer: (b) Division and Multiplication

Explanation: None

21) Which one of the following has the highest precedence in the expression?

a. Division
b. Subtraction
c. Power
d. Parentheses
Answer: (d) Parentheses

Explanation: PEMDAS (similar to BODMAS).

22) Which of the following functions is a built-in function in python language?

a. val()
b. print()
c. print()
d. None of these

Answer: (b) print()

Explanation: The print() function is a built-in function in python language that prints a value directly to the system.

23) Study the following function:

round(4.576)

What will be the output of this function?

a. 4
b. 5
c. 576
d. 5

Answer: (d) 5

Explanation: The round function is a built-in function in the Python language that round-off the value (like 3.85 is
4), so the output of this function will be 5.

24) Which of the following is correctly evaluated for this function?

pow(x,y,z)
a. (x**y) / z
b. (x / y) * z
c. (x**y) % z
d. (x / y) / z
Answer: (c) (x**y) % z

25) Study the following function:

all([2,4,0,6])

What will be the output of this function?

a. False
b. True
c. 0
d. Invalid code

Answer: (a) False

Explanation: If any element is zero, it returns a false value, and if all elements are non-zero, it returns a true value.
Hence, the output of this "all([2,4,0,6])" function will be false.

26) Study the following program:

x=1
while True:
if x % 5 = = 0:
break
print(x)
x+=1

What will be the output of this code?

a. error
b. 2 1
c. 0 3 1
d. None of these
Answer: (a) error

Explanation: Syntax error, there should not be a space between + and =.

27) Which one of the following syntaxes is the correct syntax to read from a simple text file stored in ''d:\java.txt''?

a. Infile = open(''d:\\java.txt'', ''r'')


b. Infile = open(file=''d:\\\java.txt'', ''r'')
c. Infile = open(''d:\java.txt'',''r'')
d. Infile = open.file(''d:\\java.txt'',''r'')

Answer: (a) Infile = open(''c:\\scores.txt'', ''r'')

Explanation: None

28) Study the following code:

x = ['XX', 'YY']
for i in a:
i.lower()
print(a)

What will be the output of this program?

a. ['XX', 'YY']
b. ['xx', 'yy']
c. [XX, yy]
d. None of these

Answer: (a) ['XX', 'YY']

Explanation: None
29) Study the following function:

import math
abs(math.sqrt(36))

What will be the output of this code?

a. Error
b. -6
c. 6
d. 6.0

Answer: (d) 6.0

Explanation: This function prints the square of the value.

30) Study the following function:

any([5>8, 6>3, 3>1])

What will be the output of this code?

a. False
b. Ture
c. Invalid code
d. None of these

Answer: (b) True

Explanation: None

31) Study the following statement:

>>>"a"+"bc"

What will be the output of this statement?


a. a+bc
b. abc
c. a bc
d. a

Answer: (b) abc

Explanation: In Python, the "+" operator acts as a concatenation operator between two strings.

32) Study the following code:

>>>"javatpoint"[5:]

What will be the output of this code?

a. javatpoint
b. java
c. point
d. None of these

Answer: (c) point

Explanation: Slice operation is performed on the string.

33) The output to execute string.ascii_letters can also be obtained from:?

a. character
b. ascii_lowercase_string.digits
c. lowercase_string.upercase
d. ascii_lowercase+string.ascii_upercase

Answer: (d) string.ascii_lowercase+string.ascii_upercase

Explanation: None
34) Study the following statements:

>>> str1 = "javat"


>>> str2 = ":"
>>> str3 = "point"
>>> str1[-1:]

What will be the output of this statement?

a. t
b. j
c. point
d. java

Answer: (a) t

Explanation: The correct output of this program is "t" because -1 corresponds to the last index.

35) Study the following code:

>>> print (r"\njavat\npoint")

What will be the output of this statement?

a. java
point
b. java point
c. \njavat\npoint
d. Print the letter r and then javat and then point

Answer: (c) \njavat\npoint

Explanation: None
36) Study the following statements:

>>> print(0xA + 0xB + 0xC)

What will be the output of this statement?

a. 33
b. 63
c. 0xA + 0xB + 0xC
d. None of these

Answer: (a) 33

Explanation: A, B and C are hexadecimal integers with values 10, 11 and 12 respectively, so the sum of A, B and C
is 33.

37) Study the following program:

class book:
def __init__(a, b):
a.o1 = b

class child(book):
def __init__(a, b):
a.o2 = b

obj = page(32)
print "%d %d" % (obj.o1, obj.o2)

Which of the following is the correct output of this program?

a. 32
b. 32 32
c. 32 None
d. Error is generated
Answer: (d) Error is generated

Explanation: Error is generated because self.o1 was never created.

38) Study the following program:

class Std_Name:
def __init__(self, Std_firstName, Std_Phn, Std_lastName):
self.Std_firstName = Std_firstName
self. Std_PhnStd_Phn = Std_Phn
self. Std_lastNameStd_lastName = Std_lastName

Std_firstName = "Wick"
name = Std_Name(Std_firstName, 'F', "Bob")
Std_firstName = "Ann"
name.lastName = "Nick"
print(name.Std_firstName, name.Std_lastName)

What will be the output of this statement?

a. Ann Bob
b. Ann Nick
c. Wick Bob
d. Wick Nick

Answer: (d) Wick Nick

Explanation: None

39) Study the following statements:

>>> print(ord('h') - ord('z'))

What will be the output of this statement?

a. 18
b. -18
c. 17
d. -17

Answer: (b) -18

Explanation: ASCII value of h is less than the z. Hence the output of this code is 104-122, which is equal to -18.

40) Study the following program:

x = ['xy', 'yz']
for i in a:
i.upper()
print(a)

Which of the following is correct output of this program?

a. ['xy', 'yz']
b. ['XY', 'YZ']
c. [None, None]
d. None of these

Answer: (a) ['xy', 'yz']

Explanation: None

41) Study the following program:

i = 1:
while True:
if i%3 == 0:
break
print(i)

Which of the following is the correct output of this program?

a. 1 2 3
b. 3 2 1
c. 1 2
d. Invalid syntax

Answer: (d) Invalid syntax

Explanation: Invalid syntax, because this declaration (i = 1:) is wrong.

42) Study the following program:

a=1
while True:
if a % 7 = = 0:
break
print(a)
a += 1

Which of the following is correct output of this program?

a. 1 2 3 4 5
b. 1 2 3 4 5 6
c. 1 2 3 4 5 6 7
d. Invalid syntax

Answer: (b) 1 2 3 4 5 6

Explanation: None

43) Study the following program:

i=0
while i < 5:
print(i)
i += 1
if i == 3:
break
else:
print(0)

What will be the output of this statement?

a. 1 2 3
b. 0 1 2 3
c. 0 1 2
d. 3 2 1

Answer: (c) 0 1 2

Explanation: None

44) Study the following program:

i=0
while i < 3:
print(i)
i += 1
else:
print(0)

What will be the output of this statement?

a. 0 1
b. 0 1 2
c. 0 1 2 0
d. 0 1 2 3

Answer: (c) 0 1 2 0

Explanation: None

45) Study the following program:


z = "xyz"
j = "j"
while j in z:
print(j, end=" ")

What will be the output of this statement?

a. xyz
b. No output
c. x y z
d. j j j j j j j..

Answer: (b) No output

Explanation: "j" is not in "xyz".

46) Study the following program:

x = 'pqrs'
for i in range(len(x)):
x[i].upper()
print (x)

Which of the following is the correct output of this program?

a. PQRS
b. pqrs
c. qrs
d. None of these

Answer: (b) pqrs


Explanation: None

47) Study the following program:

d = {0: 'a', 1: 'b', 2: 'c'}


for i in d:
print(i)

What will be the output of this statement?

a. a b c
b. 0 1 2
c. 0 a 1b 2c
d. None of these above

Answer: (b) 0 1 2

Explanation: None

48) Study the following program:

d = {0, 1, 2}
for x in d:
print(x)

What will be the output of this statement?

a. {0, 1, 2} {0, 1, 2} {0, 1, 2}


b. 0 1 2
c. Syntax_Error
d. None of these above

Answer: (b) 0 1 2

Explanation: None
49) Which of the following option is not a core data type in the python language?

a. Dictionary
b. Lists
c. Class
d. All of the above

Answer: (c) Class

Explanation: Class is not a core data type because it is a user-defined data type.

50) What error will occur when you execute the following code?

MANGO = APPLE
a. NameError
b. SyntaxError
c. TypeError
d. ValueError

Answer: (a) NamaError

Explanation: Mango is not defined hence the name error.

51) Study the following program:

def example(a):
aa = a + '1'
aa = a*1
return a
>>>example("javatpoint")

What will be the output of this statement?

a. hello2hello2
b. hello2
c. Cannot perform mathematical operation on strings
d. indentationError

Answer: (d) indentationError

Explanation: None

52) Which of the following data types is shown below?

L = [2, 54, 'javatpoint', 5]

What will be the output of this statement?

a. Dictionary
b. Tuple
c. List
d. Stack

Answer: (c) List

Explanation: Any value can be stored in the list data type.

53) What happens when '2' == 2 is executed?

a. False
b. Ture
c. ValueError occurs
d. TypeError occurs

Answer: (a) False

Explanation: It only evaluates to false.

54) Study the following program:


try:
if '2' != 2:
raise "JavaTpoint"
else:
print("JavaTpoint has not exist")
except "JavaTpoint":
print ("JavaTpoint has exist")

What will be the output of this statement?

a. invalid code
b. JavaTpoint has not exist
c. JavaTpoint has exist
d. none of these above

Answer: (a) invalid code

Explanation: A new exception class must inherit from a BaseException, and there is no such inheritance here.

55) Study the following statement

z = {"x":0, "y":1}

Which of the following is the correct statement?

a. x dictionary z is created
b. x and y are the keys of dictionary z
c. 0 and 1 are the values of dictionary z
d. All of the above

Answer: (d) All of the above

Explanation: All of the above statements is correct regarding Python code.


Q.15 The flowchart symbol bellow

(a)Process symbol (b)Input/output symbol

(c)Decision symbol (d)Terminator symbol


Q.16 The flowchart symbol shown below is

(a)Process symbol (b)Input/output symbol

(c)Decision symbol (d)Terminator symbol


Q.17 The flowchart symbol shown below is

(a)Process symbol (b)Input/output symbol

(c)Decision symbol (d)Terminator symbol

Q.18 The flowchart symbol shown below is


(a)Process symbol (b)Input/output symbol

(c)Decision symbol (d)Terminator symbol


Q.19Which of the following is not a basic control structure?

(a)The process (b)The Loop

(c)The decision (d)The sequential

Q.20 Which of the following is not a principle of good programming style?


(a)Use descriptive variable names (b)Provide a welcome message
(c)Identify using text the numbers that are output (d)Test the program

Q.21Method which uses a list of well defined instructions to complete a task starting from a given
initial state

from a given initial state to end state is calls as

(a)Program (b)Flowchart (c)Algorithm

(d)A & B
Q.22The chart that contains only function flow and no code is called as

(a)flowchart (b)Structure chart (c)Both A and B


(d)None
Q.23 Which of the following is a program planning tool?
(a)Sequential (b)decision (c)Pseudo code (d)Both B and C
Q.24Which of the following structures are used in computer programs?
(a)sequential (b)decision (c)Timesharing (d)None

Q.25Execution of two or more programs by a single CPU is known as

(a)Multiprogramming (b)Multiprocessing
(c)Timesharing
(d)None
Q.26 A structured chart is

(a)A statement of information processing requirements


(b)A document of what has to be accomplished

(c)A hierarchical Partitioning of the


program (d)Beginners all purpose
(e)All
Q.27 In structure charts modules are described as
(a)Circle (b) Triangles (c)Rectangle (d)Ellipse
Q.28 The sequence logic will not be used while

(a)Accepting input from user (b)Comparing two sets of data


(c)Giving output to the user (d)Adding two numbers

MCQ Question Bank

Q.29 Flowcharts and Algorithms are used for

(a)Better Programming

(b)Efficient Coding

(c)Easy testing and Debugging


(d)All
Q30 An Algorithm represented in the form of programming languages is _________
(a)Flowchart (b)Pseudo code (c)Program (d)None
Q31Which of the following is a pictorial representation of an algorithm?
(a)Pseudo code (b)Program (c)Flowchart (d)Algorithm

Q.32Which of the following symbol in a flowchart are used to indicate all arithmetic processes of
adding, subtracting, multiplying and dividing ?
(a)Input/output
(b)terminal
(c)Processing (d)Decision
Q.33 A flowchart that outlines the main segments of program is called as
(a)Micro flowchart (b)Macro flowchart (c)Flowchart
(d)Algorithm
Q.34 A flowchart that outlines with all detail is called as

(a)Micro flowchart (b)Macro flowchart (c)Flowchart (d)Algorithm


Q.35Pseudo code is also known as

(a)Program Design Language


(b)Software Language

(c)Hardware Language

(d)Algorithm

Q.36 Pseudo code emphasizes on

(a)Development (b)Coding

(c)Design
(d)Debugging

Q.37 In which of the following pseudo code instructions are written in the order or sequence in
which
they are to be performed?
(a)Selection Logic (b)Sequence Logic (c)Iteration Logic (d)Looping Logic

Q.38 Which of the following logic is used to produce loops in program logic when one or more
instruction may be executed several times depending on some conditions?
(a) Iteration Logic (b) Selection Logic (c) Sequence Logic (d)Decision Logic
Q.39 Selection logic also called as
(a) Decision Logic (b) Iteration Logic
(c) Sequence Logic (d)Looping Logic

Q.40 Which of the following program planning tool allows the programmers to plan program logic
by writing
program instruction in an ordinary language?
(a)Flowchart (b)Pseudo code (c)Program (d)Looping

Q.41Which logic is used to select the proper path out of two or more alternative paths in program
logic
(a)Looping Logic (b)Sequence Logic (c)Iteration Logic (d)Selection Logic
Q.42 Which of the following control structures are used in iteration logic

(a)if then if then else (b)do which


(c)do which repeat until
(d)do while if else

Q.43 To write the correct and effective program we much first

(a)Draw a flowchart

(b)Plan its logic

(c)Write pseudo code (d)Use iterations


Q.44Match the following

(i)

(ii) (iii)

(iv) (v)
(a)Connecting

(b)Input/Output

(c)Processing

(d)Terminal

(e)Decision
ANS=i-(d),ii-(e),iii-(c),iv-(a);

Q.45 which of the following file conations the programmer‟s original program code?
(a)Application file (b)Executing (c)Object file (d)Source file

16

MCQ Question Bank

Q.46 Algorithm is

(a)step by step execution of program


(b)Executable file

(c)Object file (d)Source file


Q.47 Kite box in flow chart is used for

(a)Connecter (b)Decision
(c)Statement
(d) All of the above
Q.48 Which of the following is not a characteristic of good algorithm?
(a)Precise
(b)Finite number of steps

(c)Ambiguous

(d)Logical flow of control

Q.49 Diagrammatic representation of an algorithm is

(a)Flowchart (b)Data flow Diagram


(c)Algorithm design (d) Pseudo code
Q.50 Goto statement is ?

(a)Used to jump the control of program

(b)Same as switch case statement


(c)Used for user defined iteration

(d)None of above

Q.51 After a programmer plans the logic of a program ,she /he will next____

(a)Understand the problem

(b)Test the program

(c)Translate the program

(d)Code the program

Q.52 What symbol is used to represent output in a flowchart?

(a)Square (b)Circle (c)Parallelogram


(d)Triangle

Q.53 What is the standard terminal symbol for flowchart?


(a)Circle (b)Parallelogram (c)Diamond (d)Square

Q.54 The following pseudo code is an example of _______ structure:


Get number
While number is positive
Add to sum
(a)Sequence (b)Decision (c)Loop (d)Nested
Q.55 The following pseudo code is an example of _______structure:
Get number
Get another number

If first number is greater than second


then Print first number
Else
print second number
(a)Sequence (b)Decision (c)Loop (d)Nested
Q.56The following pseudo code is an example of ________structure:
Get number
Get another number
Multiply numbers
Print result
(a)Sequence (b)Decision (c)Loop (d)Nested

Q.57structured program can be easily broken down into routines or _______that can be assigned to
any
number of programmers
(a)Segments (b)Modules (c)Units (d)Sequences
1. Python was developed by
A. Guido van Rossum
B. James Gosling
C. Dennis Ritchie
D. Bjarne Stroustrup
View Answer
Ans : A

Explanation: A Dutch Programmer Guido van Rossum developed python at Centrum


Wiskunde & Informatica (CWI) in the Netherlands as a successor to the ABC language.

2. Python was developed in which year?


A. 1972
B. 1995
C. 1989
D. 1981
View Answer
Ans : C

Explanation: Python was introduced by Guido Van Rossum in 1989. So Option C is


correct.

3. Python is written in which language?


A. C
B. C++
C. Java
D. None of the above
View Answer
Ans : A

Explanation: Python is written in C with default/traditional implementation as CPython.


So, Option A is correct.

4. What is the extension of python file?


A. .p
B. .py
C. .python
D. None of the above
View Answer
Ans : B

Explanation: Python file is saved with an extension .py. So, Option B is correc

5. Python is Object Oriented Programming Language.


A. True
B. False
C. Neither true nor false
D. None of the above
View Answer
Ans : A

Explanation: Yes python is object oriented language but not pure. It does not support
strong encapsulation while it is one of the core features of an "object-oriented"
programming language. So, Option A is correct.

6. Python 3.0 is released in which year?


A. 2000
B. 2008
C. 2011
D. 2016
View Answer
Ans : B

Explanation: Python 3.0 was released on December 3rd, 2008. So, Option B is correct.

7. Which of the following statements is true?


A. Python is a high level programming language.
B. Python is an interpreted language.
C. Python is an object-oriented language
D. All of the above
View Answer
Ans : D

Explanation: Python is high level, object oriented and interpreted programming


language. So, Option D is correct.

8. What is used to define a block of code in Python?


A. Parenthesis
B. Indentation
C. Curly braces
D. None of the above
View Answer
Ans : B

Explanation: Python uses indentation to define block of code. Indentations are simply
Blank spaces or Tabs which is used as an indicator that indented code is the child part.
As curlybraces are used in C/C++/Java.. So, Option B is correct.

9. By the use of which character, single line is made comment in


Python?
A. *
B. @
C. #
D. !
View Answer
Ans : C

Explanation: # is used for single line is made comment in Python. So, Option C is
correct.

10. What is a python file with .py extension called?


A. package
B. module
C. directory
D. None of the above
View Answer
Ans : B

Explanation: python file with .py extension called module. So, Option B is correct.

11. What will be the output of the following program on execution?


a=0

b=5

x=(a&b)|(a&a)|(a|b)

print("x")

A. 1
B. 5
C. 0
D. None of the above
View Answer
Ans : D

Explanation: Output of the following python code x. Therefore output is none of the
above.

12. What will be the output of the following program on execution?


if False:

print ("inside if block")

elif True:

print ("inside elif block")

else:

print ("inside else block")

A. inside if block
B. inside elif block
C. inside else block
D. Error
View Answer
Ans : B
Explanation: Output of the following python code is inside elif block. Therefore Option B
is correct.

13. Which of the following statements are correct?


(i) Python is a high level programming language.
(ii) Python is an interpreted language.
(iii) Python is a compiled language.
(iv) Python program is compiled before it is interpreted.
A. i, ii
B. i, iv
C. ii, iii
D. ii, iv
View Answer
Ans : B

Explanation: Python is a high level programming language and Python program is


compiled before it is interpreted is correct statement.

14. Which of the following is incorrect variable name in Python?


A. variable_1
B. variable1
C. 1variable
D. _variable
View Answer
Ans : C

Explanation: 1variable is incorrect variable name in Python.The Option C is correct.

15. What will be the output of following Python code snippet?


str1="012"

num1=2

num2=0

for i in range(4):
num1+=2

for j in range(len(str1)):

num2=num2+num1

num3=num2%int(str1)

print(num3)

A. 7
B. Infinite Loop
C. 0
D. Error
View Answer
Ans : C

Explanation: The Output for the following code is 0. So, Option C is correct.

16. What will be the result of following Python code snippet after
execution?
str1=""

i=0

var2=1

while(i<3):

var1=1

if str1:

var2=var1*var2+5

else:

var2=var1*var2+1

i=i+1

print(var2)
A. 16
B. 12
C. 11
D. 4
View Answer
Ans : B

Explanation: The Output for the following code is 12. So, Option B is correct.

17. Which of the following is not a relational opeartor in Python?


A. >=
B. <=
C. =
D. !=
View Answer
Ans : C

Explanation: = is not considered as a relational operator in Python. So Option C is


correct.

18. Suppose we have two sets A & B, then A < B is:


A. True if len(A) is less than len(B).
B. True if A is a proper subset of B.
C. True if the elements in A when compared are less than the elements in B.
D. True if A is a proper superset of B.
View Answer
Ans : B

Explanation: If A is proper subset of B then hen all elements of A are in B but B contains
at least one element that is not in B.

19. Which of the following will result in error?


(i) list1[3]=list1[2]
(ii) list1[3]=list1[4]
(iii) list1.insert(1,78)
(iv) list1.pop(50)
If list1=[10,20,60,50]

A. i, iii
B. i, iv
C. ii, iv
D. ii, iii
View Answer
Ans : C

Explanation: list1[3]=list1[4] and list1.pop(50) will result in error. So Option C is correct.

20. If str1="Programming Language"


What does str1.find("m") return?
A. Number of occurances of "m" in string str1.
B. Index positions of "m" in the string str1.
C. It returns the whole string str1 if it contains "m".
D. It returns the index position of first occurance of "m" in the string str1.
View Answer
Ans : D

Explanation: It returns the index position of first occurance of "m" in the string str1. So
Option D is correct.

21. Which one of the following is correct way of declaring and


initialising a variable, x with value 5?
A. int x
x=5
B. int x=5
C. x=5
D. declare x=5
View Answer
Ans : C

Explanation: One of the following is correct way of declaring and initialising a variable, x
with value 5 is x=5.

22. Which of the following is not valid variable name in Python?


A. _var
B. var_name
C. var11
D. 11var
View Answer
Ans : D

Explanation: 11var is not valid variable name in Python.

23. Which of the following is incorrect regarding variables in


Python?
A. Variable names in Python cannot start with number. However, it can
contain number in any other position of variable name.
B. Variable names can start with an underscore.
C. Data type of variable names should not be declared
D. None of the above
View Answer
Ans : D

Explanation: All of the above options are correct regarding variables in Python.

24. Which of the following will give error?


A. a=b=c=1
B. a,b,c=1
C. a,b,c=1, “python―, 1.5
D. None of the above
View Answer
Ans : B

Explanation: a,b,c=1 give error in Python.

25. How many keywords are there in python 3.7?


A. 32
B. 33
C. 31
D. 30
View Answer
Ans : B

Explanation: There are 33 keywords in Python 3.7 . Keywords are reserved words that
can not be used as variables. So, Option B is correct.

26. What is the maximum length of an identifier in python?


A. 32
B. 31
C. 63
D. None of the above
View Answer
Ans : D

Explanation: In pyhton Identifier can be of any length. So, Option D is correct.

27. All keyword in python are in


A. Lowercase
B. Uppercase
C. Both uppercase & Lowercase
D. None of the above
View Answer
Ans : C

Explanation: All keywords in python are in lowercase except True, False and None. So,
Option C is correct.

28. Which of the following statment is False?


A. Variable names can be arbitrarily long.
B. They can contain both letters and numbers.
C. Variable name can begin with underscore.
D. Variable name can begin with number.
View Answer
Ans : D

Explanation: Variable name can not begin with number it can begin with letter or
underscore. So, Option D is correct.
29. Which of the following is a valid variable?
A. var@
B. 32var
C. class
D. abc_a_c
View Answer
Ans : D

Explanation: Variable name should not be keyword, cannot begin with digit and should
not contain special symbol. Hence D is the correct identifier or variable. So, Option D is
correct.

30. Why are local variable names beginning with an underscore


discouraged?
A. they confuse the interpreter
B. they are used to indicate a private variables of a class
C. they are used to indicate global variables
D. they slow down execution
View Answer
Ans : B

Explanation: local variable names beginning with an underscore discouraged because


they are used to indicate a private variables of a class. So, Option B is correct.

31. Which of these are keyword?


A. in
B. is
C. assert
D. All of the above
View Answer
Ans : D

Explanation: All "in", "is" and "assert" are keywords. So, Option D is correct.
32. What is the output of the following code : print 5//2
A. 2
B. 2.5
C. 2.0
D. Error
View Answer
Ans : A

Explanation: Floor Division "//" - The division of operands where the result is the
quotient in which the digits after the decimal point are removed. So in this case we get 2
as a answer. So, Option A is correct.
SINHGAD COLLEGE OF ENGINEERING
Department of Information Technology
Programming and Problem Solving (110005)
UNIT-II- Decision Control Statements
Multiple choice questions Bank

Content:
Decision Control Statements: Decision control statements, Selection/conditional branching
Statements: if, if-else, nested if, if-elif-else statements. Basic loop Structures/Iterative statements:
while loop, for loop, selecting appropriate loop. Nested loops, The break, continue, pass, else
statement used with loops. Other data types- Tuples, Lists and Dictionary.

1. Which of the following is not used as loop in Python?

A. for loop
B. while loop
C. do-while loop
D. None of the above
Answer: C

2. Which of the following is False regarding loops in Python?

A. Loops are used to perform certain tasks repeatedly.


B. While loop is used when multiple statements are to executed repeatedly until the given
condition becomes False
C. While loop is used when multiple statements are to executed repeatedly until the given
condition becomes True.
D. for loop can be used to iterate through the elements of lists.
Answer: B

3. Which of the following is True regarding loops in Python?

A. Loops should be ended with keyword "end".


B. No loop can be used to iterate through the elements of strings.
C. Keyword "break" can be used to bring control out of the current loop.
D. Keyword "continue" is used to continue with the remaining statements inside the loop.
Answer: C

4. How many times will the loop run?


i=2
while(i>0):
i=i-1
A. 2
B. 3
C. 1
D. 0
Answer: A
5. What will be the output of the following Python code?

list1 = [3 , 2 , 5 , 6 , 0 , 7, 9]
sum = 0
sum1 = 0
for elem in list1:
if (elem % 2 == 0):
sum = sum + elem
continue
if (elem % 3 == 0):
sum1 = sum1 + elem
print(sum , end=" ")
print(sum1)

A. 8 9
B. 8 3
C. 2 3
D. 8 12
Answer: D

6. Which one of the following is a valid Python if statement

A. if a>=2 :
B. if (a >= 2)
C. if (a => 22)
D. if a >= 22
Answer: A

7. What keyword would you use to add an alternative condition to an if statement?

A. else if
B. elseif
C. elif
D. None of the above
Answer: C

8. Can we write if/else into one line in python?

A. Yes
B. No
C. if/else not used in python
D. None of the above
Answer: A

9. In a Python program, a control structure:

A. Defines program-specific data structures


B. Directs the order of execution of the statements in the program
C. Dictates what happens before the program starts and after it terminates
D. None of the above
Answer: B

10. What will be output of this expression?


'p' + 'q' if '12'.isdigit() else 'r' + 's'

A. pq
B. rs
C. pqrs
D. pq12
Answer: A

11. Which statement will check if a is equal to b?

A. if a = b:
B. if a == b:
C. if a === c:
D. if a == b
Answer: B

12. Does python have switch-case statement?

A. True
B. False
C. Python has switch statement but we cannot use it.
D. None of the above
Answer: B

13. What will be the output of given Python code?


n=7
c=0
while(n):
if(n>5):
c=c+n-1
n=n-1
else:
break
print(n)
print(c)

A. 2
B. 6 5 2
C. 3
D. 5 2
Answer: A
14. What will be the output of given Python code?

str1="hello"
c=0
for x in str1:
if(x!="l"):
c=c+1
else:
pass
print(c)

A. 2
B. 0
C. 4
D. 3
Answer: D

15. Which of the following Python code will give different output from the others?

A. for i in range(0,5):
print(i)
B. for j in [0,1,2,3,4]:
print(j)
C. for k in [0,1,2,3,4,5]:
print(k)
D. for l in range(0,5,1):
print(l)
Answer: C

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


str1="learn python"
str2=""
str3=""
for x in str1:
if(x=="r" or x=="n" or x=="p"):
str2+=x
pass
if(x=="r" or x=="e" or x=="a"):
str3+=x
print(str2,end=" ")
print(str3)

A. rnpn ea
B. rnpn ear
C. rnp ea
D. rnp ear
Answer: B

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


for i in range(0,2,-1):
print("Hello")
A. Hello
B. Hello Hello
C. No Output
D. Error
Answer: C

18. Which of the following is a valid for loop in Python?

A. for(i=0; i < n; i++)


B. for i in range(0,5):
C. for i in range(0,5)
D. for i in range(5)
Answer: B

19. Which of the following sequences would be generated bt the given line of code?
range (5, 0, -2)

A. 5 4 3 2 1 0 -1
B. 5 4 3 2 1 0
C. 5 3 1
D. None of the above
Answer: C

20. A while loop in Python is used for what type of iteration?

A. indefinite
B. discriminant
C. definite
D. indeterminate
Answer: A

21. When does the else statement written after loop executes?

A. When break statement is executed in the loop


B. When loop condition becomes false
C. Else statement is always executed
D. None of the above
Answer: B

22. What will be the output of the following code?


x = "abcdef"
i = "i"
while i in x:
print(i, end=" ")

A. a b c d e f
B. abcdef
C. i i i i i.....
D. No Output
Answer: D
23. What will be the output of the following code?
x = "abcd"
for i in range(len(x)):
print(i)

A. abcd
B. 0 1 2 3
C. 1 2 3 4
D. a b c d
Answer: B

24. What will be the output of the following code?


x = 12
for i in x:
print(i)

A. 12
B. 1 2
C. Error
D. None of the above
Answer: C

25. What does the following code print to the console?


if 2 == 2:
print("ice cream is tasty!")

A. No output
B. ice cream
C. "ice cream is tasty!"
D. None of the above
Answer: C

26. What does the following code print to the console?


if "cat" == "dog":
print("prrrr")
else:
print("ruff")
"ruff" is printed.

A. prrrr
B. ruf
C. prrrrruff
D. None of the above
Answer: B
27. What does the following code print to the console?
if 5 > 10:
print("fan")
elif 8 != 9:
print("glass")
else:
print("cream")
"glass" is printed.

A. fan
B. cream
C. glass
D. None of the above
Answer: C

28. What does the following code print to the console?


name = "maria"
if name == "melissa":
print("usa")
elif name == "mary":
print("ireland")
else:
print("colombia")

A. ireland
B. maria
C. usa
D. colombia
Answer: D

29. What does the following code print to the console?


if 88 > 100:
print("cardio")

A. error
B. cardio
C. No output
D. None of the above
Answer: C

30. What does the following code print to the console?


hair_color = "blue"
if 3 > 2:
if hair_color == "black":
print("You rock!")
else:
print("Boring")
A. Boring
B. You rock!
C. black
D. None of the above
Answer: A
31. What does the following code print to the console?
if True:
print(101)
else:
print(202)

A. 201
B. 101201
C. 101
D. error
Answer: C

32. What does the following code print to the console?


if False:
print("Nissan")
elif True:
print("Ford")
elif True:
print("BMW")
else:
print("Audi")
"Ford" is printed

A. BMW
B. Ford
C. Nissan
D. Audi
Answer: B

33.What does the following code print to the console?


if 0:
print("huh?")
else:
print("0 is falsy!")
0 is falsy is printed.

A. huh?
B. 0 is falsy
C. huh? 0 is falsy
D. No Output
Answer: B

34. What does the following code print?

if 4 + 5 == 10:
print("TRUE")
else:
print("FALSE")
print("TRUE")
A. TRUE
B.
TRUE
FALSE
C.
FALSE
TRUE
D.
TRUE
FALSE
TRUE
Answer: A

35. Which of the following is true about the code below?

x=3
if (x > 2):
x = x * 2;
if (x > 4):
x = 0;
print(x)

A. x will always equal 0 after this code executes for any value of x
B. if x is greater than 2, the value in x will be doubled after this code executes
C. if x is greater than 2, x will equal 0 after this code executes
D. None of the Above
Answer: C

36. What is the total for 12 items that weigh 3 pounds?


weight = 0.5
numItems = 5
if weight < 1:
price = 1.45
if weight >= 1:
price = 1.15
total = weight * price
if numItems >= 10:
total = total * 0.9
print(weight)
print(price)
print(total)

A. $3.45
B. $3.11
C. $3.105
D. $3.10
Answer: C
37. Given two variables, num1 and num2, which of the following would mean that both num1 and num2
are positive integers?

A. (num1 = num2)
B. (num1 = num2) OR (num1 ≠ num2)
C. (num1 = num2) AND (num1<0)
D. (num1 = num2) AND (num2>0)
Answer: D

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


x = ['ab', 'cd']
for i in x:
x.append(i.upper())
print(x)

A. [‘AB’, ‘CD’]
B. [‘ab’, ‘cd’, ‘AB’, ‘CD’]
C. [‘ab’, ‘cd’]
D. none of the mentioned
Answer: D

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


i=1
while True:
if i%3 == 0:
break
print(i)
i+=1

A. 1 2
B. 1 2 3
C. error
D. none of the mentioned
Answer: C

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


i=1
while True:
if i%0O7 == 0:
break
print(i)
i += 1

A. 1 2 3 4 5 6
B. 1 2 3 4 5 6 7
C. error
D. none of the mentioned
Answer: A
41. What will be the output of the following Python code?
True = False
while True:
print(True)
break

A. True
B. False
C. None
D. none of the mentioned
Answer: D

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


i=0
while i < 3:
print(i)
i += 1
else:
print(0)

A. 0 1 2 3 0
B. 0 1 2 0
C. 0 1 2
D. error
Answer: B

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


x = "abcdef"
i = "a"
while i in x:
print('i', end = " ")

A. no output
B. i i i i i i …
C. a a a a a a …
D. a b c d e f
Answer: B

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


x = "abcdef"
i = "a"
while i in x:
x = x[:-1]
print(i, end = " ")

A. i i i i i i
B. a a a a a a
C. a a a a a
D. none of the mentioned
Answer: B
45. What will be the output of the following Python code?
x = "abcdef"
i = "a"
while i in x:
x = x[1:]
print(i, end = " ")

A. a a a a a a
B. a
C. no output
D. error
Answer: B

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


x = "abcdef"
i = "a"
while i in x[1:]:
print(i, end = " ")

A. a a a a a a
B. a
C. no output
D. error
Answer: C

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


x = 'abcd'
for i in x:
print(i)
x.upper()

A. a B C D
B. a b c d
C. A B C D
D. error
Answer: B

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


x = 'abcd'
for i in x:
print(i.upper())

A. a b c d
B. A B C D
C. a B C D
D. error
Answer: B

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


x = 'abcd'
for i in range(x):
print(i)
A. a b c d
B. 0 1 2 3
C. error
D. none of the mentioned
Answer: C

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


x = 'abcd'
for i in range(len(x)):
print(i)

A. a b c d
B. 0 1 2 3
C. error
D. 1 2 3 4
Answer: B
1. Which of the following is the use of function in python?
a) Functions are reusable pieces of programs
b) Functions don’t provide better modularity for your application
c) you can’t also create your own functions
d) All of the mentioned
Answer: a
2. Which keyword is used for function?
a) Fun
b) Define
c) Def
d) Function
Answer: c
3. What will be the output of the following Python code?
1. def sayHello():
2. print('Hello World!')
3. sayHello()
4. sayHello()

a)
Hello World!
Hello World!
b)
'Hello World!'
'Hello World!'
c)
Hello
Hello
d) None of the mentioned
Answer: a

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


1. def printMax(a, b):
2. if a > b:
3. print(a, 'is maximum')
4. elif a == b:
5. print(a, 'is equal to', b)
6. else:
7. print(b, 'is maximum')
8. printMax(3, 4)
a) 3
b) 4
c) 4 is maximum
d) None of the mentioned
Answer: c
5. What will be the output of the following Python code?
1. x = 50
2. def func(x):
3. print('x is', x)
4. x = 2
5. print('Changed local x to', x)
6. func(x)
7. print('x is now', x)
a)
x is 50
Changed local x to 2
x is now 50
b)
x is 50
Changed local x to 2
x is now 2
c)
x is 50
Changed local x to 2
x is now 100
d) None of the mentioned
Answer: a
6. What will be the output of the following Python code?
1. x = 50
2. def func():
3. global x
4. print('x is', x)
5. x = 2
6. print('Changed global x to', x)
7. func()
8. 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
Answer: b
7. What will be the output of the following Python code?
1. def say(message, times = 1):
2. print(message * times)
3. say('Hello')
4. say('World', 5)
a)
Hello
WorldWorldWorldWorldWorld
b)
Hello
World 5
c)
Hello
World,World,World,World,World
d)
Hello
HelloHelloHelloHelloHello
Answer: a
8. What will be the output of the following Python code?
1. def func(a, b=5, c=10):
2. print('a is', a, 'and b is', b, 'and c is', c)
3.
4. func(3, 7)
5. func(25, c = 24)
6. func(c = 50, a = 100)
a)
a is 7 and b is 3 and c is 10
a is 25 and b is 5 and c is 24
a is 5 and b is 100 and c is 50
b)
a is 3 and b is 7 and c is 10
a is 5 and b is 25 and c is 24
a is 50 and b is 100 and c is 5
c)
a is 3 and b is 7 and c is 10
a is 25 and b is 5 and c is 24
a is 100 and b is 5 and c is 50
d) None of the mentioned
Answer: c
9. What will be the output of the following Python code?
1. def maximum(x, y):
2. if x > y:
3. return x
4. elif x == y:
5. return 'The numbers are equal'
6. else:
7. return y
8.
9. print(maximum(2, 3))
a) 2
b) 3
c) The numbers are equal
d) None of the mentioned
Answer: b
10. Which of the following is a feature of DocString?
a) Provide a convenient way of associating documentation with Python modules,
functions, classes, and methods
b) All functions should have a docstring
c) Docstrings can be accessed by the __doc__ attribute on objects
d) All of the mentioned
Answer: d
11. Which are the advantages of functions in python?
a) Reducing duplication of code
b) Decomposing complex problems into simpler pieces
c) Improving clarity of the code
d) All of the mentioned
Answer: d
12. What are the two main types of functions?
a) Custom function
b) Built-in function & User defined function
c) User function
d) System function
Answer: b
13. Where is function defined?
a) Module
b) Class
c) Another function
d) All of the mentioned
Answer: d
14. What is called when a function is defined inside a class?
a) Module
b) Class
c) Another function
d) Method
Answer: d
15. Which of the following is the use of id() function in python?
a) Id returns the identity of the object
b) Every object doesn’t have a unique id
c) All of the mentioned
d) None of the mentioned
Answer: a
16. Which of the following refers to mathematical function?
a) sqrt
b) rhombus
c) add
d) rhombus
Answer: a
17. What will be the output of the following Python code?
1. def cube(x):
2. return x * x * x
3. x = cube(3)
4. print x
a) 9
b) 3
c) 27
d) 30
Answer: c
18. What will be the output of the following Python code?
1. def C2F(c):
2. return c * 9/5 + 32
3. print C2F(100)
4. print C2F(0)
a)
212
32
b)
314
24
c)
567
98
d) None of the mentioned
Answer: a
19. What will be the output of the following Python code?

1. def power(x, y=2):


2. r = 1
3. for i in range(y):
4. r=r*x
5. return r
6. print power(3)
7. print power(3, 3)
a)
212
32
b)
9
27
c)
567
98
d) None of the mentioned
Answer: b
20. What will be the output of the following Python code?
1. def sum(*args):
2. '''Function returns the sum
3. of all values'''
4. r = 0
5. for i in args:
6. r += i
7. return r
8. print sum.__doc__
9. print sum(1, 2, 3)
10. print sum(1, 2, 3, 4, 5)

a)
6
15
b)
6
100
c)
123
12345
d) None of the mentioned
Answer: a
21. Python supports the creation of anonymous functions at runtime, using a construct
called __________
a) lambda
b) pi
c) anonymous
d) none of the mentioned
Answer: a
22. What will be the output of the following Python code?
1. y = 6
2. z = lambda x: x * y
3. print z(8
a) 48
b) 14
c) 64
d) None of the mentioned
Answer: a
23. What will be the output of the following Python code?
1. lamb = lambda x: x ** 3
2. print(lamb(5))
a) 15
b) 555
c) 125
d) None of the mentioned
Answer: c
24. Does Lambda contains return statements?
a) True
b) False
Answer: b
25. Lambda is a statement.
a) True
b) False
Answer: b
26. Lambda contains block of statements.
a) True
b) False
Answer: b
27. What will be the output of the following Python code?
1. def f(x, y, z): return x + y + z
2. f(2, 30, 400

a) 432
b) 24000
c) 430
d) No output
Answer: a
28. What will be the output of the following Python code?
1. def writer():
2. title = 'Sir'
3. name = (lambda x:title + ' ' + x)
4. return name
5.
6. who = writer()
7. who('Arthur')
a) Arthur Sir
b) Sir Arthur
c) Arthur
d) None of the mentioned
Answer: b
29. What will be the output of the following Python code?
1. L = [lambda x: x ** 2,
2. lambda x: x ** 3,
3. lambda x: x ** 4]
4.
5. for f in L:
6. print(f(3))
a)
27
81
343
b)
6
9
12
c)
9
27
81
d) None of the mentioned
Answer: c
30. What will be the output of the following Python code?
1. min = (lambda x, y: x if x < y else y)
2. min(101*99, 102*98)

a) 9997
b) 9999
c) 9996
d) None of the mentioned
Answer: c
31. What is a variable defined outside a function referred to as?
a) A static variable
b) A global variable
c) A local variable
d) An automatic variable
Answer: b
32. What is a variable defined inside a function referred to as?
a) A global variable
b) A volatile variable
c) A local variable
d) An automatic variable
Answer: c
UNIT-IV STRINGS

Multiple Choice Questions

Q-1: What is printed by the following statements?

s = "python rocks"
print(s[1] * s.index("n"))
A. yyyyy
B. 55555
C. n
D. Error, you cannot combine all those things together.

Ans-D

Q-2: What will be printed when the following executes?

str = "His shirt is red"


pos = str.find("is")
print(pos)
A. 1
B. 9
C. 10
D. 6

Ans-A

Q-3: What will be printed when the following executes?

str = "This is the end"


str = str[5]
print(str)
A. i
B. s
C. is the end
D. t

Ans-A

Q-4: What is the value of s1 after the following code executes?

s1 = "HEY"
s2 = s1.lower()
s3 = s2.capitalize()
A. Hey
B. hey
C. HEY
D. HEy
Ans- C

Q-5: What would the following code print?

Mali = 5
print("Mali" + " is " + str(Mali))
A. Mali is Mali
B. Mali is 5
C. 5 is Mali
D. 5 is 5

Ans- B

Q-6: What is printed by the following statements?

s = "python rocks"
print(s[3])
A. t
B. h
C. c
D. Error, you cannot use the [ ] operator with a string.

Ans- B

Q-7: What is printed by the following statements?

s = "python rocks"
print(s[2] + s[-5])
A. tr
B. ps
C. nn
D. Error, you cannot use the [ ] operator with the + operator.

Ans-A

Q-8: What is printed by the following statements?

s = "python rocks"
print(len(s))

A. 11
B. 12
C. 10
D. 7

Ans-B
Q-9: What is printed by the following statements:

s = "Rose"
s[1] = "i"
print(s)

A. Rose
B. Rise
C. Error
D. Rsoe

Ans-C

Q-10: What is printed by the following statements:

s = "ball"
r = ""
for item in s:
r = item.upper() + r
Print(r)

A. Ball
B. BALL
C. LLAB
D. LAB

Ans-C

Q-11: What is printed by the following statements?

s = "python rocks"
print(s[7:11] * 3)
A. rockrockrock
B. rock rock rock
C. rocksrocksrocks
D. Error, you cannot use repetition with slicing.

Ans-A

Q-12: What is the output of the following string operations

str = "My salary is 7000";


print(str.isalnum())

A. True
B. False

Ans-B
Q-13: In Python, strings are…

A. str objects

B. Incorrect

C. changeable

D. Immutable

Ans-C

Q-14: What will be the output of the following Python statement?

>>>"a"+"bc"
a) a
b) bc
c) bca
d) abc

Answer: d
Explanation: + operator is concatenation operator.

Q-14: What will be the output of the following Python statement?

>>>"abcd"[2:]
a) a
b) ab
c) cd
d) dc

Answer: c

Explanation: Slice operation is performed on string.

Q-15: The output of executing string.ascii_letters can also be achieved by:


a) string.ascii_lowercase_string.digits
b) string.ascii_lowercase+string.ascii_upercase
c) string.letters
d) string.lowercase_string.upercase

Answer: b
Explanation: Execute in shell and check.
Q-16: What will be the output of the following Python code?

>>> str1 = 'hello'


>>> str2 = ','
>>> str3 = 'world'
>>> str1[-1:]

a) olleh
b) hello
c) h
d) o

Answer: d
Explanation: -1 corresponds to the last index.

Q-17: What arithmetic operators cannot be used with strings?


a) +
b) *
c) –
d) All of the mentioned

Answer: c
Explanation: + is used to concatenate and * is used to multiply strings.

Q-18: What will be the output of the following Python code?

>>>print (r"\nhello")

a) a new line and hello


b) \nhello
c) the letter r and then hello
d) error

Answer: b
Explanation: When prefixed with the letter ‘r’ or ‘R’ a string literal becomes a raw
string and the escape sequences such as \n are not converted.

Q-19: What will be the output of the following Python statement?

>>>print('new' 'line')
a) Error
b) Output equivalent to print ‘new\nline’
c) newline
d) new line

Answer: c
Explanation: String literal separated by whitespace are allowed. They are
concatenated.
Q-20: What will be the output of the following Python statement?

>>> print('x\97\x98')
a) Error
b)

97
98
c) x\97
d) \x97\x98

Answer: c
Explanation: \x is an escape sequence that means the following 2 digits are a
hexadecimal number encoding a character.

Q-21: What will be the output of the following Python code?

>>>str1="helloworld"
>>>str1[::-1]
a) dlrowolleh
b) hello
c) world
d) helloworld

Answer: a
Explanation: Execute in shell to verify.

Q-22: What will be the output of the following Python code?

print(0xA + 0xB + 0xC)


a) 0xA0xB0xC
b) Error
c) 0x22
d) 33

Answer: d
Explanation: 0xA and 0xB and 0xC are hexadecimal integer literals representing the
decimal values 10, 11 and 12 respectively. There sum is 33.
Q-23: What will be the output of above Python code?

str1="6/4"

print("str1")

A. 1
B. 6/4
C. 1.5
D. str1
Ans : D
Explanation: Since in print statement, str1 is written inside double quotes so it
will simply print str1 directly.

Q-24: Which of the following will result in an error?

str1="python"

A. print(str1[2])
B. str1[1]="x"
C. print(str1[0:9])
D. Both (b) and (c)
Ans : B
Explanation: Strings are immutable. So,new values cannot be assigned at any
index position in a string

Q-25: Which of the following is False?

A. String is immutable.
B. capitalize() function in string is used to return a string by converting the whole
given string into uppercase.
C. lower() function in string is used to return a string by converting the whole given
string into lowercase.
D. None of these.
Ans : B
Explanation: capitalize() function in string gives the output by converting only the
first character of the string into uppercase and rest characters into
lowercase.However, upper() function is used to return the whole string into
uppercase.
Q-26: What will be the output of below Python code?

str1="Information"

print(str1[2:8])

A. format
B. formatio
C. orma
D. ormat
Ans : A
Explanation: Concept of slicing is used in this question. In string slicing,the
output is the substring starting from the first given index position i.e 2 to one less
than the second given index position i.e.(8-1=7) of the given string str1. Hence,
the output will be "format".

Q-27: What will be the output of below Python code?

str1="Aplication"

str2=str1.replace('a','A')

print(str2)

A. application
B. Application
C. ApplicAtion
D. applicAtion
Ans : C
Explanation: replace() function in string is used here to replace all the existing "a"
by "A" in the given string.
Q-28: What will be the output of below Python code?

str1="poWer"

str1.upper()

print(str1)

A. POWER
B. Power
C. power
D. poWer
Ans : D
Explanation: str1.upper() returns the uppercase of whole string str1. However,it
doesnot change the string str1. So, output will be the original str1.

Q-29:What will the below Python code will return?

If str1="save paper,save plants"

str1.find("save")

A. It returns the first index position of the first occurance of "save" in the given
string str1.
B. It returns the last index position of the last occurance of "save" in the given
string str1.
C. It returns the last index position of the first occurance of "save" in the given
string str1.
D. It returns the first index position of the first occurance of "save" in the given
string str1.
Ans : A
Explanation: It returns the first index position of the first occurance of "save" in
the given string str1.
Q-30:What will the below Python code will return?

list1=[0,2,5,1]

str1="7"

for i in list1:

str1=str1+i

print(str1)

A. 70251
B. 7
C. 15
D. Error
Ans : D
Explanation: list1 contains integers as its elements. Hence these cannot be
concatenated to string str1 by simple "+" operand. These should be converted to
string first by use of str() function,then only these will get concatenated.

Q-31: Which of the following will give "Simon" as output?

If str1="John,Simon,Aryan"

A. print(str1[-7:-12])
B. print(str1[-11:-7])
C. print(str1[-11:-6])
D. print(str1[-7:-11])
Ans : C
Explanation: Slicing takes place at one index position less than the given second
index position of the string. So,second index position will be -7+1=-6.
Q-32: What will following Python code return?

str1="Stack of books"

print(len(str1))

A. 13
B. 14
C. 15
D. 16
Ans : B
Explanation: len() returns the length of the given string str1, including spaces and
considering " " as a single character.

Q-33: What is the output when following code is executed ?

print r"\nhello"
The output is
A. a new line and hello
B. \nhello
C. the letter r and then hello
D. Error
Ans: B

Q-34: What is the output of “hello”+1+2+3 ?


A. hello123
B. hello
C. Error
D. hello6

Answer: Option C
Explanation:
Cannot concantenate str and int objects.
Q-35:What is the output of the following?

print('ab'.isalpha())
A. True
B. False
C. None
D. Error

Answer: Option A
Explanation:
The string has only letters.

Q-36: What is the output of print str[0] if str = 'Hello World!'?

A - Hello World!

B-H

C - ello World!

D - None of the above.

Answer : B
Explanation
H is the correct answer.
Q-37: What is the output of print tinylist * 2 if tinylist = [123, 'john']?

A - [123, 'john', 123, 'john']

B - [123, 'john'] * 2

C - Error

D - None of the above.

Answer : A
Explanation
It will print list two times. Output would be [123, 'john', 123, 'john'].

Q-38:Which of the following function convert a String to an object in python?

A - repr(x)

B - eval(str)

C - tuple(s)

D - list(s)

Answer : B
Explanation
eval(str) − Evaluates a string and returns an object.
Q-39:Which of the following function convert a single character to its integer
value in python?

A - unichr(x)

B - ord(x)

C - hex(x)

D - oct(x)

Answer : B
Explanation
ord(x) − Converts a single character to its integer value.

Q-40 : Which of the following statement is used when a statement is required


syntactically but you do not want any command or code to execute?

A - break

B - continue

C - pass

D - None of the above.

Answer : C
Explanation
pass statement − The pass statement in Python is used when a statement is
required syntactically but you do not want any command or code to execute.
Q-41 : Which of the following function checks in a string that all characters are in
uppercase?

A - isupper()

B - join(seq)

C - len(string)

D - ljust(width[, fillchar])

Answer : A
Explanation
isupper() − Returns true if string has at least 1 character and all characters are in
uppercase.

Q-42 : Which of the following function returns the min alphabetical character
from the string str?

A - lower()

B - lstrip()

C - max(str)

D - min(str)

Answer : D
Explanation
min(str) − Returns the min alphabetical character from the string str.
Q-43 : What is the output of ['Hi!'] * 4?

A - ['Hi!', 'Hi!', 'Hi!', 'Hi!']

B - ['Hi!'] * 4

C - Error

D - None of the above.

Answer : A
Explanation
['Hi!', 'Hi!', 'Hi!', 'Hi!']

Q-44 : What is the following function removes last object from a list?

A - list.index(obj)

B - list.insert(index, obj)

C - list.pop(obj=list[-1])

D - list.remove(obj)

Answer : C
Explanation
list.pop(obj=list[-1]) − Removes and returns last object or obj from list.
Combined Extra Multiple Choice Questions

1. Do we need to compiler a program before execution in Python?


A. Yes
B. No

Answer : B

2. How to output the string “May the odds favor you” in Python?

A. print(“May the odds favor you”)


B.echo(“May the odds favor you”)
C.System.out(“May the odds favor you”)
D.printf(“May the odds favor you”)

Answer : A

3. How to create a variable in Python with value 22.6?


A. int a = 22.6
B. a = 22.6
C. Integer a = 22.6
D. None of the above

Answer : B

4. How to add single-line comment in Python?


A. /* This is comment */
B. !! This is comment
C. // This is comment
D. # This is comment

Answer : D

5. How to represent 261500000 as a floating number in Python?


A. 2.615E8
B. 261500000
C. 261.5E8
D. 2.6

Answer : A

6. Select the correct example of complex datatype in Python


A. 3 + 2j
B. -100j
C. 5j
D. All of the above are correct

Answer : D

7. What is the correct way of creating a multi-line string in Python?


A. str = “”My name is Kevin and I
live in New York””
B. str = “””My name is Kevin and I
live in New York”””
C. str = “My name is Kevin and I
live in New York”
D. All of the above

Answer : B

8. How to convert the uppercase letters in the string to lowercase in Python?


A. lowercase()
B. capilaize()
C. lower()
D. toLower()

Answer : C

9. How to access substring “Kevin” from the following string declaration in

Python:
1
2str = "My name is Kevin"
3
A. str[11:16]
B. str(11:16)
C. str[11][16]
D. str[11-16]

Answer : A

10. Which of the following is the correct way to access a specific character. Let’s

say we need to access the character “K” from the following string in Python?
1
2str = "My name is Kevin"
3
A. str(11)
B. str[11]
C. str:9
D. None of the above

Answer : B

11. Which Python module is used to parse dates in almost any string format?
A. datetime module
B. time module
C. calendar module
D. dateutil module

Answer : D

12. Which of the following is the correct way to indicate Hexadecimal Notation in

Python?
A. str = ‘\62’
B. str = ’62’
C. str = “62”
D. str = ‘\x62’

Answer : D

13. To begin slicing from the end of the string, which of the following is used in

Python?
A. Indexing
B. Negative Indexing
C. Begin with 0th index
D. Escape Characters
Answer : B

14. How to fetch characters from a given range in Python?


A. [:]
B. in operator
C. []
D. None of the above

Answer : A

15. How to capitalize only the first letter of a sentence in Python?


A. uppercase() method
B. capitalize() method
C. upper() method
D. None of the above

Answer : B

16. What is the correct way to get maximum value from Tuple in Python?
A. print (max(mytuple));
B. print (maximum(mytuple));
C. print (mytuple.max());
D. print (mytuple.maximum);

Answer : A

17. How to fetch and display only the keys of a Dictionary in Python?
A. print(mystock.keys())
B. print(mystock.key())
C. print(keys(mystock))
D. print(key(mystock))

Answer : A

18. How to align a string centrally in Python?


A. align() method
B. center() method
C. fill() method
D. None of the above
Answer : B

19. How to access value for key “Price” in the following Python Dictionary:
1
2mystock = {
3"Product": "Earphone",
4"Price": 800,
5"Quantity": 50,
6"InStock" : "Yes"
7}
8
A. mystock[“Product”]
B. mystock(“Product”)
C. mystock[Product]
D. mystock(Product)

Answer : A

20. How to set the tab size to 6 in Python Strings?


A. expandtabs(6)
B. tabs(6)
C. expand(6)
D. None of the above

Answer : A

21. ___________ uses square brackets for comma-separated values in Python? Fill

in the blanks with a Python collection?


A. Lists
B. Dictionary
C. Tuples
D. None of the above

Answer : A

22. Are Python Tuples faster than Lists?


A. TRUE
B. FALSE

Answer : A
23. How to find the index of the first occurrence of a specific value “i”, from string

“This is my website”?
A. str.find(“i”)
B. str.find(i)
C. str.index()
D. str.index(“i”)

Answer : D

24. How to display whether the date is AM/PM in Python?


A. Use the %H format code
B. Use the %p format code
C. Use the %y format code
D. Use the %I format code

Answer : B

25. Which of the following is the correcy way to access a specific element from a

Multi-Dimensional List?
A. list[row_size:column_size]
B. list[row_size][column_size]
C. list[(row_size)(column_size)]
D. None of the above

Answer : B

26. Which of the following Bitwise operators in Python shifts the left operand

value to the right, by the number of bits in the right operand. The rightmost bits

while shifting fall off?


A. Bitwise XOR Operator
B. Bitwise Right Shift Operator
C. Bitwise Left Shift Operator
D. None of the Above

Answer : B
27. How to specify range of index in Python Tuples? Let’s say our tuple name is

“mytuple”
A. print(mytuple[1:4])
B. print(mytuple[1 to 4])
C. print(mytuple[1-4])
D. print(mytuple[].slice[1:4])

Answer : A

28. How to correctly create a function in Python?


A. demoFunction()
B. def demoFunction()
C. function demoFunction()
D. void demoFunction()

Answer : B

29. Which one of the following is a valid identifier declaration in Python?


A. str = “demo666”
B. str = “666”
C. str = “demo demo2”
D. str = “$$$666”

Answer : A

30. How to check whether all the characters in a string is printable?


A. print() method
B. printable() method
C. isprintable() method
D. echo() method

Answer : C

31. How to delete an element in a Dictionary with a specific key. Let’s say we need

to delete the key “Price”


A. del dict[‘Price’]
B. del.dict[‘Price’]
C. del dict(‘Price’)
D. del.dict[‘Price’]
Answer : A
32. How to swap case in Python i.e. lowercase to uppercase and vice versa?
A. casefold() method
B. swapcase() method
C. case() method
D. title() method

Answer : B

33. The def keyword is used in Python to?


A. Define a function name
B. Define a list
C. Define an array
D. Define a Dictionary

Answer : A

34. Which of the following is used to empty the Dictionary in Python? Let’s say

our dictionary name is “mystock”.


A. mystock.del()
B. clear mystock
C. del mystock
D. mystock.clear()

Answer : D

35. How to display only the day number of year in Python?


A. date.strftime(“%j”)
B. date.strftime(“%H”)
C. date.strftime(“%I”)
D. date.strftime(“%p”)

Answer : A

36. What is used in Python functions, if you have no idea about the number of

arguments to be passed?
A. Keyword Arguments
B. Default Arguments
C. Required Arguments
D. Arbitrary Arguments
Answer : D
37. What is the correct way to create a Dictionary in Python?
A. mystock = {“Product”: “Earphone”, “Price”: 800, “Quantity”: 50}
B. mystock = {“Product”- “Earphone”, “Price”-800, “Quantity”-50}
C. mystock = {Product[Earphone], Price[800], Quantity[50]}
D. None of the above

Answer : A

38. In Python Functions, what is to be used to skip arguments or even pass them in

any order while calling a function?


A. Keyword arguments
B. Default Arguments
C. Required Arguments
D. Arbitrary Arguments

Answer : A

39. How to get the total length of Tuple in Python?


A. count() method
B. length() method
C. len() method
D. None of the above

Answer : C

40. How to access a value in Tuple?


A. mytuple(1)
B. mytuple{1}
C. mytuple[1]
D. None of the above

Answer : C

41. What is to be used to create a Dictionary of arguments in a Python function?


A. Arbitrary arguments in Python (*args)
B. Arbitrary keyword arguments in Python (**args)
C. Keyword Arguments
D. Default Arguments

Answer : B
42. How to convert the lowercase letters in the string to uppercase in Python?
A. upper()
B. uppercase()
C. capitalize()
D. toUpper()

Answer : A

43. What is the correct way to get minimum value from a List in Python?
A. print (minimum(mylist));
B. print (min(mylist));
C. print (mylist.min());
D. print (mylist.minimum());

Answer : B

44. Is using return statement optional in a Python Function?


A. Yes
B. No

Answer : A

45. Which of the following correctly converts int to float in Python?


A. res = float(10)
B. res = convertToFloat(10)
C. None of the above

Answer : A

46. How to get the type of a variable in Python?


A. print(typeOf(a))
B. print(typeof(a))
C. print(type(a))
D. None of the above

Answer : C
47. How to compare two operands in Python and check for equality? Which

operator is to be used?
A. =
B. in operator
C. is operator
D. == (Answer)

Answer : D

48. What is the correct way to get minimum value from Tuple?
A. print (min(mytuple));
B. print (minimum(mytuple));
C. print (mytuple.min());
D. print (mytuple.minimum);

Answer : A

49. How to display only the current month’s number in Python?


A. date.strftime(“%H”)
B. date.strftime(“%I”)
C. date.strftime(“%p”)
D. date.strftime(“%m”)

Answer : D

50. How to compare two objects and check whether they have same memory

locations?
A. is operator
B. in operator
C. **
D. Bitwise operators

Answer : A
51. How to fetch and display only the values of a Dictionary in Python?
A. print(mystock.value())
B. print(mystock.values())
C. print(values(mystock))
D. print(value(mystock))

Answer : A

52. Which operator is used in Python to raise numbers to the power?


A. Bitwise Operators
B. Exponentiation Operator (**)
C. Identity Operator (is)
D. Membership Operators (in)

Answer : B

53. Can we create a Tuple in Python without parenthesis?


A. TRUE
B. FALSE

Answer : A

54. ____________ represents key-value pair in Python?


A. Tuples
B. Lists
C. Dictionary
D. All the Above

Answer : C

55. Which of the following Bitwise operators sets each bit to 1, if only one of them

is 1, i.e. if only one of the two operands are 1.


A. Bitwise XOR
B. Bitwise OR
C. Bitwise AND
D. Bitwise NOT

Answer : A
56. What is the correct way to get maximum value from a List in Python?
A. print (maximum(mylist));
B. print (mylist.max());
C. print (max(mylist));
D. print (mylist.maximum());

Answer : C

57. An example to correctly begin searching from the end range of index in

Python Tuples. Let’s say our Python Tuple has 4 elements


A. print(mytuple[-3 to -1])
B. print(mytuple[3-1])
C. print(mytuple[].slice[-3:-1])
D. print(mytuple[-3:-1])

Answer : D

58. Which of the following Bitwise operators in Python shifts the left operand

value to the left, by the number of bits in the right operand. The leftmost bits

while shifting fall off.


A. Bitwise XOR Operator
B. Bitwise Right Shift Operator
C. Bitwise Left Shift Operator
D. None of the Above

Answer : C

59. Can we update Tuples or any of its elements in Python after assignment?
A. Yes
B. No

Answer : A
60. How to display only the current month’s name in Python?
A. date.strftime(“%H”)
B. date.strftime(“%B”)
C. date.strftime(“%m”)
D. date.strftime(“%d”)

Answer : B

61. ___________ uses Parenthesis for comma-separated values in Python? Fill in

the blanks with a Python collection?


A. List
B. Tuples
C. None of the above

Answer : B

62. How to create an empty Tuple in Python?


A. mytuple = ()
B. mytuple = (0)
C. mytuple = 0
D. mytuple =

Answer : A

63. Can we have duplicate keys in Python Dictionary?


A. TRUE
B. FALSE

Answer : B

64. Lists in Python are Immutable?


A. TRUE
B. FALSE

Answer : B
65. What is the correct way to create a list with type float?
A. mylist = [5.7, 8.2, 9. 3.8, 2.9]
B. mylist = (5.7, 8.2, 9. 3.8, 2.9)
C. mylist = {5.7, 8.2, 9. 3.8, 2.9}
D. None of the above

Answer : A

66. How to display only the day number of year in Python?


A. date.strftime(“%j”)
B. date.strftime(“%H”)
C. date.strftime(“%I”)
D. date.strftime(“%p”)

Answer : A

67. Delete multiple elements in a range from a Python List


A. del mylist[2:4]
B. del mylist(2:4)
C. del mylist[2 to 4]
D. del mylist(2 to 4)

Answer : A

68. How to fetch last element from a Python List with negative indexing?
A. print(“Last element = “,mylist[0])
B. print(“Last element = “,mylist[])
C. print(“Last element = “,mylist[-1])
D. None of the above

Answer : C

69. What is the correct way to get the length of a List in Python?
A. mylist.count()
B. count(mylist)
C. len(mylist)
D. length(mylist)

Answer : C
70. To get today’s date, which Python module is to be imported?
A. calendar module
B. datetime module
C. dateutil module
D. None of the above

Answer : B
UNIT-V
OBJECT ORIENTED PROGRAMMING

Multiple Choice Questions

1.Which of the following is correct with respect to OOP concept in Python?

A. Objects are real world entities while classes are not real.
B. Classes are real world entities while objects are not real.
C. Both objects and classes are real world entities.
D. Both object and classes are not real.
Ans : A
Explanation: In OOP, classes are basically the blueprint of the objects. They
doesnot have physical existence.

2. How many objects and reference variables are there for the given Python code?

class A:

print("Inside class")

A()

A()

obj=A()

A. 2 and 1
B. 3 and 3
C. 3 and 1
D. 3 and 2
Ans : C
Explanation: obj is the reference variable here and an object will be created each
time A() is called.So there will be 3 objects created.

3. Which of the following is False with respect Python code?

class Student:

def __init__(self,id,age):

self.id=id
self.age=age

std=Student(1,20)

A. "std" is the reference variable for object Student(1,20)


B. id and age are called the parameters.
C. Every class must have a constructor.
D. None of the above
Ans : C
Explanation: It is not mandatory for a class to have a constructor.

4. What will be the output of below Python code?

class Student:

def __init__(self,name,id):

self.name=name

self.id=id

print(self.id)

std=Student("Simon",1)

std.id=2

print(std.id)
A. 1
1
B. 1
2
C. 2
1
D. 2
2
Ans : B
Explanation: When object with id =1 is created for Student, constructor is invoked
and it prints 1. Later, id has been changed to 2, so next print statement prints 2.

5. What will be the output of below Python code?


class A():
def __init__(self,count=100):
self.count=count
obj1=A()
obj2=A(102)
print(obj1.count)
print(obj2.count)

A. 100
100
B. 100
102
C. 102
102
D. Error
Ans : B
Explanation: By default,the value of "count" is 100, so obj1.count=100. For
second object, value of "count" is 102, so obj2.count=102.

6. Which of the following is correct?

class A:

def __init__(self,name):

self.name=name

a1=A("john")

a2=A("john")

A. id(a1) and id(a2) will have same value.


B. id(a1) and id(a2) will have different values.
C. Two objects with same value of attribute cannot be created.
D. None of the above
Ans : B
Explanation: Although both a1 and a2 have same value of attributes,but these two
point to two different object. Hence, their id will be different.

7. Which of the following is correct?

class A:

def __init__(self):
self.count=5

self.count=count+1

a=A()

print(a.count)
A. 5
B. 6
C. 0
D. Error
Ans : D
Explanation: It will throw an error as inside constructor, "count" is not defined.

8. Which of the following is correct?

class Book:

def __init__(self,author):

self.author=author

book1=Book("V.M.Shah")

book2=book1

A. Both book1 and book2 will have reference to two different objects of class Book.
B. id(book1) and id(book2) will have same value.
C. It will throw error as multiple references to same object is not possible.
D. None of the above
Ans : B
Explanation: book1 and book2 will reference to the same object. Hence, id(book1)
and id(book2) will have same value.

9. In python, what is method inside class?

A. attribute
B. object
C. argument
D. function
Ans : D
Explanation: In OOP of Python, function is known by "method".
10. What will be the output of below Python code?

class A:

def __init__(self,num):

num=3

self.num=num

def change(self):

self.num=7

a=A(5)

print(a.num)

a.change()

print(a.num)
A. 5
7
B. 5
5
C. 3
3
D. 3
7
Ans : D
Explanation: Inside constructor, self.num=3. First print statement prints 3. As,
method change() is invoked, self.num=7 and hence second print statement prints
7.

11. Which of these is not a fundamental features of OOP?


a) Encapsulation
b) Inheritance
c) Instantiation
d) Polymorphism

Answer: c
Explanation: Instantiation simply refers to creation of an instance of class. It is not
a fundamental feature of OOP.
12. Which of the following is the most suitable definition for encapsulation?
a) Ability of a class to derive members of another class as a part of its own definition
b) Means of bundling instance variables and methods in order to restrict access to
certain class members
c) Focuses on variables and passing of variables to functions
d) Allows for implementation of elegant software that is well designed and easily
modified

Answer: b
Explanation: The values assigned by the constructor to the class members is used to
create the object.

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

class Demo:
def __init__(self):
self.a = 1
self.__b = 1

def display(self):
return self.__b
obj = Demo()print(obj.a)
a) The program has an error because there isn’t any function to return self.a
b) The program has an error because b is private and display(self) is returning a
private member
c) The program runs fine and 1 is printed
d) The program has an error as you can’t name a class member using __b

Answer: c
Explanation: The program has no error because the class member which is public is
printed. 1 is displayed. Execute in python shell to verify.

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

class Demo:
def __init__(self):
self.a = 1
self.__b = 1
def display(self):
return self.__b

obj = Demo()print(obj.__b)
a) The program has an error because there isn’t any function to return self.a
b) The program has an error because b is private and display(self) is returning a
private member
c) The program has an error because b is private and hence can’t be printed
d) The program runs fine and 1 is printed

Answer: c
Explanation: Variables beginning with two underscores are said to be private
members of the class and they can’t be accessed directly.

15. Methods of a class that provide access to private members of the class are called
as ______ and ______
a) getters/setters
b) __repr__/__str__
c) user-defined functions/in-built functions
d) __init__/__del__

Answer: a
Explanation: The purpose of getters and setters is to get(return) and set(assign)
private instance variables of a class.

16. Which of these is a private data field?

def Demo:def __init__(self):


__a = 1
self.__b = 1
self.__c__ = 1
__d__= 1
a) __a
b) __b
c) __c__
d) __d__

Answer: b
Explanation: Variables such as self.__b are private members of the class.
17. What will be the output of the following Python code?

class Demo:
def __init__(self):
self.a = 1
self.__b = 1

def get(self):
return self.__b

obj = Demo()print(obj.get())
a) The program has an error because there isn’t any function to return self.a
b) The program has an error because b is private and display(self) is returning a
private member
c) The program has an error because b is private and hence can’t be printed
d) The program runs fine and 1 is printed

Answer: d
Explanation: Here, get(self) is a member of the class. Hence, it can even return a
private member of the class. Because of this reason, the program runs fine and 1 is
printed.

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

class Demo:
def __init__(self):
self.a = 1
self.__b = 1
def get(self):
return self.__b
obj = Demo()
obj.a=45print(obj.a)
a) The program runs properly and prints 45
b) The program has an error because the value of members of a class can’t be changed
from outside the class
c) The program runs properly and prints 1
d) The program has an error because the value of members outside a class can only be
changed as self.a=45

Answer: a
Explanation: It is possible to change the values of public class members using the
object of the class.

19. Private members of a class cannot be accessed.


a) True
b) False

Answer: b
Explanation: Private members of a class are accessible if written as follows:
obj._Classname__privatemember. Such renaming of identifiers is called as name
mangling.

20. The purpose of name mangling is to avoid unintentional access of private class
members.
a) True
b) False
Answer: a
Explanation: Name mangling prevents unintentional access of private members of a
class, while still allowing access when needed. Unless the variable is accessed with its
mangled name, it will not be found.

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

class fruits:
def __init__(self):
self.price = 100
self.__bags = 5
def display(self):
print(self.__bags)
obj=fruits()
obj.display()
a) The program has an error because display() is trying to print a private class member
b) The program runs fine but nothing is printed
c) The program runs fine and 5 is printed
d) The program has an error because display() can’t be accessed
Answer: c
Explanation: Private class members can be printed by methods which are members
of the class.

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

class student:
def __init__(self):
self.marks = 97
self.__cgpa = 8.7
def display(self):
print(self.marks)
obj=student()print(obj._student__cgpa)
a) The program runs fine and 8.7 is printed
b) Error because private class members can’t be accessed
c) Error because the proper syntax for name mangling hasn’t been implemented
d) The program runs fine but nothing is printed

Answer: a
Explanation: Name mangling has been properly implemented in the code given
above and hence the program runs properly.

23. Which of the following is false about protected class members?


a) They begin with one underscore
b) They can be accessed by subclasses
c) They can be accessed by name mangling method
d) They can be accessed within a class

Answer: c
Explanation: Protected class members can’t be accessed by name mangling.

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

class objects:
def __init__(self):
self.colour = None
self._shape = "Circle"
def display(self, s):
self._shape = s
obj=objects()print(obj._objects_shape)
a) The program runs fine because name mangling has been properly implemented
b) Error because the member shape is a protected member
c) Error because the proper syntax for name mangling hasn’t been implemented
d) Error because the member shape is a private member

Answer: b
Explanation: Protected members begin with one underscore and they can only be
accessed within a class or by subclasses.

25. Which feature of OOP indicates code reusability?


a) Encapsulation
b) Inheritance
c) Abstraction
d) Polymorphism

Answer: b
Explanation: Inheritance indicates the code reusability. Encapsulation and
abstraction are meant to hide/group data into one element. Polymorphism is to
indicate different tasks performed by a single entity.

26. If a function can perform more than 1 type of tasks, where the function name
remains same, which feature of OOP is used here?
a) Encapsulation
b) Inheritance
c) Polymorphism
d) Abstraction

Answer: c
Explanation: For the feature given above, the OOP feature used is Polymorphism.
Example of polymorphism in real life is a kid, who can be a student, a son, a
brother depending on where he is.

27. If different properties and functions of a real world entity is grouped or embedded
into a single element, what is it called in OOP language?
a) Inheritance
b) Polymorphism
c) Abstraction
d) Encapsulation
Answer: d
Explanation: It is Encapsulation, which groups different properties and functions of
a real world entity into single element. Abstraction, on other hand, is hiding of
functional or exact working of codes and showing only the things which are
required by the user.

28. Which of the following is not a feature of pure OOP?


a) Classes must be used
b) Inheritance
c) Data may/may not be declared using object
d) Functions Overloading

Answer: c
Explanation: Data must be declared using objects. Object usage is mandatory
because it in turn calls its constructors, which in turn must have a class defined. If
object is not used, it is a violation of pure OOP concept.

29. Which among the following doesn’t come under OOP concept?
a) Platform independent
b) Data binding
c) Message passing
d) Data hiding

Answer: a
Explanation: Platform independence is not feature of OOP. C++ supports OOP but
it’s not a platform independent language. Platform independence depends on
programming language.

30. Which feature of OOP is indicated by the following code?

class student{ int marks; };class topper:public student{ int age; topper(int
age){ this.age=age; } };
a) Inheritance
b) Polymorphism
c) Inheritance and polymorphism
d) Encapsulation and Inheritance

Answer: d
Explanation: Encapsulation is indicated by use of classes. Inheritance is shown by
inheriting the student class into topper class. Polymorphism is not shown here
because we have defined the constructor in the topper class but that doesn’t mean
that default constructor is overloaded.
31. Which feature may be violated if we don’t use classes in a program?
a) Inheritance can’t be implemented
b) Object must be used is violated
c) Encapsulation only is violated
d) Basically all the features of OOP gets violated

Answer: d
Explanation: All the features are violated because Inheritance and Encapsulation
won’t be implemented. Polymorphism and Abstraction are still possible in some
cases, but the main features like data binding, object use and etc won’t be used
hence the use of class is must for OOP concept.

32. How many basic features of OOP are required for a programming language to be
purely OOP?
a) 7
b) 6
c) 5
d) 4
Answer: a
Explanation: There are 7 basic features that define whether a programing language is
pure OOP or not. The 4 basic features are inheritance, polymorphism, encapsulation
and abstraction. Further, one is, object use is must, secondly, message passing and
lastly, Dynamic binding.

33. The feature by which one object can interact with another object is
_____________
a) Data transfer
b) Data Binding
c) Message Passing
d) Message reading

Answer: c
Explanation: The interaction between two object is called the message passing
feature. Data transfer is not a feature of OOP. Also, message reading is not a
feature of OOP.

34. ___________ underlines the feature of Polymorphism in a class.


a) Nested class
b) Enclosing class
c) Inline function
d) Virtual Function

Answer: d
Explanation: Virtual Functions can be defined in any class using the keyword
virtual. All the classes which inherit the class containing the virtual function, define
the virtual function as required. Redefining the function on all the derived classes
according to class and use represents polymorphism.

35. Which feature in OOP is used to allocate additional function to a predefined


operator in any language?
a) Operator Overloading
b) Function Overloading
c) Operator Overriding
d) Function Overriding

Answer: a
Explanation: The feature is operator overloading. There is not a feature named
operator overriding specifically. Function overloading and overriding doesn’t give
addition function to any operator.

36. Which among doesn’t illustrates polymorphism?


a) Function overloading
b) Function overriding
c) Operator overloading
d) Virtual function

Answer: b
Explanation: Function overriding doesn’t illustrate polymorphism because the
functions are actually different and theirs scopes are different. Function and
operator overloading illustrate proper polymorphism. Virtual functions show
polymorphism because all the classes which inherit virtual function, define the
same function in different ways.

37. Exception handling is a feature of OOP.


a) True
b) False

Answer: a
Explanation: Exception handling is a feature of OOP as it includes classes concept
in most of the cases. Also it may come handy while using inheritance.

38. Which among the following, for a pure OOP language, is true?
a) The language should follow 3 or more features of OOP
b) The language should follow at least 1 feature of OOP
c) The language must follow only 3 features of OOP
d) The language must follow all the rules of OOP
Answer: d
Explanation: The language must follow all the rules of OOP to be called a purely
OOP language. Even if a single OOP feature is not followed, then it’s known to be
a partially OOP language.

39. Does OOP provide better security than POP?


a) Always true for any programming language
b) May not be true with respect to all programming languages
c) It depends on type of program
d) It’s vice-versa is true
Answer: a

Explanation: It is always true as we have the facility of private and protected access
specifiers. Also, only the public and global data are available globally or else the
program should have proper permission to access the private data.

40. Which among the following best describes polymorphism?


a) It is the ability for a message/data to be processed in more than one form
b) It is the ability for a message/data to be processed in only 1 form
c) It is the ability for many messages/data to be processed in one way
d) It is the ability for undefined message/data to be processed in at least one way

Answer: a
Explanation: It is actually the ability for a message / data to be processed in more
than one form. The word polymorphism indicates many-forms. So if a single entity
takes more than one form, it is known as polymorphism.

41. What do you call the languages that support classes but not polymorphism?
a) Class based language
b) Procedure Oriented language
c) Object-based language
d) If classes are supported, polymorphism will always be supported

Answer: c
Explanation: The languages which support classes but doesn’t support
polymorphism, are known as object-based languages. Polymorphism is such an
important feature, that is a language doesn’t support this feature, it can’t be called
as a OOP language.

42. Which among the following is the language which supports classes but not
polymorphism?
a) SmallTalk
b) Java
c) C++
d) Ada
Answer: d
Explanation: Ada is the language which supports the concept of classes but doesn’t
support the polymorphism feature. It is an object-based programming language.
Note that it’s not an OOP language.

43. If same message is passed to objects of several different classes and all of those
can respond in a different way, what is this feature called?
a) Inheritance
b) Overloading
c) Polymorphism
d) Overriding

Answer: c
Explanation: The feature defined in question defines polymorphism features. Here
the different objects are capable of responding to the same message in different
ways, hence polymorphism.

44. Which class/set of classes can illustrate polymorphism in the following code?

abstract class student{


public : int marks;
calc_grade();}class topper:public student{
public : calc_grade()
{
return 10;
}};class average:public student{
public : calc_grade()
{
return 20;
}};class failed{ int marks; };
a) Only class student can show polymorphism
b) Only class student and topper together can show polymorphism
c) All class student, topper and average together can show polymorphism
d) Class failed should also inherit class student for this code to work for
polymorphism

Answer: c
Explanation: Since Student class is abstract class and class topper and average are
inheriting student, class topper and average must define the function named
calc_grade(); in abstract class. Since both the definition are different in those
classes, calc_grade() will work in different way for same input from different
objects. Hence it shows polymorphism.

45. Which type of function among the following shows polymorphism?


a) Inline function
b) Virtual function
c) Undefined functions
d) Class member functions

Answer: b
Explanation: Only virtual functions among these can show polymorphism. Class
member functions can show polymorphism too but we should be sure that the same
function is being overloaded or is a function of abstract class or something like this,
since we are not sure about all these, we can’t say whether it can show
polymorphism or not.

46. In case of using abstract class or function overloading, which function is supposed
to be called first?
a) Local function
b) Function with highest priority in compiler
c) Global function
d) Function with lowest priority because it might have been halted since long time,
because of low priority

Answer: b
Explanation: Function with highest priority is called. Here, it’s not about the thread
scheduling in CPU, but it focuses on whether the function in local scope is present
or not, or if scope resolution is used in some way, or if the function matches the
argument signature. So all these things define which function has the highest
priority to be called in runtime. Local function could be one of the answer but we
can’t say if someone have used pointer to another function or same function name.

47. Which among the following can’t be used for polymorphism?


a) Static member functions
b) Member functions overloading
c) Predefined operator overloading
d) Constructor overloading

Answer: a
Explanation: Static member functions are not property of any object. Hence it can’t
be considered for overloading/overriding. For polymorphism, function must be
property of object, not only of class.
48. What is output of the following program?

class student{
public : int marks;
void disp()
{
cout<<”its base class”
};
class topper:public student
{
public :
void disp()
{
cout<<”Its derived class”;
}
}
void main() { student s; topper t;
s.disp();
t.disp();}
a) Its base classIts derived class
b) Its base class Its derived class
c) Its derived classIts base class
d) Its derived class Its base class

Answer: a
Explanation: You need to focus on how the output is going to be shown, no space
will be given after first message from base class. And then the message from
derived class will be printed. Function disp() in base class overrides the function of
base class being derived.

49. Which among the following can show polymorphism?


a) Overloading ||
b) Overloading +=
c) Overloading <<
d) Overloading &&
Answer: c
Explanation: Only insertion operator can be overloaded among all the given options.
And the polymorphism can be illustrated here only if any of these is applicable of
being overloaded. Overloading is type of polymorphism.

50. Find the output of the following program.

class education{
char name[10];
public : disp()
{
cout<<”Its education system”;
}
class school:public education
{
public: void dsip()
{
cout<<”Its school education system”;
}
};
void main()
{
school s;
s.disp();
}}
a) Its school education system
b) Its education system
c) Its school education systemIts education system
d) Its education systemIts school education system

Answer: a
Explanation: Notice that the function name in derived class is different from the
function name in base class. Hence when we call the disp() function, base class
function is executed. No polymorphism is used here.
51. Polymorphism is possible in C language.
a) True
b) False

Answer: a
Explanation: It is possible to implement polymorphism in C language, even though it
doesn’t support class. We can use structures and then declare pointers which in turn
points to some function. In this way we simulate the functions like member functions
but not exactly member function. Now we can overload these functions, hence
implementing polymorphism in C language.

52. Which problem may arise if we use abstract class functions for polymorphism?
a) All classes are converted as abstract class
b) Derived class must be of abstract type
c) All the derived classes must implement the undefined functions
d) Derived classes can’t redefine the function

Answer: c
Explanation: The undefined functions must be defined is a problem, because one may
need to implement few undefined functions from abstract class, but he will have to
define each of the functions declared in abstract class. Being useless task, it is a
problem sometimes.

53. Which among the following is not true for polymorphism?


a) It is feature of OOP
b) Ease in readability of program
c) Helps in redefining the same functionality
d) Increases overhead of function definition always

Answer: d
Explanation: It never increases function definition overhead, one way or another if
you don’t use polymorphism, you will use the definition in some other way, so it
actually helps to write efficient codes.

54. If 2 classes derive one base class and redefine a function of base class, also
overload some operators inside class body. Among these two things of function and
operator overloading, where is polymorphism used?
a) Function overloading only
b) Operator overloading only
c) Both of these are using polymorphism
d) Either function overloading or operator overloading because polymorphism can be
applied only once in a program

Answer: d
Explanation: Both of them are using polymorphism. It is not necessary that
polymorphism can be used only once in a program, it can be used anywhere, any
number of times in a single program.

Q. Which of the following represents a distinctly identifiable entity in the real


world?

A. A class
B. An object
C. A method
D. A data field
Answer. B

Q. Which of the following represents a template, blueprint, or contract that


defines objects of the same type?

A. A class
B. An object
C. A method
D. A data field
Answer. A

Q. Which of the following keywords mark the beginning of the class


definition?

A. def
B. return
C. class
D. All of the above.
Answer. C

Q. Which of the following is required to create a new instance of the class?

A. A constructor
B. A class
C. A value-returning method
D. A None method
Answer. A

Q. Which of the following statements is most accurate for the declaration x =


Circle()?

A. x contains an int value.


B. x contains an object of the Circle type.
C. x contains a reference to a Circle object.
D. You can assign an int value to x.
Answer. C

Q. What will be the output of the following code snippet?

class Sales:
def __init__(self, id):
self.id = id
id = 100
val = Sales(123)
print (val.id)

A. SyntaxError, this program will not run


B. 100
C. 123
D. None of the above
Answer. C

Q. Which of the following statements are correct?

A. A reference variable is an object.


B. A reference variable refers to an object.
C. An object may contain other objects.
D. An object can contain the references to other objects.
Answer. B , D

Q. Which of the following can be used to invoke the __init__ method in B from
A, where A is a subclass of B?

A. super().__init__()
B. super().__init__(self)
C. B.__init__()
D. B.__init__(self)
Answer. A, D

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

class test:
def __init__(self,a=""Hello World""):
self.a=a
def display(self):
print(self.a)
obj=test()
obj.display()

(A) The program has an error because constructor can’t have default arguments
(B) Nothing is displayed
(C) “Hello World” is displayed
(D) The program has an error display function doesn’t have parameters
Answer: C
Explanation: The program has no error. “Hello World” is displayed. Execute in
python shell to verify.

Q. Which of the following is not a class method?


(A) Non-static
(B) Static
(C) Bounded
(D) Unbounded
Answer: A
Explanation: The three different class methods in Python are static, bounded and
unbounded methods.
Q. What are the methods which begin and end with two underscore characters
called?
(A) Special methods
(B) In-built methods
(C) User-defined methods
(D) Additional methods
Answer: A
Explanation: Special methods like __init__ begin and end with two underscore
characters.
Q. Special methods need to be explicitly called during object creation.
(A) TRUE
(B) FALSE
Answer:B
Explanation: Special methods are automatically called during object creation.
Q. __del__ method is used to destroy instances of a class.
(A) TRUE
(B) FALSE
Answer: A
Explanation: ___del__ method acts as a destructor and is used to destroy objects of
classes.
Q. Suppose B is a subclass of A, to invoke the __init__ method in A from B, what is
the line of code you should write?
(A) A.__init__(self)
(B) B.__init__(self)
(C) A.__init__(B)
(D) B.__init__(A)
Answer: A
Explanation: To invoke the __init__ method in A from B, either of the following
should be written: A.__init__(self) or super().__init__(self).

Q. What will be the output of below Python code?


class Student:
def __init__(self,name,id):
self.name=name
self.id=id
print(self.id)

std=Student("Simon",1)
std.id=2
print(std.id)

A. 1
1
B. 1
2
C. 2
1
D. 2
2
Ans : B

Explanation: When object with id =1 is created for Student, constructor is invoked and
it prints 1. Later, id has been changed to 2, so next print statement prints 2.

Q. What will be the output of below Python code?


class A():
def __init__(self,count=100):
self.count=count
obj1=A()
obj2=A(102)
print(obj1.count)
print(obj2.count)

A. 100
100
B. 100
102
C. 102
102
D. Error
Ans : B

Explanation: By default,the value of "count" is 100, so obj1.count=100. For second


object, value of "count" is 102, so obj2.count=102.
Q. In python, what is method inside class?

A. attribute
B. object
C. argument
D. function
Ans : D

Explanation: In OOP of Python, function is known by "method".

Q. Study the following program:


class Std_Name:
def __init__(self, Std_firstName, Std_Phn, Std_lastName):
self.Std_firstName = Std_firstName
self. Std_PhnStd_Phn = Std_Phn
self. Std_lastNameStd_lastName = Std_lastName

Std_firstName = "Wick"
name = Std_Name(Std_firstName, 'F', "Bob")
Std_firstName = "Ann"
name.lastName = "Nick"
print(name.Std_firstName, name.Std_lastName)

What will be the output of this statement?


A. Ann Bob

B. Ann Nick

C. Wick Bob

D. Wick Nick

Answer: (d) Wick Nick

Q. Which of the following option is not a core data type in the python language?

A. Dictionary
B. Lists
C. Class
D. All of the above

Answer: C

Q. Which of these is a private data field?


def Demo:
def __init__(self):
__a = 1
self.__b = 1
self.__c__ = 1
__d__= 1

A. __a

B. __b

C. __c__

D. __d__

Answer: B
Explanation: Variables such as self.__b are private members of the class.

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


class demo():
def __repr__(self):
return '__repr__ built-in function called'
def __str__(self):
return '__str__ built-in function called'
s=demo()
print(s)

A. Error
B. Nothing is printed
C. __str__ called
D. __repr__ called
Answer: C
Explanation: __str__ is used for producing a string representation of an object’s value
that Python can evaluate. Execute in python shell to verify.

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


class test:
def __init__(self,a="Hello World"):
self.a=a

def display(self):
print(self.a)
obj=test()
obj.display()

A. The program has an error because constructor can’t have default arguments
B. Nothing is displayed
C. “Hello World” is displayed
D. The program has an error display function doesn’t have parameters

Answer: C
Explanation: The program has no error. “Hello World” is displayed. Execute in
python shell to verify.

You might also like