0% found this document useful (0 votes)
230 views

Total MCQ

The document contains questions and answers related to Python programming concepts. It covers topics like list comprehensions, functions, classes, exceptions, file handling, and more. Multiple choice questions are provided along with explanations for concepts tested in Python interviews and assessments.

Uploaded by

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

Total MCQ

The document contains questions and answers related to Python programming concepts. It covers topics like list comprehensions, functions, classes, exceptions, file handling, and more. Multiple choice questions are provided along with explanations for concepts tested in Python interviews and assessments.

Uploaded by

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

1.select the list comprehension code equivalent to the below script.

sum=[] for x in (range(1,3)

for y in range(3,6)

sum append(x+y)

1.sum=[x + y doe x in range(1,3) for y in range(3,6)]

2.sum=for x in range(1,3) for y in range(3,6) print x+y]

3.sum=[ return x+y for y in range(1,3) for x in range(3,6)]

4.sum=[ for x in range(1,3) for y in range(3,6) return x+y]

ans:a
===================================================================

2. which function is used to read two charecters from a file object in file?

a. infile.readline(2)

b.infile.read(2)

c.infile.read()

d.infile.readlines(2)
ans:b
===================================================================

3. which function is used to write the data in the binary format?

a.dump

b.write

c.output

d. all of the above


ans:a

===================================================================
4.which collection is used to store unique values?

list /dict/tuple/set
ans:set
===================================================================

5.identify the output print((2,4)+(6,8))

a.(2,4,6,8)

b.error

c.{4,6}

d.{(2,4),(6,8)}
ans:a
===================================================================

4. class Name(object)

def first(

print("Iam callled")

def second()

print("i got called")

obj=Name()

Name.first(obj)

******
a. unbound method call

b. bounded method call

c.incorrect object declaration

d.all the above

ans:a
===================================================================
5.which is appropriate to use the static method in a class?

a.to access the attribute of the instance

b. to instantiate the class based on the given parameter


c.to perform the action relevant to the class without instantiating the class
d. to access the static members of the class
Ans:C

===================================================================

6. which function displaya a file dialog for opening an existing file?

a. tmpfile=askopenfilename()

b.tmpfile=openfilename()

c.tmpfile=saveasfilename()

d.tmpfile=asksaveasfilename()

ans:A
===================================================================
7. def demo():

try;

print(1)

finally;
print(2)

demo()

a.2

b.1 2

c.1

Ans:b
===================================================================
7.on what condition finally block gets executed?

1.on sepecific condition

2.on exceptions

3.on errors

4.always
ans:D
===================================================================

8. select the correct option

a. none of the listed options

b.a user defined exception can be created by deriving a class from error class.

c.custom exceptions is unavailable in python

d. a user definedexception can be created by deriving a class from exception class.

ans:D

===================================================================

9.select the code snippet that divide by zero error with error message " number
cannot be divided with zero"

a. try: 1/except:raise

b.try: 1/except ax e : print(e)

c. try: 1/ except ZeroDivisionError: print("number cannot be divided with zero")

d.try: 1/ except ValueError: print (("number cannot be divided with zero")

ans:C
===================================================================

10.identify the output-


for i in [1,0]: print(i+1)

a.1

b. 2 1

c.1 1

Ans:B

===================================================================

11.identify the output

y=["test",'Done]

for i in y:i.upper() print(y)

a.['test','done']

b.['TEST','DONE']

c. none of the listed options

d.[None,None]

Ans:a

===================================================================

12.select the correct match

1.__iter__2 next

a.method that is called a initialization of an iterator

b. the iterator next method return the next value for the iterable.

options

--------

a. 1 -a 2 -b

b.***

b.****

d.***
ans:a

===================================================================

13.numbers=[2,4,6,8,1]

newnumbers= tuple(map(lamda x:x*x,numbers))

print(newnumbers)

a.(4,16,36,64,1)

b.(2,4,6,8,1)

c.[2,4,6,8,1]

d.[4,16,36,64,1]

ans:a

===================================================================

14.what is the o/p

def string_reverse(str1): str2=" index=len(str1)

while index>0;

str2 +=str1[index-1]

index=index-1

return str2

print(string_reverse('5678ABCD'))

a.5678ABCD

b.8765DCBA

c.DCBA8765

D.none of the above

ans:C
===================================================================
14.which of the following code uses inheritance?

a.class Hello: Pass class world(Hello):Pass

b.class Hello: Pass

c. class Hello: Pass class Test: Pass class World(Hello,Test):Pass


d. none of the above

ans:a,c

===================================================================
5.code snippet

class Company:

def__init__(self,name,empnum);

self.name=name

self.empnum=empnum

def myfunc(self);

print("Welcome to"+self.name+' '+self.empnum)

p1=Company("Cognizant","12345")

a.Welcome to Cognizant

b.Syntax error, this program will not run

c. Welcome to Cognizant 12345

d. Cognizant 12345

ans:C
===================================================================
16. code snippet

def coverFunction();

global a

a=4

def innerFunction();

global a

a=5

print('a=',a)

a=6

coverFunction()

print('a=',a)

a.a=5 a=4

b.a=5

c.a=6
d.a=4

ans:d
===================================================================
17.List the return type of format function on strings

a.boolean

b.string

c.error

d.integer

ans:b
===================================================================
18.true or false

output of the below statement is "Python"

str_variable="Hello Python"

print(str_variable[6:11])

select one

a. true

b.false

Ans:b
===================================================================

19.which keyword is used at the begining of the class definition

a.pass

b.class

c.__init__

d.def

Ans:b
===================================================================

20.o/p of the code

import OrderedDict

my_string1="Welcome 1"

print(my_string1)

my_string2= "Welcome 2"


print(my_string2)

my_string3="Welcome 4"

print(my_string3)

my_string4="""Welcome All"""

a. Welcome 1 Welcome 2 Welcome 4 Welcome All

b. Error

c. Welcome 1 Welcome 2 Welcome 4

d.Welcome 1 Welcome 2

ans:a
===================================================================

21.choose the correct option

class py_Arraysum

def twoSum(self,numbers,total);

lookup={}

if total-num in lookup;

return(lookup[total-num]+1,i+1)

lookup[num]=i

print("Number1=%d"%py_ArraySum().twoSum((3,1,4,5,2,7),6))

output: Number 1=2, Number2=4

Select one

a. none of the listed

b.while i,num in enumerate(numbers);

c. if i, num in enumerate(numbers);

d. for i, num in enumerate(numbers);

ANS:d

===================================================================
22. Let a tuplevalue contains 5 elements , how to set third element of the tuple to
'india'

a.def test

b.test[3]='india'
c.elements of the tuple remains unchanged

d.test[2]='india'

ans:c
===================================================================

22.identify the output

integer=[1,3,4,5,6,7,8,9]

print(integer[::3])

a.[1,3,5,7,9]

b.[1,3,5]

c.[1,3,5,7]

d.[1,4,7]

ans:[1,5,8]

===================================================================

23. sample_dict('n':3,'e':7,'o':9)

sorted(sample_dict)

a.[3,7,9]

b. {'n':3,'e':7,'o':9}

c.{'e':7.'n':3,'o':9}

d.[e,n,o]
Ans:d
===================================================================

24.select the applicable to with statement( check box)

a.with statement is used to loop over a generator

b.with statement encapsulates try, except , finally patern for code reuse

c.with stement is used to alias an object

d.if an exception occurs in the block __exit__() method of the context manager is
called to clean up resources

ans:a,b,d
===================================================================

25.select the correct option that closes file if exception occurs

a. none of the listed options

b. with open("demo.txt", encoding='utf-8')as f # perform file operations


c. f=open("demo.txt",'f',encoding='utf-8') f.read()

d.try #code that can raise error pass


ans:b,d
===================================================================
26. identify the output

def demo():

try:

return 1

finally:

return 3

test=demo()

print(test)

a.error more than one return statement

b.3

c.1

Ans:b
===================================================================

27. identify the ouptut

file= None for i in range(5):

with open("hello.txt","w") as file

if i>2 break

print the closed

a. true

b.false

ANS:a
===================================================================
30. state the below statements are true or not
python module should contain only definitions like functions,classes and variables
and not statements like print
a. true
b.false

ans:b
===================================================================
31.what is the output of the following

def nameFruits("fruit):print("i love",fruit)


nameFruits('Apple','Mango','orange')

select one option

a.('I love',( 'Apple','Mango','orange'))

b.Syntax error nameFruits() can take only one argument

c. i love Apple i love Mango i love Orange

d. i love Apple
Ans:a

===================================================================
32. select the correct statement(check box)

a. a reference variable is an object

b. an object may contain other objects

c. an object can contain reference to other objects

d.a referance vaiable refers to an object.

Ans:c,d
===================================================================
33.output for the below code

class Hello:

__init__(self,name)

self.name=name sayHello(self):

print(self.name)

p1=Hello("Tom")

p2=Hello("Sam")

p2.sayHello()

a.Hello Tom

b.Sam

c.Tom

d.Hello Sam

ans:b
===================================================================
34. identify the output

class MapPoint:

def __init__(self,x=0,y=0):

self.x=x+2
self.y=y+3

s1=MapPoint()

print(s1.x,s1.y)

select one

a.error

b.2,3

c.x,y

d.,0

ans:b
===================================================================

35. select the correct statement

choose one or two

a.tuple is immutable and list is mutable

b.set is an unordered collection of unique items

c.Dictinoary is an ordered collection of key-value pairs

d.tuple is mutable and list is immutable

ans:a,b
===================================================================

36.choose the correct optiona to print pi constant

as declared in math module

a. from math import pi print(math pi)

b. from math import pi print(pi)

c.print(math pi)

d.print(pi)

ans:b
===================================================================
37. what does the "cycle " function drom "iterators" module do?

a. return a iterator wich cycles through the given list over and over again

b. returns a iterator for the given iteratable object

c.converts the given list into generator

d. cycles through the given list


ans:
===================================================================
38. what would be the function return if no return statement is used inside it

a. none object
b.an arbitary object
c.Error function must have a return statement.
ans:a

===================================================================
39. what happens if a non-existant file is opened?

a. new file gets created

b.open an alternative file

c.none of the listed options

d.raises an exception

ans:d

===================================================================

40. select the correct option

a.custom exception is unavailable in python

b. a user-defined exception can be created by deriving a class from exception class

c.none of the listed options

d.a user-defined exception can be deriving a class from error class

ans:a
===================================================================
41.select that all applicable to generators(check box)

a.generator help program to perform faster since the code do not wait for the while
data set to be generated.

b.generator are used only to loop over list

c.generator is memory efficient

d. generator yield stament returns one valut at time to the calling loop.
Ans:All

===================================================================

42. identify the output

cubes={1,1,28,3:27,4:64,5:125}

print(cubes pop(4))

print(cubes)
a.125{1:1,2:8,3:27,5:125}

b.4{1:1,2:8,3:27,5:125}

c.64{1:1,2:8,3:27,5:125}

d.none of the listed options

ans:c
===================================================================
1.Which action should be avoided so that you do not mistakenly overwrite names that you have
already defined?

use the wildcard import

2. While using Python IDLE, by how many space are the code suites indented?

3. When using the Python shell and code block, what triggers the interpreter to begin evaluating
block of code?

execute command (wrong answer)

4. The bool class is subset of .

int

5. Which statement correctly assigns X as an infinite number?

x=flot('inf')

6. Which statement accurately defines the bool class?

Boolean not return false if the oprand is True

7. bytearray provides an mutable sequence (making it modifiable)

true

8. Using Pop in list will remove the popped up item.

true

9. Which statements prevent the escape sequence interpretation?

r'col\tcol2\tcol3\t'

10. Empty dictionary is represented as .

{}

11. Consider b is frozen set, what happen to b.add(3)?

Error as Frozen set cannot be modified


12. All of these range types are correct except ___.

range(20,40,-2)

13. What is the output of below code snippet - for char in 'Welcome': print (char, end='*')
print()

W*e*l*c*o*m*e*

14. What is the output of the following code? for x in (1,10,100): print (x)

1 10 100

15. a = 0 if a: print("a's value") else: print("Sorry nothing will get printed")

Sorry nothing will get printed

16. What is the output of the following code count = 0 while count < 2: print (count, " is less
than 2") count = count + 2 else: print (count, " is not less than 2") - 0 is less than 2; 2 is not less
than 2

17. Which methods can be used with list objects?

Reverse, pop, clear

18. a = -10 if a: print("a's value") else: print("Sorry nothing will get printed") a's value

19. The 2 main versions of Python include Python

2.x & 3.x

20. In what format does the input function read the user input ?

String

21. What is the output of min('Infinity')? I - (Wrong, code output is I but dont know)

22. Which of these could be used in

tuple object Sorted,lens,Max

23. Code written in Python 3 is backward compatible with Python 2.

False

24. Python supports automatic garbage collection.


true

25. Bitwise operators cannot be used on the float type

false

26. Which of the following attributes shows the characteristics of Python? Python is everywhere
(Webscripting, 3D Modelling , Games , and Desktop applications ).

Object Oriented

27. a.difference(b) highlights the .

a-b

28. a.symmetricdifference(b) highlights the _. a.union(b) - a.intersection(b)

29. Values in bytearray should be integers between

0-255

30. Is x,y=5,6 a valid statement?

true

31. What command is used to output text from both the Python shell and within a Python
module?

print()

32. Which of these are salient features of Python, except?

limited platform Support

33. While using slicing in lists, list[0:2] is equivalent to . list[:2]

34. The default decode option available in the byte data type is unicode (Wrong answer)

35. What is the output of - listpt = list('Welcome') print(listpt)

['W', 'e', 'l', 'c', 'o', 'm', 'e']

36. Which of these methods can be used with list objects, except ?

decode,Lambda
37. The class which provides immutable sequence of elements tuple

*****************
Attempt 2
******************

1. You can send an email whenever the chef-client fails using ____ handler.

Report

2. Which of the following is not an event in chef-client run?

:deleted_cookbook

3. When the success property of the run_status object is true ____handler is executed.

Report

4. You can attach callbacks to events using ______.

Handlers

5. Which of the following is not a Chef Handler?

test

6. Which of the following are the built-in handlers in chef?

None of these

7. You can send an email whenever the chef-client fails using ____ handler.

event

8. To generate a new key for the vault use the command _____.

9. Chef maintains a log which has all the users who accessed it.

false

10. To update the content of the vault use the command ______.

Update
11. The chef server has the private part of the RSA key and the nodes/users has the public part
of the key.

false

12. To decrypt an item in the vault and open it in json format use the command _____.

edit

13. To delete a vault’s item, use the commad _____.

delete

14. The _____ resource from ohai cookbook will help you deploy ohai plugin.

ohai_plugin

15. Ohai plugins cannot make use of mixin libraries.

false

16. berks install is used to _______.

resolve dependencies

17. ____ is a dependency manager in cookbooks.

Berkshelf

18. To know what a chef client run would do, use the command _____. Why-run

19. The only way to load exception/report handlers is using client.rb.

false

19. Consider a cookbook with name ‘fresco’ and the files within the resource/providers
directory as ‘play’, then the custom resource will be ____.

fresco_play

20. The node related information are collected using _____.

ohai

21. The process of checking the state of resource collector using ChefSpec is called _______.
Unit Testing

22. Integration Testing uses ____

InSpec

23. The _____ object is used to run the report handler without any error handling.

run_report_unsafe

24. To run the knife commands in local mode instead of in server, use the option ____.

-z

25. Node related information from ohai are stored in a ______.

Node Object

26. The code to converge the system to desired state will be listed under ______.

providers

27. Use this option in the knife command to specify the files to be added to the vault item.

--file FILE

28. To see the test matrix use the command _____.

29. In a custom handler, _____ interface will define how the handler will behave.

30. The process of checking the desired state of the system is called ______.

Integrated Testing

31. The test files in ChefSpec will be place in _____ directory. /spec/unit --------------------------
******************
Puppet 5 - Cardinal
******************
1. Manifest files are stored as ____ file extension.

.pp

2. Puppet manifests are written in ______.

Domain Specific Language


3. Puppet does not run on Windows.

false

4. Puppet compiles catalog from ____.

All of them

5. What is the correct syntax for If-else conditional statment?

if{} elsif{} else

6. Which of the following is not used as a conditional statement?

while

7. Which function transforms data structure by removing non-matching elements?

filter

8. Which of the following mode is used to dry-run Puppet code?

--noop

9. Notify is to _____, whereas subscribe is to _____.

before,required

10. Which command is used for displaying facts in YAML format?

factor -y

11. Is it compulsory to preceed class parameters with its data type?

No

12. Which of the following is a valid input for file resource?

All

13. _____ is not a section in puppet.conf file.

mainifest

14. To see the value of a setting in Puppet, which of the following will you use?
puppet config print

15. You can override modulepath from the commandline using _____. --

modulepath

16. Manifests have logic (conditional statements) and Catalogs (compiled from manifests) do
not have logic.

true

17. Which attribute is used to start a service at boot time?

enable

18. _____ function is used to repeat a block of code any number of times.

each

19. You should install Ruby first before installing Puppet-Agent in machines.

No

20. Puppet code is written in _____ language.

declarative

21. Which of the following file does Puppet Agent downloads from Puppet Master?

catalog

22. Which of the following command is used in Standalone Architecture of Puppet?

puppet apply

23. _____ is used to see the modules you have installed.

puppet module list

24. Which of these is the default section in puppet.conf file, which is used by all commands and
services?

main

25. Which of the following is not a Pull based Configuration Management tool? Ansible
26. Puppet compiles catalog from _____. mainifest -- Wrong Answer, May be correct is All the
option

************************
Kibana - Data Exquisites ***************** ******
1. What can be created with the help of Kibana?

All of the above

2. If Elasticsearch is not visible via Kibana, what could be the problem?

Both of these

3. Is it necessary to use curl command while querying in Kibana?

No, not necessary

4. Default location to run Kibana is _.

localhost:5601

5. What is Kibana?

A visulization tool

6. Visualize page is responsible for __.

All of these

7. Geohash is used to create buckets based upon .

geo_point fileds

8. Which of the following is not a metric aggregation?

log

9. Date histogram is performed on date/time values that are automatically extracted from
documents.

true

10. In bucket aggregation, buckets are created to store _.

Documents
11. You can only set the Index pattern once.

false

12. A dashboard can be embedded in a HTML page.

true

13. How can we insert a dashboard into a HTML page?

With Embedded iframe

14. Why is Dashboard used for?

All of these

15. We can show multiple dashboards in visualization page.

false

16. Timelion is a . Time Series data visulizer

17. What is the function of Gauge? It indecates the status of metric in referance to a threshold
value

18. Discover is used for .

Both of these

19. Can you share a dashboard as we shared a visualization?

Yes, we can

20. Where can you access discover page in Kibana?

Top Left side below kibana logo

21. Anyone in the world can see the visualization with the help of the sharable link.

No, Only those client who have access to Kibana can view
QuestionBaSubBankDifficulty Leve Question Choice 1 Choice 2 Choice 3Choice G
4 radeGrade G
2 rade 3Grade 4
for x in range(0, 20):
print('hello %s' % x)
if x < 9:
Python Flow Control Simple break hello 0 hello 9 hello 1 hello 1 0 0 0

Python Identifiers Simple Which of the following are valid PyPython123 123Python ca$h def 1 0 0 0
Fin the output? >>> 5+4
9
>>> _
9
Python Basics Simple >>> _+15 SyntaxError: in 24 0 9 0 1 0 0

>>> a, _, b = (1, 2, 3)
Python Basics Simple >>> print(a,b) (1,2,3) (1,3) (1,_,2,3) None of the a 0 1 0 0
Find the output for the following
snippet.
_=5
while _ < 10:
print(_, end = ' ')
_ += 1
Python Flow Control Simple 56789 12345 10 9 8 7 6 Error 1 0 0 0

Find the output for the following


snippet.
print("{2} {0}
{1}".format("list","tuple","dictonoa
Python Data Strutcure Simple ry")) list tuple dicton dictionary list tupledictionary tuple li Syntax Error 0 1 0 0
Identify the output.

s=input("Enter a string:")
s1=s.replace(' ', '$')
print(s1)
Python Data Strutcure Simple Hello how are yHellohowareyou? Hello$how$are$yo'$' is an inval 0 0 1 0
Identify the output

s=input("Enter a string:")
s1=s[::-1]
print(s1)
Python Data Strutcure Simple n nohtyP yhn nhy 0 1 0 0

my_list = [2, 5, -4, 6]


c=[2 * item for item in my_list]
Python Data Strutcure Simple print© [4, 10, -8, 12] [4,25,-18,36] [[2,5,-4,6,2,5,-4,6 [2*2,5,-4,6] 1 0 0 0
Identify the output

a=[(a, b) for a in (1, 2, 3) for b in


(4, 5, 6)]
Python Flow Control Simple print(a) [(1, 4), (1, 5), ( [(1,2,3)],[(4,5,6)] [(1,4),(2,5),(3,6)] [(1,4),(2,4),(3 1 0 0 0
Identify the output

list_a= ['id', 'name', 'age']


list_b = [100, 'python', '30']
s= dict(zip(list_a,list_b))
print(s)
Python Data Strutcure Simple TypeError: Can{'id': 100, 'name': Invalid keyword 'Z None of the a 0 1 0 0
Identify the output

a = [1,2,3]
a.append(4,5)
print(a)
Python Data Strutcure Simple Error:append() [1,2,3,4,5] [1,2,3,(4,5)] [4,5,1,2,3] 1 0 0 0
Identify the output
def yrange(n):
i=0
while i < n:
Python Generators Average yield i [1,2,3,4,5] [5,4,3,2,1] [0, 1, 2, 3, 4] None of the a 0 0 1 0
Identify the output
s=input("Enter a string:")
s1=s[::2]
print (s1)

>>>Enter a string:hello how are


Python Data Structure Average you? Hlohwaeyu Hello are you? elhwru? are 1 0 0 0
Identify the output

subject1 = [
['Python', 'C++', 'Java'],
['HTML', 'XML', 'JSON']
]
import copy
subject2 =
copy.deepcopy(subject1)
subject2[0][0] = 'Javascript'
Python Deep copy Average print(subject2) [['Javascript', 'C[['Python', 'C++', 'J['Javascript','HTM [['HTML', 'XM 1 0 0 0
Identify the output

Python Function Average a = [10,20,30,40,50] [10, 20, 30, 40 [20, 40, 60, 80, 10Prints nothing [20, 40, 60, 8 0 0 1 0
Find the output for the following
snippet.
class SimpleClass:
def __method1(self):
return "Welcome to Python
Programming"

def call_method2(self):
return self.__method1()
Python Function Difficult AttributeError Welcome to PythoInvalid method ca None of the a 0 1 0 0
Identify the output for the
following code snippet

Python Flow Control Difficult def count_fruits(apple, orange): 11 100 75 150 1 0 0 0

Python Basics Simple Python is Intepreter compiler Assembler Link loader 1 0 0 0


Python Basics Simple _______is the distribution for larg IronPython Stackless Python Portable Python Anaconda Py 0 0 0 1

Python Regular ExpressAverage Which of the following is True abo Checks for a mChecks for a matcChecks all the posChecks all the possible matches in the entire sequence but returns r
Identify the output

list= [x for x in range(20) if x % 2


Python Flow Control Average [0, 6, 12, 18] [0,2,4,6,8,10,12,1 [0,3,6,9,12,15,18] None of the a 1 0 0 0
== 0 if x % 6 == 0]
Identify the output

list = [[1,2,3],[4,5,6],[7,8,9]]
result=[[row[i] for row in list] for i
in range(2)]
Python Data Structure Difficult print(result) [[1,2,3],[4,5,6]] [[4,5,6],[7,8,9]] [[1, 4, 7], [2, 5, 8]] [[1, 4, 7], [2, 5 0 0 10
Identify the output for the
following snippet.

tuple = (1, 1, [3,4])

a=id(tuple[0]) == id(tuple[1])
Python Data Structure Simple print(a) Equal TRUE FALSE None 0 1 0 0
Identify the output for the
following snippet.

a = (1, 1, [3,4])
a.append(5)
Python Data Structure Simple print(a) (1, 1, [3,4],5) (1, 1,5, [3,4]) (5,1, 1, [3,4]) Attribute Erro 0 0 0 1
Identify the output

t1 = (1,2,3,4)
Python Data Structure Simple t2 = [5,6,7,8] (1, 2, 3, 4, 5, 6 can only concaten((1,2,3,4)(5,6,7,8) (1,5,2,6,4,7,4 0 1 0 0
t= (1,)
print(any(t))
Python Data Structure Simple TRUE FALSE 1 0
Identify the type of 'a'

a='1',
Python Data Structure Simple print(type(a)) <class 'tuple'> <class 'str'> <class 'list'> invalid syntax 1 0 0 0
_____method in Python, it is
used to write a list of strings to
Python File Operation Simple the file Writelines() Writes() Write() Writable() 1 0 0 0
which of the following code
makes it useful when we want to
have a string that contains s=a'Hi\nHell
backslash and don’t want it to be s='Hi\nHello' s=r'Hi\nHello' s=b'Hi\nHello' o'
Python Data Structure Average treated as an escape character. print(s) print(s) print(s) print(s) 0 1 0 0
Identify the ouput

from collections import Counter


fruits = ['apple', 'orange',
'grapes', 'grapes', 'banana',
'orange', 'orange']
Python Data Strutcure Average print(Counter(fruits)) Counter({'appl Counter({'apple': Counter({3:'orang Counter({'ora 0 0 0 1
Which of the following is used to
represent the absence of a
Python Basics Simple value. None FALSE 0 Null 1 0 0 0
which of the following can be
used to split long statements
Python Simple over multiple lines. / \ // \\ 0 1 0 0
Which of the following keyword is
Python Function simple used to define a function block? def define create function fun 1 0 0 0
Identify the output

def function(hello, num = 2): Welcomepyth


print(hello * num) on
Welcomepyth pythonpython WelcomeWelco
function('Welcome') on WelcomeWelco me
Python Function Average function('python', 2) me pythonpython Attribute Erro 0 0 1 0
Python Function Simple Which of the following function takstr string toString type 1 0 0 0
Which of the following is an
expresstion that can be used as
a function shorthand that allows
us to embed a function within the
code.
Python Function Simple Filter define Lamda Func 0 0 1 0
Which of the following
arguments can be used in any
function where you are
expecting a variable number of
Python Function Simple arguments. ** Dict arg **kwarg 0 0 0 1
After del or remove is performed
on a list, the items following the
Python Data Structure Simple eliminated item are moved one posmoved one positioposition unchangeare moved fro 1 0 0 0
Identify the following output

def argu(**kwargs):
print(kwargs)
Python Function Average argu(a=10, b=20,c=30) [10,20,30] {'a': 10, 'b': 20, 'c' (10,20,30) {10,20,30} 0 1 0 0
_____method of the os module
in Python, returns a string that
contains the absolute path of the
Python Module Simple current working directory. getcwd() getpwd() getdir() presentdir() 1 0 0 0
Identify the type of module that
provides access to some
variables used or maintained by
the interpreter and to functions
that interact strongly with the
interpreter
Python Module Simple OS module collection module sys module math module 0 0 1 0
Identify the statements True/
False about equality operator

Statement 1:An is expression


outputs True if both variables
are pointing to the same
reference

Statement 2:An == expression


outputs True if both variables
contain the same data
Python Basics Average Only statemen Only statement 2 Both the Stateme Both the state 0 0 1 0
Identify the output

list=[10,0,9,8,3,7,4,6,1,None]
Python list.sort() TypeError [0,1,3,4,6,7,8,9,10[None,0,1,3,4,6,7 [None,0,1,3,4 1 0 0 0
Identify the output

subject=[]
subject.append('Python')
subject.append('Java')
subject.append('C++')
Python Data Structure Average print(subject.pop()) C++ Python Java None of the a 1 0 0 0
Identify the statements True/
False about any(),all()

any() returns True if any values


in the returned list evaluate to
True.

all() returns True only if all


values in the returned list are
Python Data Structure Simple True. Only statemen Only statement 2 Both the Statements are True 0 0 1 0
t = 1, 2, 3
print(t)

Python Data Structure Simple The above technique is called Tuple packing Tuple unpacking Tuple assignment None of the a 1 0 0 0
Which of the following is True
Python Function Simple about Range function Only integer ar Parameters can b The range() funct Range functio 1 1 1 0
____is a string literal that occurs
as the first statement in a
module, function, class, or
method definition.
Python Simple docstring __init__ __str__ __name__ 1 0 0 0
class Emp:
def __init__(self, id):
self.id = id
id = 100

a = Emp(123)
Python OOPS Average print (a.id) 100 123 Error None of the a 0 1 0 0
class sample:
def __init__(self):

self.i=10

self.i=i+1
obj=sample()
Python OOPS Average print(a.i) 10 11 0 Error 'i' not d 0 0 0 1
Which of the following technique
is useful if you have edited the
module source file using an
external editor and want to try
out the new version without
Python Module Simple leaving the Python interpreter. reload loadagain refresh clean 1 0 0 0
A function without an explicit
return statement returns
Python Function Simple _______ 1 None 0 Null 0 1 0 0
Which of the following is used to
create a global variable and
make changes to the variable in
Python Identifiers Simple a local context. global local import None of the a 1 0 0 0
In Dictinoary,User is adding
value,If the key is already
available what is the status of
Python Data Structure Simple the old value New entry will bDictionary is immuOld value will be r None of the a 0 0 1 0
Identify the following keyword
which generators uses to return
Python Generators Simple value assign return Yield get 0 0 1 0
Which of the following is called
Python Function Simple as Anonymous function user defined fulambda unknown function null function 0 1 0 0
Python Function Average Identify the types of function Keyword argumPostitional argumeVariable length ar Default argum 0.3 0.3 0.2 0.2
Identify the following function is
used to match a complete target
Python Regular ExpressAverage string. find() searchall() findall() fullmatch() 0 0 0 1
Identify the ouput.

import re
s=re.sub("[a-z]","*","a1b2c3d4e")
Python Regular ExpressDifficult print(s) a*b*c*d*e *a1b2c3d4e* *1234*abcde* *1*2*3*4* 0 0 0 1
class Book:

def __init__(self,id,price):

self.id=id

self.price=price

obj=Book(1,200)

Which of the following is wrong


Python OOPS Average about the above code? id and price ar Every class must obj is called as a None of the a 0 1 0 0
What will be the output of below
Python code?

class Book:

def __init__(self,bname,bid):

self.bname=bname

self.bid=bid
1 1 2 2
Python OOPS Difficult print(self.bid) 2 1 1 2 1 0 0 0
Identify how many objects and
reference variables are there in
the below code code?

class A:
print("Welcome to Python")
A()
A()
obj=A()
Python OOPS Difficult obj1=A() 4 and 2 2 and 2 4 and 0 3 and 1 1 0 0 0

l1=[20,30, 40, 50]


l2=[10, 20, 20]
a=l2=l1
Python Data Structure Average print(a) [10, 20, 20] [10, 20, 20,30, 40 [20, 30, 40, 50] [20] 0 0 1 0
Every exception in python is
Python Exception Handl Simple ____ object type class string 1 0 0 0

t=(10,20,30,40)
a,b,c,d=t
print("a=",a,"b=",b,"c=",c,"d=",d)
This above code technique is
Python Data Structure Simple called? Tuple packing Tuple unpacking Assignment None of the a 0 1 0 0
Which of the following blocks will
be executed whether an
Python Exception Handl Simple exception is thrown or not? catch assert thrown finally 0 0 0 1
What are different types of
inheritance supported by Hierarchical
Python Exception Handl Simple Python? Multiple Inherit Multilevel InheritanInheritance All the above 0 0 0 1
One of the following keryword
performs no action and serves
as a placeholder in Python,it can
be used when a statement is
required syntactically but the
program requires no action

Python Basics Simple def None Pass break 0 0 1 0


which of the following is an
appropriate method to close a
Python File Operation Simple file? close(fp) fclose(fp) fp.close() fp.__close__ 0 0 1 0
Subject: Python

1.select the list comprehension code equivalent to the below script.

sum=[] for x in (range(1,3)

for y in range(3,6)

sum.append(x+y)

1.sum=[x + y for x in range(1,3) for y in range(3,6)]

2.sum=for x in range(1,3) for y in range(3,6) print x+y]

3.sum=[ return x+y for y in range(1,3) for x in range(3,6)]

4.sum=[ for x in range(1,3) for y in range(3,6) return x+y]

2. which function is used to read two charecters from a file object in file?

a. infile.readline(2)

b.infile.read(2)

c.infile.read()

d.infile.readlines(2)
3. which function is used to write the data in the binary format?

a.dump

b.write

c.output

d. all of the above

4.which collection is used to store unique values?

list /dict/tuple/set

5.identify the output print(2,4)+(6,8)

a.(2,4,6,8)

b.error

c.{4,6}

d.{(2,4),(6,8)}
4. class Name(object)

def first(

print("Iam callled")

def second()

print("i got called")

obj=Name()

Name.first(obj)

**

a. unbound method call

b. bounded method call

c.incorrect object declaration

d.all the above

5.which is appropriate to use the static method in a class?

a.to access the attribute of the instance

b. to instantiate the class based on the given parameter


c.to perform the action relevant to the class without instantiating the class

d. to access the static members of the class

6. which function displaya a file dialog for opening an existing file?

a. tmpfile=askopenfilename()

b.tmpfile=openfilename()

c.tmpfile=saveasfilename()

d.tmpfile=asksaveasfilename()

7. def demo();

try;

print(1)

finally;

print(2)
demo()

a.2

b.1 2

c.1

7.on what condition finally block gets executed?

1.on sepecific condition

2.on exceptions

3.on errors

4.always

8. select the correct option

a. none of the listed options

b.a user defined exception can be created by deriving a class from error class.

c.custom exceptions is unavailable in python

d. a user definedexception can be created by deriving a class from exception class.


9.select the code snippet that divide by zero error with error message " number cannot be divided
with zero"

a. try: 1/except:raise

b.try: 1/except ax e : print(e)

c. try: 1/ except ZeroDivisionError: print("number cannot be divided with zero")

d.try: 1/ except ValueError: print (("number cannot be divided with zero")

10.identify the output-

for i in [1,0]: print(i+1)

a.1

b. 11 1

c.1 1
11.identify the output

y=["test",'Done]

for i in y:i.upper() print(y)

a.['test','dont']

b.['TEST','DONE']

c. none of the listed options

d.[None,None]

12.select the correct match

1._iter_2 next

a.method that is called a initialization of an iterator

b. the iterator next method return the next value for the iterable.

options
--------

a. 1 -a 2 -b

b.*

b.**

d.*

13.numbers=[,4,6,8,1]

newnumbers= tuple(map(lamda x:x*x,numbers))

print(newnumbers)

a.(4,16,36,64,1)

b.(2,4,6,8,1)

c.[2,4,6,8,1]

d.[4,16,36,64,1]
14.what is the o/p

def string_reverse(str1): str2=" index=len(str1)

while index>0;

str2 +=str1[index-1]

index=index-1

return str2

print(string_reverse('5678ABCD'))

a.5678ABCD

b.8765DCBA

c.DCBA8765

D.none of the above

14.which of the following code uses inheritance?

a.class Hello: Pass class world(Hello):Pass

b.class Hello: Pass


c. class Hello: Pass class Test: Pass class World(Hello,Test):Pass

c. none of the above

15.code snippet

class Company:

def_init_(self,name,empnum);

self.name=name

self.empnum=empnum

def myfunc(self);

print("Welcome to"+self.name+' '+self.empnum)

p1=Company("Cognizant","12345")

a.Welcome to Cognizant

b.Syntax error, this program will not run

c. Welcome to Cognizant 12345

d. Cognizant 12345
16. code snippet

def coverFunction();

global a

a=4

def innerFunction();

global a

a=5

print('a=',a)

a=6

coverFunction()

print('a=',a)

a.a=5 a=4

b.a=5

c.a=6

d.a=4
17.List the return type of format function on strings

a.boolean

b.string

c.error

d.integer

18.true or false

output of the below statement is "Python"

str_variable="Hello Python"

print(str_variable[6:11])

select one

a. true

b.false

19.which keyword is used at the begining of the class definition


a.pass

b.class

c._init_

d.def

20.o/p of the code

import OrderedDict

my_string1="Welcome 1"

print(my_string1)

my_string2= "Welcome 2"

print(my_string2)

my_string3="Welcome 4"

print(my_string3)

my_string4="""Welcome All"""
a. Welcome 1 Welcome 2 Welcome 4 Welcome All

b. Error

c. Welcome 1 Welcome 2 Welcome 4

d.Welcome 1 Welcome 2

-------------------------------------

21.choose the correct option

class py_Arraysum

def twoSum(self,numbers,total);

lookup={}

if total-num in lookup;

return(lookup[total-num]+1,i+1)

lookup[num]=i

print("Number1=%d"%py_ArraySum().twoSum((3,1,4,5,2,7),6))

output: Number 1=2, Number2=4

Select one
a. none of the listed

b.while i,num in enumerate(numbers);

c. if i, num in enumerate(numbers);

d. for i, num in enumerate(numbers);

22. Let a tuplevalue contains 5 elements , how to se third element of the tuple to 'india'

a.def test

b.test[3]='india'

c.elements of the tuple remains unchanged

d.test[2]='india'

22.identify the output

integer=[1,2,3,4,5,6,7,8,9]

print(integer[::3])

a.[1,3,5,7,9]
b.[1,3,5]

c.[1,3,5,7]

d.[1,4,7]

23. sample_dict('n':3,'e':7,'o':9)

sorted(sample_dict)

a.[3,7,9]

b. {'n':3,'e':7,'o':9}

c.{'e':7.'n':3,'o':9}

d.[e,n,o]

24.select the applicable to with statement( check box)

a.with statement is used to loop over a generator

b.with statement encapsulates try, except , finally patern for code reuse

c.with stement is used to alias an object


d.if an exception occurs in the block _exit_() method of the context manager is called to clean up
resources

25.select the correct option that closes file if exception occurs

a. none of the listed options

b. with open("demo.txt", encoding='utf-8')as f # perform file operations

c. f=open("demo.txt",'f',encoding='utf-8') f.read()

d.try #code that can raise error pass

26. identify the output

def demo():

try:

return 1

finally:

return 3

test=demo()

print(test)
a.error more than one return statement

b.3

c.1

27. identify the ouptut

file= None for i in range(5):

with open("hello.txt","w") as file

if i>2 break

print the closed

a. true

b.false

28.match the statement with correct option

1.type error
2.value error

3.runtime error

a. raised when the built-in function for a data type has the valid type of arguments, but the
arguments have invalid values specified.

b.raised when an operation or function is atempted that is invalid for the specified data type.

c. raised when a generated error does not fail into any category

select one:

a. all of the listed options

b.1-c 2-a 3-b

c.1-a 2-b 3-c

d. 1-b 2-a 3-c

29.whicn operator to import modules from packages

a. .operator

b. operator

30. state the below statements are true or not


python module should contain only definitions like functions,classes and variables and not
statements like print

a. true b.false

31.what is the output of the following

this should be a *

def nameFruits("fruit):print("i love",fruit)

nameFruits('Apple','Mango','orange')

select one option

a.('I love',( 'Apple','Mango','orange'))

b.Syntax error nameFruits() can take only one argument

c. i love Apple i love Mango i love Orange

d. i love Apple

32. select the correct statement(check box)

a. a reference variable is an object


b. an object may contain other objects

c. an object can contain reference to other objects

d.a referance vaiable refers to an object.

33.output for the below code

class Hello:

_init_(self,name)

self.name=name sayHello(self):

print(self.name)

p1=Hello("Tom")

p2=Hello("Sam")
p2.sayHello()

a.Hello Tom

b.Sam

c.Tom

d.Hello Sam

34. identify the output

class MapPoint:

def _init_(self,x=0,y=0):

self.x=x+2

self.y=y+3

s1=MapPoint()

print(s1.x,s1.y)
select one

a.error

b.2,3

c.x,y

d.,0

35. select the correct statement

choose one or two

a.tuple is immutable and list is mutable

b.set is an unordered collection of unique items

c.Dictinoary is an ordered collection of key-value pairs

d.tuple is mutable and list is immutable

36.choose the correct optiona to print pi constant

as declared in math module


a. from math import pi print(math pi)

b. from math import pi print(pi)

c.print(math pi)

d.print(pi)

37. what does the "cycle " function drom "iterators" module do?

a. return a iterator wich cycles through the given list over and over again

b. returns a iterator for the given iteratable object

c.converts the given list into generator

d. cycles through the given list

38. what would be the function return if no return statement is used inside it

a. none object

b.an arbitary object

c.Error function must have a return statement.


39. what happens if a non-existant file is opened?

a. new file gets created

b.open an alternative file

c.none of the listed options

d.raises an exception

40. select the correct option

a.custom exception is unavailable in python

b. a user-defined exception can be created by deriving a class from exception class

c.none of the listed options

d.a user-defined exception can be deriving a class from error class

41.select that all applicable to generators(check box)


a.generator help program to perform faster since the code do not wait for the while data set to be
generated.

b.generator are used only to loop over list

c.generator is memory efficient

d. generator yield stament returns one valut at time to the calling loop.

42. identify the output

cubes={1,1,28,3:27,4:64,5:125}

print(cubes pop(4))

print(cubes)

a.125{1:1,2:8,3:27,5:125}

b.4{1:1,2:8,3:27,5:125}

c.64{1:1,2:8,3:27,5:125}

d.none of the listed options

43. select the corect statement

a._ini_() is called when a new object is initiated

b. single object can be made from the given class


c. the way operators behave in pyhon can be changed.

d. same operaor may behave differently depending upon operands.

44. which is the default valueof a funcion withou a return statement?

a.null

b.1

c.none

45. select the correct outpu for the code snippet

X=[5,3,6]

a=iter(x)

b=iter(x)

print(next(a))

print(next(b))

a.55

b.12

c.22
d.53

46.

Idenify the ouput

I=sum=0

While i<=5:

Sum+=i

i=i+1

print(sum)

a.1

b.5

c.15

c.4
47. identify the putput

Try:file=open(“demoFile”,”W”)

File.wrie(“This file for exception handling”)

Excep IOError:

Prin “Error cant find file or read data”

Else:

Prin “Writen conten in the file”

File.close()

a. The file for exception handling

b. Error: Cant find file or read data

c. Written content in the file

d. File unavailable

48.try:

Pass

Except(TypeError,ZeroDivisionError):
Print(“error”)

a. If no execpion occurs,print error

b. Always prin error

c. If TypeError or ZeroDivisionError occurs,prints Error

d. If any Exception(other than TypeError, ZeroDivisionError occurs,prints Error

49. what will resul if the file is opened in ‘a’ mode?

a.opens a file for appending at the end of the file.

b.file is deleted

c. file is opened for reading only

d.file is opened for writing

50. select the correct statement

a. elemts of set can be changed

b. elements of a set are unique

c. a set is an unordered collection of items

d.all the listed options


51. idenify he ouput

class hello():

def _repr_(self):

return “_repr_buil-in function called”

def _str_(self):

return “_str_ built-in funcation called”

say=hello()

print(say)

a._Str_built-in function called

b._repr_ built-in function called

c.Error

d.None of the listed options

55. The class methods in python

a.unbounded

b.sttatic
c.bounded

d. non-static

56.identtify the ouput of the given code

Str=”Hello”

Str.center(1,’1’))

a. None of the listed options

b. B.Hello1111

c. 1Hello1111

d. 11Hello11

57.Select the result.

Class TestClass:

Pass

Test_object=TestClass()

Test_object.attribute=”value”
a.last_object will not becreated due o NameError:name ‘NoObject’ is defined

b.Class will not be created due o SyntaxError: Invalid syntax” exception

c.AttributeError:TestClass instance has no attribute ‘a1’

d. No error

58.select the correct statements

a.same operator may behave differenly depeding uopn operands

b._init_() is called when a object is instantiated

c.single object can be made from different class

d.the way operators behave in python can be changed.

59.python allows functions to be called using keyword arguments and keyword arguments must
follow positinoal arguments

a.true

b.false

60.select the output of the following code snippet

Class UserError(“ValueError”):

Pass
class UserError1(UserError):

Pass

Class UserError2(UserError1):

Pass

For err in[UserError,UserError1,UserError2]

try:

Raise err except UserError:

Prin(“UserError”)

Except UserError1:

print(“UserError1”)

except UserError2

print(“UserError2”)

a.valueErrpr ValueError ValueEror

b.UserError UserError UserError


c.UserError2 UserError1 UserError

d. UserError UserError1 UserError2

61.what kind of error do you get while compailing the following code?

Print(Str/2)

a.Zero error

b.type error

c. trace back error

d. none error

62. idenify the oupu if entered company is cognizant.

Import sys

Print “Enter your current company:”,

Name=”while rue:

d=sys.stdin.read(1)

if d==”\n”:

break

name=name+d
print “Your comapany is “,name

a.All the listted options

b.cognizant

c.your company is cognizant

print

63.os.listdir() is used for

a.creating a new directory

b.prints current directory

c.clones current directory

d.prints all directories and files inside he given directory

64. identify the ouput

Ex_tuple=(‘Python’,)*(a.len_()-a[::-1][])

Print(ex_tuple)
a. (‘Python’)

b. (‘Pyhon’,’Python’)

c. Error

d. 0

65.Identify the output

fruit_list_1=[‘Orange’,’Gavua’,’Cherry’,’Strawbery’]

fruit_list_2=fruit_list_1
fruit_list1 = ['Apple',
'Berry', 'Cherry',
'Papaya']
fruit_list_3=frui_list_1[:] fruit_list2 = fruit_list1
fruit_list3 = fruit_list1[:]

fruit_list2[0] = 'Guava'
fruit_list3[1] = 'Kiwi'
fruit_list_2[]=’Owl’
sum = 0
for ls in (fruit_list1,
fruit_list2, fruit_list3):
fruit_list_3[1]=’Penguin’ if ls[0] == 'Guava':
sum += 1
if ls[1] == 'Kiwi':
sum += 20
sum=0 print (sum)

for ls in (fruit_list_1,frui_list_2,fruit_list_3):

if ls[]==’owl’

sum+=1

if ls[1]==’Penguin’:

sum+=2
print(sum)

a. 21

b. 22

c. 2

66.which command is used to remove a string “World” from list_1

a.list_1.remove(“World”)

b.list_1.removeAll(“World”)

c.list_1.removeOne(“World”)

d.list_1.remove(World)

67. identify the outpu

Vowels=[‘a’,’e’,’i’,’o’,’u’]

Print(vowels,3)
a.[ ’o’,’u’]

b. [‘a’,’e’,’i’,’o’,’u’]

c. [‘a’,’e’]

d.[ ’i’,’o’]

68. select the correct options

a.All of listed opions

b._new() method automatically invokes the __init_ method

c._init_ method is defined in the object class

d.__eq(other) method is defined in the object class.


1.select the list comprehension code equivalent to the below script.
sum=[] for x in (range(1,3)
for y in range(3,6)
sum.append(x+y)
1.sum=[x + y for x in range(1,3) for y in range(3,6)]
2.sum=for x in range(1,3) for y in range(3,6) print x+y]
3.sum=[ return x+y for y in range(1,3) for x in range(3,6)]
4.sum=[ for x in range(1,3) for y in range(3,6) return x+y]

Answer: 1

2. which function is used to read two charecters from a file object in file?
a. infile.readline(2)
b.infile.read(2)
c.infile.read()
d.infile.readlines(2)

Answer: b

3. which function is used to write the data in the binary format?


a.dump
b.write
c.output
d. all of the above

Answer: a

4.which collection is used to store unique values?


a. list
b. dict
c. tuple
d. set

Answer: d

5. Identify the output print(2,4)+(6,8)


a. (2,4,6,8)
b. error
c. {4,6}
d. {(2,4),(6,8)}

Answer: b
6. class Name(object)
def first(
print("Iam callled")
def second()
print("i got called")
obj=Name()
Name.first(obj)
**
a. unbound method call
b. bounded method call
c.incorrect object declaration
d.all the above

Answer: c

7. Which is appropriate to use the static method in a class?


a.to access the attribute of the instance
b. to instantiate the class based on the given parameter
c.to perform the action relevant to the class without instantiating the class
d. to access the static members of the class

Answer: c&d

8. which function displaya a file dialog for opening an existing file?


a. tmpfile=askopenfilename()
b.tmpfile=openfilename()
c.tmpfile=saveasfilename()
d.tmpfile=asksaveasfilename()

Answer: a

9. def demo();
try:
print(1)
finally:
print(2)
demo()
a.2
b.1 2
c.1
d.1
2

Answer: d
10. On what condition finally block gets executed?
1.on sepecific condition
2.on exceptions
3.on errors
4.always

Answer: 4

11. select the correct option


a. none of the listed options
b. a user defined exception can be created by deriving a class from error class.
c. custom exceptions is unavailable in python
d. a user definedexception can be created by deriving a class from exception class.

Answer: d

12. Select the code snippet that divide by zero error with error message " number cannot be divided
with zero"
a. try: 1/except:raise
b.try: 1/except ax e : print(e)
c. try: 1/ except ZeroDivisionError: print("number cannot be divided with zero")
d.try: 1/ except ValueError: print (("number cannot be divided with zero")

Answer: c

13. Identify the output-


for i in [1,0]: print(i+1)
a.1
b. 11 1
c.1 1
d.2 1

Answer: d

14. Identify the output


y=["test",'Done]
for i in y:i.upper() print(y)
a.['test','Done']
b.['TEST','DONE']
c. none of the listed options
d.[None,None]

Answer: a
15. Select the correct match
1._iter_
2 next
a.method that is called a initialization of an iterator
b. the iterator next method return the next value for the iterable.
options
--------
a. 1 -a 2 -b
b.*
b.**
d.*

Answer: a

16. Numbers=[2,4,6,8,1]
newnumbers= tuple(map(lamda x:x*x,numbers))
print(newnumbers)
a.(4,16,36,64,1)
b.(2,4,6,8,1)
c.[2,4,6,8,1]
d.[4,16,36,64,1]

Answer: a

17. What is the o/p


def string_reverse(str1): str2=" index=len(str1)
while index>0;
str2 +=str1[index-1]
index=index-1
return str2
print(string_reverse('5678ABCD'))
a.5678ABCD
b.8765DCBA
c.DCBA8765
D.none of the above

Answer: c

18. Which of the following code uses inheritance?


a.class Hello: Pass class world(Hello):Pass
b.class Hello: Pass
c. class Hello: Pass class Test: Pass class World(Hello,Test):Pass
d. none of the above

Answer: a & c
19. Code snippet
class Company:
def_init_(self,name,empnum);
self.name=name
self.empnum=empnum
def myfunc(self);
print("Welcome to"+self.name+' '+self.empnum)
p1=Company("Cognizant","12345")

a.Welcome to Cognizant
b.Syntax error, this program will not run
c. Welcome to Cognizant 12345
d. Cognizant 12345

Answer: c (if the function is called)

20. Code snippet


def coverFunction();
global a
a=4
def innerFunction();
global a
a=5
print('a=',a)
a=6
coverFunction()
print('a=',a)
a.a=5 a=4
b.a=5
c.a=6
d.a=4

Answer: d

21. List the return type of format function on strings


a.boolean
b.string
c.error
d.integer

Answer: b
22. True or False
output of the below statement is "Python"
str_variable="Hello Python"
print(str_variable[6:11])
select one
a. true
b.false

Answer: b (false)

23. Which keyword is used at the begining of the class definition


a.pass
b.class
c._init_
d.def

Answer: b

24. O/P of the code


import OrderedDict
my_string1="Welcome 1"
print(my_string1)
my_string2= "Welcome 2"
print(my_string2)
my_string3="Welcome 4"
print(my_string3)
my_string4="""Welcome All"""

a. Welcome 1 Welcome 2 Welcome 4 Welcome All


b. Error
c. Welcome 1 Welcome 2 Welcome 4
d.Welcome 1 Welcome 2
Ex: From math import pi
Answer: b
Here math file includes the value of pi

Likewise,

From collections, import orderDict


25. Choose the correct option
class py_Arraysum
def twoSum(self,numbers,total):
lookup={}
if total-num in lookup;
return(lookup[total-num]+1,i+1)
lookup[num]=i
print("Number1=%d"%py_ArraySum().twoSum((3,1,4,5,2,7),6))
output: Number 1=2, Number2=4
Select one
a. none of the listed
b.while i,num in enumerate(numbers);
c. if i, num in enumerate(numbers);
d. for i, num in enumerate(numbers);

Answer: d

26. Let a tuple value contains 5 elements , how to se third element of the tuple to 'india'
a.def test
b.test[3]='india'
c.elements of the tuple remains unchanged
d.test[2]='india'

Answer: c

27. Identify the output


integer=[1,2,3,4,5,6,7,8,9]
print(integer[::3])
a.[1,3,5,7,9]
b.[1,3,5]
c.[1,3,5,7]
d.[1,4,7]

Answer: d

28. Sample_dict={'n':3,'e':7,'o':9}
sorted(sample_dict)
a.[3,7,9]
b. {'n':3,'e':7,'o':9}
c.{'e':7.'n':3,'o':9}
d.[e,n,o]

Answer: d
29. Select the applicable to with statement( check box)
a.with statement is used to loop over a generator
b.with statement encapsulates try, except , finally patern for code reuse
c.with stement is used to alias an object
d.if an exception occurs in the block _exit_() method of the context manager is called to clean up
resources

Answer: A&B&C&D

30. Select the correct option that closes file if exception occurs
a. none of the listed options
b. with open("demo.txt", encoding='utf-8')as f # perform file operations
c. f=open("demo.txt",'f',encoding='utf-8') f.read()
d.try #code that can raise error pass

ANSWER: b

31. Identify the output


def demo():
try:
return 1
finally:
return 3
test=demo()
print(test)
a.error more than one return statement
b.3
c.1

Answer: b (finally block is executed before try block)

32. Identify the ouptut


file= None
for i in range(5):
with open("hello.txt","w") as file
if i>2 break
print the closed
a. true
b. false

Answer: a
33. Match the statement with correct option
1.type error
2.value error
3.runtime error
a. raised when the built-in function for a data type has the valid type of arguments, but the
arguments have invalid values specified.
b.raised when an operation or function is atempted that is invalid for the specified data type.
c. raised when a generated error does not fail into any category
select one:
a. all of the listed options
b.1-c 2-a 3-b
c.1-a 2-b 3-c
d. 1-b 2-a 3-c

Answer: d

34. Which operator to import modules from packages


a. .operator
b. operator

Answer: a

35. State the below statements are true or not


python module should contain only definitions like functions, classes and variables and not
statements like print
a. true
b. false

Answer: b (false)

36. What is the output of the following


def nameFruits("fruit):
print("i love",fruit)
nameFruits('Apple','Mango','orange')
select one option

a.('I love',( 'Apple','Mango','orange'))


b.Syntax error nameFruits() can take only one argument
c. i love Apple i love Mango i love Orange
d. i love Apple

Answer: a (if * is there)


b (if “ is not there)
37. Select the correct statement(check box)
a. a reference variable is an object
b. an object may contain other objects
c. an object can contain reference to other objects
d.a referance vaiable refers to an object.

Answer: c & d

38. Output for the below code


class Hello:
_init_(self,name)
self.name=name sayHello(self):
print(self.name)
p1=Hello("Tom")
p2=Hello("Sam")
p2.sayHello()
a.Hello Tom
b.Sam
c.Tom
d.Hello Sam

Answer: b

39. Identify the output


class MapPoint:
def _init_(self,x=0,y=0):
self.x=x+2
self.y=y+3
s1=MapPoint()
print(s1.x,s1.y)
select one
a.error
b.2,3
c.x,y
d.,0

Answer: b
40. Select the correct statement
choose one or two
a.tuple is immutable and list is mutable
b.set is an unordered collection of unique items
c.Dictinoary is an ordered collection of key-value pairs
d.tuple is mutable and list is immutable

Answer: a & b

41. Choose the correct option to print pi constant


as declared in math module
a. from math import pi print(math pi)
b. from math import pi print(pi)
c.print(math pi)
d.print(pi)

Answer: b

42. What does the "cycle " function from "iterators" module do?
a. return a iterator wich cycles through the given list over and over again
b. returns a iterator for the given iteratable object
c.converts the given list into generator
d. cycles through the given list

Answer: a

43. What would be the function return if no return statement is used inside it
a. none object
b.an arbitary object
c.Error function must have a return statement.

Answer: a (if any return statement is not mentioned I a function, “None” is returned)

44. What happens if a non-existant file is opened?


a. new file gets created
b.open an alternative file
c.none of the listed options
d.raises an exception

Answer: d
45. Select the correct option
a. custom exception is unavailable in python
b. a user-defined exception can be created by deriving a class from exception class
c. none of the listed options
d. a user-defined exception can be deriving a class from error class

Answer: b

46. Select that all applicable to generators(check box)


a. generator help program to perform faster since the code do not wait for the while data set to be
generated.
b. generator are used only to loop over list
c. generator is memory efficient
d. generator yield statement returns one valet at time to the calling loop.

Answer: a,c,d
B (generator is not only used to loop over list)

47. Identify the output


cubes={1,1,28,3:27,4:64,5:125}
print(cubes pop(4))
print(cubes)
a.125{1:1,2:8,3:27,5:125}
b.4{1:1,2:8,3:27,5:125}
c.64{1:1,2:8,3:27,5:125}
d.none of the listed options

Answer: c

48. Select the corect statement


a._init_() is called when a new object is initiated
b. single object can be made from the given class
c. the way operators behave in pyhon can be changed.
d. same operaor may behave differently depending upon operands.

Answer: a,c,d
b -> correct -> if only single object not mentioned

(Operator overloading: operator behaves differently when used with operands of different data
types)

49. Which is the default value of a function without a return statement?


a. null
b.1
c. none
Answer: c (none)

50. Select the correct output for the code snippet


X=[5,3,6]
a=iter(x)
b=iter(x)
print(next(a))
print(next(b))
a.55
b.12
c.22
d.53

Answer: a (55)

51. Identify the output


I=sum=0
While i<=5:
Sum+=i
i=i+1
print(sum)
a.1
b.5
c.15
c.4

Answer: c

52. Identify the output


Try:file=open(“demoFile”,”W”)
File.wrie(“This file for exception handling”)
Excep IOError:
Prin “Error cant find file or read data”
Else:
Prin “Writen conten in the file”
File.close()
a. The file for exception handling
b. Error: Cant find file or read data
c. Written content in the file
d. File unavailable

Answer: c
53. try:
Pass
Except(TypeError,ZeroDivisionError):
Print(“error”)
a. If no execpion occurs,print error
b. Always prin error
c. If TypeError or ZeroDivisionError occurs,prints Error
d. If any Exception(other than TypeError, ZeroDivisionError occurs,prints Error

Answer: c

54. What will be the result if the file is opened in ‘a’ mode?
a. opens a file for appending at the end of the file.
b. file is deleted
c. file is opened for reading only
d. file is opened for writing

Answer: a

55. Select the correct statement


a. elements of set can be changed
b. elements of a set are unique
c. a set is an unordered collection of items
d. all the listed options

Answer: d

56. Identify the output


class hello():
def _repr_(self):
return “_repr_built-in function called”
def _str_(self):
return “_str_ built-in function called”
say=hello()
print(say)
a. _Str_built-in function called
b. _repr_ built-in function called
c. Error
d. None of the listed options

Answer: a
57. The class methods in python
a. unbounded
b. static
c. bounded
d. non-static

Answer: a

58. Identify the output of the given code


Str=”Hello”
Str.center(1,’1’))
a. None of the listed options
b. B.Hello1111
c. 1Hello1111
d. 11Hello11

Answer: a

Unbounded -> class method


Bounded -> object method -> with/without self object

55. Select the result.


Class TestClass:
Pass
Test_object=TestClass()
Test_object.attribute=”value”
a. last_object will not becreated due o NameError:name ‘NoObject’ is defined
b. Class will not be created due o SyntaxError: Invalid syntax” exception
c. AttributeError:TestClass instance has no attribute ‘a1’
d. No error

Answer: b

You might also like