1. Which of the following will disable output buffering in Python?

Answers:

  1. Using the -u command line switch
  2. class Unbuffered: def __init__(self, stream): self.stream = stream def write(self, data): self.stream.write(data) self.stream.flush() def __getattr__(self, attr): return getattr(self.stream, attr) import sys sys.stdout=Unbuffered(sys.stdout)
  3. Setting the PYTHONUNBUFFERED environment variable
  4. sys.stdout = os.fdopen(sys.stdout.fileno(), ‘w’, 0)

2. Which of the following members of the object class compare two parameters?

Answers:

  1. object.__eq__(self, other)
  2. object.__ne__(self, other)
  3. object.__compare__(self, other)
  4. object.__equals__(self, other)
  5. object.__co__(self, other)
  6. None of these

3. Object is the base class of new-style datatypes. Which of the following functions is not a member of the object class?

Answers:

  1. object.__eq__(self, other)
  2. object.__ne__(self, other)
  3. object.__nz__(self)
  4. object.__repr__(self)
  5. None of these

4. In Python, what is the default maximum level of recursion?

Answers:

  1. 500
  2. 1000
  3. 10000
  4. There is no default maximum level

5. Various email and news clients store messages in a variety of formats, many providing hierarchical and structured folders. Which of the following provides a uniform API for reading the messages stored in all the most popular folder formats?

Answers:

  1. mailstruct
  2. emailarch
  3. emailfolders
  4. mailbox

6. Which of the following are the main features of Python?

Answers:

  1. Cross-platform
  2. Extensible
  3. Object-oriented, with multiple inheritance
  4. Written in Java
  5. Overloading of common operators
  6. All of these

7. Which of the following variables store parameters passed from outside?

Answers:

  1. sys.param
  2. sys.arg
  3. sys.argv
  4. sys.prm

8. Which of the following functions can change the maximum level of recursion?

Answers:

  1. setmaxrecursion function in the sys module
  2. setrecursionlimit function in the sys module
  3. setmaximumrecursion function in the sys module
  4. None of these

9. Read the following statements:

>>> import array
>>> a = array.array(‘c’,’spam and eggs’)
>>> a[0] = ‘S’
>>> a[-4:] = array.array(‘c’,’toast’)
>>> print ”.join(a)

Which of the following will be the output of the above code snippet?

Answers:

  1. Spam and toast
  2. spam and toast
  3. Spam and eggs
  4. spam and eggs
  5. spamandtoast
  6. spamandeggs

10. How can a numeric String (eg. “545.2222”) be converted to Float or Integer?

Answers:

  1. import string parseStr = lambda x: x.isalpha() and x or x.isdigit() and (x) or x.isalnum() and x or len(set(string.punctuation).intersection(x)) == 1 and x.count(‘.’) == 1 and float(x) or x parseStr(“545.2222”)
  2. def convert(n): try: return int(n) except ValueError: return float(n + 0.5) convert(“545.2222”)
  3. a = “545.2222” float(a) int(float(a))
  4. def parseIntOrFloat(s): return eval(s)

11. Which of the following is the correct prototype of the string.find() function?

Answers:

  1. string.find(s, sub ,start ,end)
  2. string.find(s, sub ,start [,end])
  3. string.find(s, sub [,start [,end]])
  4. string.find(s, sub [,start] ,end)

12. It is possible to use encoding other than ASCII in Python source files. The best way to do it is to put one more special comment line right after the #! line to define the source file encoding. Which of the following is the correct statement to define encoding?

Answers:

  1. coding: iso-8859-15
  2. # -*- iso-8859-15 -*-
  3. # -*- coding: iso-8859-15 -*-
  4. None of these

13. How can a null object be declared in Python?

Answers:

  1. none
  2. None
  3. null
  4. Null

14. Which of the following modules lets you check whether two files are identical, and whether two directories contain some identical files?

Answers:

  1. dircomp
  2. filecompare
  3. filecmp
  4. structcomp

15. Which function could be used to list every file and folder in the current directory?

Answers:

  1. os.dirnames(‘.’)
  2. os.listdir(‘.’)
  3. os.listdir(‘/’)
  4. os.ls()

16. The core text processing tasks in working with email are parsing, modifying, and creating the actual messages. Which of the following modules deal with parsing and processing email messages?

Answers:

  1. MimeWriter
  2. mimify
  3. Both MimeWriter and mimify
  4. Neither MimeWriter nor mimify

17. Which of the following is the correct prototype for the ‘open’ function of the file class in python 2.2+?

Answers:

  1. open(fname [,mode [,buffering]])
  2. open(fname [,buffering [,mode]])
  3. open(fname [,mode])
  4. open(fname,mode,buffering)
  5. open(fname,buffering,mode)
  6. None of these

18. Which user input method will act like a file-object on which read and readline functions can be called?

Answers:

  1. sys.stdin
  2. raw_input()
  3. input()
  4. sys.argv

19. Which of the following protocol libraries can be used for an email implementation in a Python application?

Answers:

  1. telnetlib
  2. smtplib
  3. ftplib
  4. None of these

20. Which of the following statements imports every name in a module namespace into the current namespace?

Answers:

  1. from modname import All
  2. from modname import *
  3. from modname import ?
  4. from modname import All as *

21. Which is the correct way to remove an installed Python package?

Answers:

  1. easy_install -v <package>
  2. pip uninstall <package>
  3. easy_install -u <package>
  4. pip -m <package>

22. One common way to test a capability in Python is to try to do something, and catch any exceptions that occur.
Which of the following is the correct mechanism of trapping an error?

Answers:

  1. try: code to be verified will come here exception <except>:
  2. try: code to be verified will come here except <exception>:
  3. try: code to be verified will come here exception:
  4. try: code to be verified will come here exception <exception>:

23. Which of the following is the correct way to get the size of a list in Python?

Answers:

  1. list.length()
  2. len(list)
  3. sizeof(list)
  4. list.size()

24. What will be the output of the following statements:

>>> import string
>>> string.ljust(width=30,s=”Mary had a little lamb”)

Answers:

  1. ‘Mary had a little lamb ‘
  2. ‘Mary had a little lamb’
  3. ‘ Mary had a little lamb’
  4. None of these

25. The most important element of the email package is the message. The email class provides the classes for messages in Python. Which of the following classes is used for the message?

Answers:

  1. email.Message
  2. email.message.Message
  3. email.messages
  4. email.emailmessage

26. Consider the function:

def hello():
return “Hello, world!”

Which of the following is the correct way to make a decorator that could be used to make hello() return “#Hello, world!#”?

Answers:

  1. def hello(): return “#Hello, world!#”
  2. def hashes(fn): def wrapped(): return “#” + fn() + “#” return wrapped @hashes def hello(): return “Hello, world!”
  3. def hashes(fn): def wrapped(): return “#” + “#” return wrapped @hashes def hello(): return “Hello, world!”
  4. def hashes(fn): def wrapped(): print “#” + fn() + “#” return @hashes def hello(): return “Hello, world!”

27. Object is the base class of new-style datatypes. Which of the following functions is not a member of the object class?

Answers:

  1. object.__eq__(self, other)
  2. object.__notequal__(self, other)
  3. object.__repr__(self)
  4. None of these

28. Which of the following modules keep prior directory listings in the memory to avoid the need for a new call to the file system?

Answers:

  1. sys
  2. FileSys
  3. dirsys
  4. dircache

29. Which of the following modules is used internally to determine whether a path matches?

Answers:

  1. dircmp
  2. filecompare
  3. fncmp
  4. fnmatch

30. Examine the following prototype for the ‘open’ function of the file class in Python 2.2+:

open(fname [,mode [,buffering]])

Which of the following is correct for the ‘buffering’ argument?

Answers:

  1. 0 for none
  2. 1 for line oriented
  3. An integer larger than 1 for number of bytes
  4. All of these

31. Which of the following statements copy the contents of a list and not just a reference to the list?

Answers:

  1. newlist = oldlist
  2. newlist = oldlist[:]
  3. newlist = oldlist(dummy)
  4. None of these

32. Which of the following functions is used to send audio data via the Internet?

Answers:

  1. email.MIMEAudio(audiodata [,subtype [,encoder [,**params]]])
  2. email.SendAudio(audiodata [,subtype [,encoder [,**params]]])
  3. email.MIMEAudio.MIMEAudio(audiodata [,subtype [,encoder [,**params]]])
  4. email.MIMEAudio.SendAudio(audiodata [,subtype [,encoder [,**params]]])

33. Read the following statements:

Statement 1: A simple assignment statement binds a name into the current namespace, unless that name has been declared as global.
Statement 2: A name declared as global is bound to the global (module-level) namespace.

Which of the following is correct?

Answers:

  1. Statement 1 is true, but statement 2 is false.
  2. Statement 2 is true, but statement 1 is false.
  3. Both statements are true.
  4. Both statements are false.

34. Which of the following commands would produce the following result:
result: ‘line 1nline 2’

Answers:

  1. result = ‘nline 1nline 2n’.rstrip()
  2. result = ‘nline 1nline 2n’.split()
  3. result = ‘nline 1nline 2n’.strip()
  4. result = ‘nline 1nline 2n’.lstrip()
  5. result = ‘nline 1nline 2n’.splitlines()

35. Which is not used to install Python packages?

Answers:

  1. easy_install
  2. pip
  3. distribute
  4. installtools

36. Which of the following exceptions occurs while importing a module?

Answers:

  1. ModuleError
  2. ImportError
  3. ImportModuleError
  4. ReferenceError

37. Which of the following statements can be used to remove an item from a list by giving the index?

Answers:

  1. remove listname[index]
  2. del listname[index]
  3. kill listname[index]
  4. None of these

38. Read the following statements:

>>> word = ‘Help’ + ‘A’
>>> ‘<‘ + word*5 + ‘>’

Which of the following will be the output of the above code snippet?

Answers:

  1. ‘<HelpAHelpAHelpAHelpAHelpA>’
  2. ‘<HelpA5>’
  3. ‘<HelpA*5>’
  4. An error
  5. None of these

39. The least sophisticated form of text output in Python is writing to open files. In particular, which of the following streams can be used?

Answers:

  1. STDOUT
  2. STDERR
  3. STDPRN
  4. STDFIL

40. Which of the following options are true regarding these two code samples?
Code sample 1:
def main():
for i in xrange(10**8):
pass
main()

Code sample 2:
for i in xrange(10**8):
pass

Answers:

  1. Code sample 2 would take a longer time to complete than code sample 1. This is because in code sample 1, ‘i’ is local, whereas in code sample 2 it is global.
  2. Code sample 1 would take a longer time to complete than code sample 2. This is because code sample 1 would take additional time in defining and calling the function.
  3. Code sample 2 would take less time to complete because Python is able to detect pass as a null operation, and skip the whole loop.
  4. None of these.

41. How many arguments can a print statement handle?

Answers:

  1. One
  2. Any number of string arguments only
  3. Any number of numeric arguments only
  4. Any number of string or numeric arguments

42. When is the “yield” keyword used in Python?

Answers:

  1. When other processes need to take precedence over the Python script
  2. To break out of a loop
  3. When a function needs to return a list that only needs to be read through once
  4. Never

43. What is the best way to check if the object ‘myobject’ is iterable in Python?

Answers:

  1. myobject.isIter()
  2. try: [ e for e in myobject] except TypeError: print myobject, ‘is not iterable’
  3. try: iter.myobject except: print myobject, ‘is not iterable’
  4. if [ e for e in myobject]: print myobject, ‘is iterable’ else: print myobject, ‘is not iterable’

44. In Python, built-in exceptions can be inherited from. Which of the following is the base exception class?

Answers:

  1. Exceptions
  2. BaseException
  3. Exception
  4. Except

45. Given a program that saved a text file in the directory “/temp_files”, which of the following will make sure that “/temp_files” exists before writing the file?

Answers:

  1. d = os.path.dirname(“/temp_files”) if not os.path.exists(d): os.makedirs(d)
  2. d = os.path(“/temp_files”) if not os.path(d): os.makedirs(d)
  3. d = os.path.dirname(“/temp_files”) if os.path.exists(d): os.makedirs(d)
  4. if not os.path.exists(“/temp_files”): os.makedirs(d)

46. Read the following statements:

>>> lst = [‘spam’,’and’,’eggs’]
>>> lst[2] = ‘toast’
>>> print ”.join(lst)
>>> print ‘ ‘.join(lst)

Which of the following is the output of the second print statement in the above code snippet?

Answers:

  1. spam and eggs
  2. spamandeggs
  3. spamandtoast
  4. spam and toast

47. Read the following statements:

>>> import string
>>> s = ‘mary11had a little lamb’
>>> print s

Which of the following will be the output of the above code snippet?

Answers:

  1. mary had a little lamb
  2. mary11 had a little lamb
  3. mary had a little lamb
  4. mary11had a little lamb

48. Read the following statements:

Statement 1: Many string module functions are now also available as string object methods.
Statement 2: To use string object methods, there is no need to import the string module.

Which of the following is correct?

Answers:

  1. Statement 1 is true, but statement 2 is false.
  2. Statement 2 is true, but statement 1 is false.
  3. Both statements are true.
  4. Both statements are false.

49. What would the ‘sorted_tel’ be in the following code:
tel = {‘jack’: 4098, ‘sape’: 5139, ‘bill’: 3678, ‘mike’: 2122}
sorted_tel = sorted(tel.items(), key=lambda x: x[1])

Answers:

  1. A dictionary sorted by the second element.
  2. A list of Tuples sorted by the second element.
  3. A list of dictionaries sorted by the first element.
  4. A dictionary sorted by the first element.
  5. A list of Tuples sorted by the first element.

50. Inheriting from a base class enables a custom class to use a few new capabilities, such as slots and properties. Which of the following is the base class of new-style datatypes?

Answers:

  1. base
  2. object
  3. dict
  4. custom
  5. None of these

51. How can a list be split into equal sized chunks?

Answers:

  1. f = lambda x, n, acc=[]: f(x[n:], n, acc+[(x[:n])]) if x else acc
  2. def chunks(l, n): for i in xrange(0, len(l), n): yield l[i:i+n]
  3. def split_seq(seq, num_pieces): start = 0 for i in xrange(num_pieces): stop = start + len(seq[i::num_pieces]) yield seq[start:stop] start = stop
  4. chunks = lambda l, n: [l[x: x+n] for x in xrange(0, len(l), n)] chunks(l, 10)

52. Writing to STDOUT and STDERR is fairly inflexible, and most of the time the print statement accomplishes the same purpose more flexibly. How many arguments can a print statement handle?

Answers:

  1. 1
  2. 2
  3. 7
  4. Any number

53. Which of the following is the best way to reverse the string ‘Test String’ in Python?

Answers:

  1. string.reverse(‘Test String’)
  2. ‘Test String'[::-1]
  3. reversed(‘Test String’)
  4. ‘Test String'[-1:0]

54. What is the result of the following code:
>>> import itertools
>>> x = itertools.count(0)
>>> x.__class__.__name__

Answers:

  1. Nothing
  2. ‘count’
  3. ‘Object’
  4. ‘None’

55. What is the most flexible way to call the external command “ls -l” in Python?

Answers:

  1. from subprocess import call call([“ls”, “-l”])
  2. from subprocess import call call(“ls -l”)
  3. os.system(“ls -l”)
  4. os.system([“ls”], [“-l”])

56. Which of the following is the correct method for changing a global variable inside a function?

Answers:

  1. def change_globvar(): globvar = 1
  2. def change_globvar(): global globvar globvar = 1
  3. def change_globvar(): import globvar globvar = 1
  4. def change_globvar(): global globvar = 1

57. Which list flattening method will have the shortest running time?

Answers:

  1. l = [ [1, 2, 3], [4, 5, 6], [7], [8, 9] ] * 99 import itertools list( itertools.chain.from_iterable( l ) )
  2. l = [ [1, 2, 3], [4, 5, 6], [7], [8, 9] ] * 99 reduce( lambda x, y: x + y, l )
  3. l = [ [1, 2, 3], [4, 5, 6], [7], [8, 9] ] * 99 sum( l, [ ] )
  4. l = [ [1, 2, 3], [4, 5, 6], [7], [8, 9] ] * 99 [ item for sublist in l for item in sublist ]

58. Which of the following is the correct way to flush output of Python print?

Answers:

  1. import sys sys.stdout.flush()
  2. class flushfile(file): def __init__(self, f): self.f = f def write(self, x) self.f.write(x) self.f.flush() import sys sys.stdout = flushfile(sys.stdout)
  3. import sys sys.stdout = os.fdopen(sys.stdout.fileno(), ‘w’, 0)
  4. Running python with the -u command-line switch

59. Which of the following is the best method to find the indices of all occurances of a word in a string?

line = ‘mary had a little lamb, little lamb, little lamb’
word = ‘lamb’

Answers:

  1. import re indices = [occurance.start() for occurance in re.finditer(word, line)]
  2. def find_all(line, word): start = 0 while True: start = line.find(word, start) if start == -1: return yield start start += len(word) indices = list(find_all(line, word))
  3. indices = [i – 1 for i in range(len(line)) if line.startswith(word, i – 1)]
  4. None of these

60. In Python 2.x, which of the following is the way to check to make sure that the variable ‘x’ is not a string?

Answers:

  1. assert isinstance(x, basestring)
  2. assert not isinstance(x, basestring)
  3. assert not instance(x, basestring)
  4. assert not x.isinstance(basestring)

61. Which of the following will throw an exception in Python?

Answers:

  1. call Exception(“Here is an Exception!”)
  2. throw Exception(“Here is an Exception!”)
  3. raise Exception(“Here is an Exception!”)
  4. create Exception(“Here is an Exception!”)

62. Which of the following functions modifies the list in place to indicate which items are directories, and which are plain files?

Answers:

  1. dircache.listdir(path, lst)
  2. dircache.annotate(path, lst)
  3. dircache.filter(path, lst)
  4. dircache.scan(path, lst)

63. Which Python module can be used for copying files?

Answers:

  1. util
  2. shutil
  3. copy
  4. filecopy

64. Which of the following statements are true?

A. ._variable is semi-private and meant just for convention.
B. .__variable is considered superprivate and gets name mangled to prevent accidental access.
C. .__variable__ is typically reserved for built-in methods or variables.

Answers:

  1. A
  2. B
  3. C
  4. A, B, and C

65. How can an element be removed from a list using its list index?

Answers:

  1. myList.remove(index)
  2. pop myList[index]
  3. del myList[index]
  4. myList.delete(index)

66. Which of the following is the correct way to check to see if the variable theVar is an integer?

Answers:

  1. isinstance(theVar, int)
  2. theVar.isinstance(int)
  3. int.isinstance(theVar)
  4. is(theVar, int)

67. Which of the following is the base class for new-style file objects?

Answers:

  1. base
  2. file
  3. fileobject
  4. filebase

68. Which of the following methods returns the ASCII value of a character in Python?

Answers:

  1. ascii
  2. ord
  3. asciicode
  4. None of these

69. What is the output of the following code:

name = ‘Jon’
name.rjust(4, ‘A’)

Answers:

  1. ‘Jon A’
  2. ‘A Jon’
  3. ‘AJon’
  4. ‘JonA’

70. Which of the following is a way to find a local computer’s IP address with Python?

Answers:

  1. import socket socket.gethostbyname(socket.gethostname())
  2. socket.gethostbyname(socket.gethostname())
  3. import socket gethostbyname(socket.gethostname())
  4. import ifconfig print (ifconfig -a)

71. What is a metaclass in Python?

Answers:

  1. A class that is inherited from
  2. A class that inherits from another class
  3. Something that can be attached to any class, that gives it a constant set of attributes
  4. Something that creates “class” objects

72. Which of the following is the correct way to call the private method, myPrivateMethod(), in class MyClass, using dir(obj)?

class MyClass:
def __myPrivateMethod(self):
print “Private Method”

obj = MyClass()
print dir(obj)

Answers:

  1. __myPrivateMethod
  2. _MyClass__myPrivateMethod
  3. myPrivateMethod
  4. A private method will not be shown in the output.

73. What is the output of the following code?

def foo(param1, *param2):
print param1
print param2

def bar(param1, **param2):
print param1
print param2

foo(1,2,3,4,5)
bar(1,a=2,b=3)

Answers:

  1. TypeError: foo() got multiple values for keyword argument ‘param1’
  2. 1 (2, 3, 4, 5) 1 (2, 3)
  3. 1 (2, 3, 4, 5) 1 {‘a’: 2, ‘b’: 3}
  4. 1 {2, 3, 4, 5} 1 (‘a’: 2, ‘b’: 3)

74. Which of the following is the correct way to execute a program from inside Python without having to consider how the arguments/quotes are formatted?

Answers:

  1. import subprocess subprocess.call(‘C:\Temp\a b c\Notepad.exe’, ‘C:\test.txt’)
  2. os.call([‘C:\Temp\a b c\Notepad.exe’, ‘C:\test.txt’])
  3. import subprocess subprocess.call([‘C:\Temp\a b c\Notepad.exe’, ‘C:\test.txt’])
  4. subprocess.call([‘C:\Temp\a b c\Notepad.exe’, ‘C:\test.txt’])

75. What is the correct way to delete a directory that is not empty using Python?

Answers:

  1. os.remove(‘/directory’)
  2. os.rmtree(‘/directory’)
  3. shutil.rmtree(‘/directory’)
  4. import shutil shutil.rmtree(‘/directory’)

76. Which of the following is the correct way to write a generator which will output the numbers between 1 and 100 (inclusive)?

Answers:

  1. def onehundred(start, end): current = start while current <= end: yield current current += 1 for x in onehundred(1, 100): print x
  2. def onehundred(start, end): current = start while current <= end: return current current += 1 for x in onehundred(1, 100): print x
  3. def onehundred(start, end): current = start while current <= end: yield current current += 2 for x in onehundred(1, 100): print x
  4. def onehundred(start, end): while current <= end: yield current current += 1 for x in onehundred(1, 100): print x

77. Which of the following code snippets concatenates the list a_list = [1, 2, 3] with the tuple a_tuple = (4, 5), so the result would be [1, 2, 3, 4, 5]?

Answers:

  1. a_list + a_tuple
  2. a_list.extend(a_tuple)
  3. a_list.append(a_tuple)
  4. a_list.append(*a_tuple)

78. Which of the following will determine the number of CPUs available in the operating environment?

Answers:

  1. import os os..cpu_count()
  2. import sys sys..cpu_count()
  3. import psutil sutil.NUM_CPUS
  4. import multiprocessing multiprocessing.cpu_count()

79. Which of the following will be returned by readlines() method?

Answers:

  1. str
  2. a list of lines
  3. a list of single characters
  4. a list of integers

81. What function do you use to read a string?

Answers:

  1. input(«Enter a string»)
  2. eval(input(«Enter a string»))
  3. enter(«Enter a string»)
  4. print(enter(«Enter a string»))

82.Which function do you use to read data using binary input?

Answers:

  1. write
  2. output
  3. dump
  4. send

83.Which function do you use to read data using binary input?

Answers:

  1. write
  2. output
  3. dump
  4. send

84.Which of the following statements are true?

Answers:

  1. open a file for reading, if the file does not exist, an error occurs.
  2. open a file for writing, if the file does not exist, an error occurs.
  3. open a file for reading, if the file does not exist, the program will open an empty file.
  4. open a file for writing, if the file does not exist, a new file is created.
  5. open a file for writing, if the file exists, the existing file is overwritten with the new file.

85.Which of the following is the correct way to change the current working directory in Python?

Answers:

  1. import os
    os.chdir(«/path/to/change/to»)
  2. os.chdir(«/path/to/change/to»)
  3. chdir(«/path/to/change/to»)
  4. import os
  5. import os
    os.cd(«/path/to/change/to»)

86.Invoking the ___ method converts raw byte data to a string?

Answers:

  1. encode()
  2. decode()
  3. convertString()
  4. toString()

87. Which of the following exception raised for an error that doesn’t fall in any of the categories?

Answers:

  1. SyntaxError
  2. RuntimeError
  3. SystemError
  4. CodeError

88. Which is correct about getting a free port number?

Answers:

  1. use sock.getsockname() to get a free port number
  2. Do not bind to a specific port, or bind to port 0, e.g. sock.bind((», 0))
  3. Directly use a desired port number in bind function, e.g. sock.bind((», port_number))
  4. We cannot get a free port number

89. Which of the following statements are true regarding __slots__ in Python?

Answers:

  1. __slots__ can be useful when many small object creations are needed, with predefined structures and with memory limitations.
  2. __slots__ is an optimized dynamic structure.
  3. __slots__ is a memory optimization tool.
  4. __slots__ breaks multiple inheritance.

90.The side option of the pack manager may be _____?
def change_list(list1, list2):
list1.append(‘four’)
list2 = [‘and’, ‘we’, ‘can’, ‘not’, ‘lie’]
outer_list1 = [‘one’, ‘two’, ‘three’]
outer_list2 = [‘we’, ‘like’, ‘proper’, ‘English’]
change_list(outer_list1, outer_list2)
print outer_list1
print outer_list2

Answers:

  1. [‘one’, ‘two’, ‘three’, ‘four’]
    [‘we’, ‘like’, ‘proper’, ‘English’]
  2. [‘one’, ‘two’, ‘three’, ‘four’]
    [‘and’, ‘we’, ‘can’, ‘not’, ‘lie’]
  3. [‘one’, ‘two’, ‘three’]
    [‘we’, ‘like’, ‘proper’, ‘English’]
  4. [‘one’, ‘two’, ‘three’]
    [‘and’, ‘we’, ‘can’, ‘not’, ‘lie’]

91. The side option of the pack manager may be _____?

Answers:

  1. LEFT
  2. RIGHT
  3. BOTTOM
  4. TOP
  5. All of the above

92. How to get JSON to load into an OrderedDict in python?

Answers:

  1. By simply using json.loads(D) where D is Ordered dictionary
  2. By specifying the object_pairs_hook argument to JSONDecoder
  3. Ordered dictionary is not supported yet
  4. TOP
  5. All of the above

93. Which of the following code samples will flatten the «irregular» list below:
L = [[[1, 2, 3], [4, 5]], 6] to [1, 2, 3, 4, 5, 6]

Answers:

  1. g = str(L).replace(‘[‘, »).replace(‘]’, »
    flattenedList = [int(x) for x in g.split(‘,’) if x.strip()]
  2. def flatten(L):
    for el in L:
    if isinstance(el, collections.Iterable) and not isinstance(el, basestring):
    for sub in flatten(el):
    yield sub
    else:
    yield el
  3. def flatten_gen(L, ltypes=collections.Sequence):
    ltype = type(L)
    l = list(L)
    i = 0
    while i < len(l):
    while isinstance(l[i], ltypes):
    if not l[i]:
    l.pop(i)
    i -= 1
    break
    else:
    l[i:i + 1] = l[i]
    else:
    yield l[i]
    i += 1
  4. import re
    def Flatten(L):
    a = str(L)
    b,crap = re.subn(r'[\[,\]]’, ‘ ‘, a)
    c = b.split()
    d = [int(x) for x in c]
    return(d)

94. Which statement is true regarding the __all__ module level variable?

Answers:

  1. It is a list of strings defining all symbols in a module.
  2. It is a dictionary defining all functions in a module.
  3. It is a list of strings defining what symbols in a module will be exported when from <module> import * is used on the module.>/span>
  4. It is a dictionary defining what functions in a module will be exported when from <module> import * is used on the module.

95. Regarding Secure hashes and message digests in Python 3 using standard module hashlib, which of the following is true ?

Answers:

  1. hashlib.sha224(b»test») will return the sha224 hash (as string) of the value «test».
  2. `hexdigest()` function will return a hexadecimal string representation of the underlying hash algorithm.
  3. Feeding string objects into update() is supported, as hashes work on both bytes and strings.

96. Regarding Thread Synchronization Primitives in Python, which of the following is incorrect ?

Answers:

  1. Mutual Exclusion Lock (`threading.Lock`) are used to synchronize threads so that only one thread can make modifications to shared data at any given time. Only one thread can successfully `acquire()` the lock at any given time.
  2. Reentrant Mutex Lock (`threading.RLock`) are similar to a normal mutex lock except that it can be reacquired multiple times by the same thread.
  3. Semaphores (`threading.Semaphore`) are counter-based synchronization primitive, `acquire()/release()` increments or decrements a internal counter, and like locks, cannot be called in any order and by any thread.
  4. Event Objects (`threading.Event`) can be used to have one or more threads wait for something to occur. Setting an event will unblock all waiting threads simultaneously (if any).

97. Which method in the following is used to convert raw json objects to Json in python?

Answers:

  1. json.dumps()
  2. JSONEncoder().encode()
  3. json.loads()
  4. json.default()

98. Which method in the following is used to convert raw json objects to Json in python?

Answers:

  1. json.dumps()
  2. JSONEncoder().encode()
  3. json.loads()
  4. json.default()

99. What is the difference between the two methods, «foo is None», and «foo == None», for the purposes of determining if the type of an object is None?

Answers:

  1. «is» always returns True if it compares the same object instance whereas the value returned by «==» is determined by the __eq__() method.
  2. «==» always returns True if it compares the same object instance whereas the value returned by «is» is determined by the __eq__() method.
  3. There is no difference between the two, but «==» is preferred by convention.
  4. There is no difference between the two, but «is» is preferred by convention.

100. Which of the following environment variable for Python is an alternative module search path?

Answers:

  1. PYTHONCASEOK
  2. PYTHONHOME
  3. PYTHONSEARCH
  4. PYTHONSEARCH

101. Which of the following is the correct way to empty a list, using theList as an example?

Answers:

  1. del theList[] = []
  2. theList = []
  3. del theList[:]
  4. del theList[]

102.sys.path is initialized from which of the following locations ?

Answers:

  1. The directory containing the input script .
  2. PYTHONPATH enviroment variable.
  3. The installation-dependent default.
  4. All of the above

103. Which of the following is true regarding urlopen function from the standard module urllib in Python 2?

Answers:

  1. Open a network object denoted by a URL for reading, but it cannot be used to open local files.
  2. If the connection cannot be made the LookupError exception is raised.
  3. If the connection is successful, this function returns the content of the object as string.
  4. When opening HTTPS URLs, it does not attempt to validate the server certificate.

104. Which of the following is true regarding urlopen function from the standard module urllib in Python 2?

Answers:

  1. Open a network object denoted by a URL for reading, but it cannot be used to open local files.
  2. If the connection cannot be made the LookupError exception is raised.
  3. If the connection is successful, this function returns the content of the object as string.
  4. When opening HTTPS URLs, it does not attempt to validate the server certificate.

105. What is the type of inf?

Answers:

  1. Boolean
  2. Integer
  3. Float
  4. Complex

106.Which of the following data types is not supported in python ?

Answers:

  1. List
  2. Generics
  3. Numbers
  4. Tuple

107. Which of the following data types is not supported in python ?

Answers:

  1. List
  2. Generics
  3. Numbers
  4. Tuple

108. To add a new element to a list?

Answers:

  1. list.add(1)
  2. list.addValue(1)
  3. list.append(1)
  4. list.addItem(1)

109. Check whether an object x is an instance of class A, use _____.?

Answers:

  1. x.instance(A)
  2. A.instance(x)
  3. isinstance(x, A)
  4. instance(A, x)

110.How to convert a json string to Python object?

Answers:

  1. simplejson.load()
  2. theFunction.__name__
  3. theFunction.name()
  4. theFunction.__func_name__

111. Which of the following is incorrect to say about CPython’s garbage collection mechanism ?

Answers:

  1. Python maintains a count of the number of references to each object in memory. If a reference count goes to zero then the associated object is no longer live and the memory allocated to that object can be freed up for something else.
  2. The garbage collector periodically looks for «reference cycles» and cleans them up. An example would be if you have two objects o1 and o2 such that o1.x == o2 and o2.x == o1. If o1 and o2 are not referenced by anything else then they shouldn’t be live. But each of them has a reference count of 1.
  3. The garbage collector is a deterministic process, so that heuristics are never used to improve performance of garbage collection.
  4. All of the above are correct.

112. Which of the following statement is incorrect regarding Concurrency in Python?

Answers:

  1. A Thread can be defined by subclassing the `threading.Thread` and overriding the method `run()`
  2. A Thread instance is launched when the method `begin()` from `threading.Thread` is called.
  3. Once you start a Thread, it runs independently, and one can use `join()` to wait for a thread to exit
  4. Threads share all of the data in your program, and access to shared variables may cause so called Race Conditions, which can be resolved with synchronization primitives such as Mutex Locks.

113. What would the output of the following code be:
def a():
print «a executed»
return []
def b(x=a()):
x.append(5)
x.append(1)
print x
b()
b()
b()

Answers:

  1. a executed
    [1]
    a executed
    [1, 1]
    a executed
    [1, 1, 1
  2. a executed
    [5, 1]
    [5, 1, 5, 1]
    [5, 1, 5, 1, 5, 1]

    • a executed
    [5, 1]
    [5, 1]
    [5, 1]

  3. a executed
    [5, 1]
    a executed
    [5, 1]
    a executed
    [5, 1]
  4. a executed
    [5, 1]
    a executed
    [5, 1, 5, 1]
    a executed
    [5, 1, 5, 1, 5, 1]

114. The output of executing string.ascii_letters can also be achieved by ____?

Answers:

  1. string.letters.ascii
  2. string.ascii_lowercase+string.ascii_upercase
  3. string.ascii.letters

115. Considering this Python 2.x snippet,
while(True):
try:
doWork()
except TypeError:
print ‘Type error’
except Exception:
print ‘General exception’
except GeneratorExit, KeyboardInterrupt:
print ‘Existing exception’
which of the following is correct to say?
Answers:

  1. If doWork() raise a TypeError, then the program will print ‘General exception’, as TypeError is subclass of Exception.
  2. If the user tries to exit the program by entering Ctrl + C from the keyboard, the program won’t stop as KeyboardInterrupt is being handled and not re-raised.
  3. KeyboardInterrupt is the instance name for the exception class GeneratorExit. Therefore KeyboardInterrupt is never handled on this code.
  4. No matter what exception happens, the program will not stop and will print ‘General exception’ in the console, as Exception is the first base class in the Python exception hierarchy.

116. What will be the output of following code?
x, y = 15, 45
res = x if x < y else y
print(res)pt:
print ‘Existing exception’
Which of the following is correct to say?
Answers:

  1. 45
  2. 1
  3. Error
  4. 15

114. The output of executing string.ascii_letters can also be achieved by ____?

Answers:

  1. string.letters.ascii
  2. string.ascii_lowercase+string.ascii_upercase
  3. string.ascii.letters

115. What would be the output of the following code?
def change_list(list1, list2):
list1.append(‘four’)
list2 = [‘and’, ‘we’, ‘can’, ‘not’, ‘lie’]
outer_list1 = [‘one’, ‘two’, ‘three’]
outer_list2 = [‘we’, ‘like’, ‘proper’, ‘English’]
change_list(outer_list1, outer_list2)
print outer_list1
print outer_list2

Answers:

  1. [‘one’, ‘two’, ‘three’, ‘four’]
    [‘we’, ‘like’, ‘proper’, ‘English’]
  2. [‘one’, ‘two’, ‘three’, ‘four’]
    [‘and’, ‘we’, ‘can’, ‘not’, ‘lie’]
  3. [‘one’, ‘two’, ‘three’]
    [‘we’, ‘like’, ‘proper’, ‘English’]
  4. [‘one’, ‘two’, ‘three’]
    [‘and’, ‘we’, ‘can’, ‘not’, ‘lie’]

116. Which method in the following is used to convert raw json objects to Json in python?

Answers:

Answers:

  1. json.dumps()
  2. JSONEncoder().encode()
  3. json.loads()
  4. json.default()

117.Which of the following is the correct way to output the name of any function (including builtin functions) using Python?

Answers:

Answers:

  1. theFunction.func_name
  2. theFunction.__name__
  3. theFunction.name()
  4. theFunction.__func_name__

118.Which of the following is the correct way to output the name of any function (including builtin functions) using Python?

Answers:

Answers:

  1. theFunction.func_name
  2. theFunction.__name__
  3. theFunction.name()
  4. theFunction.__func_name__

119.Which of the following is the correct way to output the name of any function (including builtin functions) using Python?

Answers:

Answers:

  1. theFunction.func_name
  2. theFunction.__name__
  3. theFunction.name()
  4. theFunction.__func_name__

120.Which of the following statements are correct about assertions in Python?

Answers:

Answers:

  1. Asserts are used to control program flow.
  2. The «assert» statements are removed when the compilation is optimized.
  3. Asserts should be used to test conditions that should never happen.
  4. Asserts are used to define custom exceptions that are to be caught.

121.Consider the Python function:
def secret_function(sPath):
import os
for sChild in os.listdir(sPath):
sChildPath = os.path.join(sPath,sChild)
if os.path.isdir(sChildPath):
secret_function(sChildPath)
else:
print(sChildPath)

What would be the most correct statement to describe above function?

Answers:

  1. This function takes the name of a directory and prints out the absolute paths for the files and sub-directories.
  2. This function takes the name of a directory and prints out the paths files within that directory as well as any files contained in contained directories.
  3. This function takes the name of a directory and prints out the paths for the files and sub-directories.
  4. This function will get stuck in the recursive calls and will eventually throw a runtime error.

122.Consider the Python function:
def secret_function(sPath):
import os
for sChild in os.listdir(sPath):
sChildPath = os.path.join(sPath,sChild)
if os.path.isdir(sChildPath):
secret_function(sChildPath)
else:
print(sChildPath)

What would be the most correct statement to describe above function?

Answers:

  1. This function takes the name of a directory and prints out the absolute paths for the files and sub-directories.
  2. This function takes the name of a directory and prints out the paths files within that directory as well as any files contained in contained directories.
  3. This function takes the name of a directory and prints out the paths for the files and sub-directories.
  4. This function will get stuck in the recursive calls and will eventually throw a runtime error.

123.Which of the following will be the output of the below code snippet?
squares = []
for x in range(5):
squares.append(lambda: x**2)
x = 8
for i in range(5):
print(squares[i]())

Answers:

  1. 1
    4
    9
    16
    25
  2. 64
    64
    64
    64
    64
  3. UnboundLocalError: local variable ‘x’ referenced before assignment
  4. 64
    4
    9
    16
    25

124.How can a list of dictionaries be sorted by the values of the dictionaries?
Answers:

  1. from operator import itemgetter
    sortedlist = sorted(a_list_of_dicts, key = itemgetter(‘name’))
  2. import operator
    sortedlist = a_list_of_dicts.sort(key = operator.itemgetter(‘name’))
  3. def mykey(adictionary):
    return adictionary[‘name’]
    sortedlist = sorted(a_list_of_dicts, key=mykey)

  4. sortedlist = a_list_of_dicts.sort(lambda x,y : cmp(x[‘name’], y[‘name’]))

125.Which of the following statement is incorrect regarding Python language?
Answers:

  1. Python is an interpreted language. That means that, unlike languages like C and its variants, Python does not need to be compiled before it is run.
  2. Python is dynamically typed, this means that you don’t need to state the types of variables when you declare them or anything like that.
  3. Python is well suited to object orientated programming in that it allows the definition of classes along with composition and inheritance.
  4. In Python, functions are not objects. This means that they cannot be assigned to variables, returned from other functions and passed into functions.

126.Which of the following statement is incorrect regarding Python language?
Answers:

  1. Python is an interpreted language. That means that, unlike languages like C and its variants, Python does not need to be compiled before it is run.
  2. Python is dynamically typed, this means that you don’t need to state the types of variables when you declare them or anything like that.
  3. Python is well suited to object orientated programming in that it allows the definition of classes along with composition and inheritance.
  4. In Python, functions are not objects. This means that they cannot be assigned to variables, returned from other functions and passed into functions.

127.Which of the following is false regarding urlretrieve function from the standard module urllib in Python 2?
Answers:

  1. It copies a network object denoted by a URL to a local file, if necessary.
  2. If the target URL points to a local file, or a valid cached copy of the object exists, the object is not copied.
  3. It returns a tuple (filename, headers, filesize) where filename is the local file name under which the object can be found.
  4. It’s possible to define a custom path for the local file, where the object will be saved.

128.Which of the following is the correct way to determine a variable’s type in Python?
Answers:

  1. type(variable_name)
  2. dir(variable_name)
  3. var(variable_name)
  4. typevar(variable_name)

129. What gets printed on the console for the following Python 2.x code?
A0 = dict(zip((‘a’,’b’,’c’,’d’,’e’),(1,2,3,4,5)))
A1 = range(5)
A2 = sorted([i for i in A1 if i in A0])
A3 = sorted([A0[s] for s in A0])
A4 = [i for i in A1 if i in A3]
A5 = {i:i*i for i in A1}
A6 = [[i,i*i] for i in A1]
print A6
Answers:

  1. [[0, 0], [1, 1], [2, 4], [3, 9], [4, 16]]
  2. [{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}]
  3. [[1, 2, 3, 4, 9, 16]]
  4. [[0, 0], [1, 1], [2, 2], [3, 3], [4, 4]]

130. Regarding Unicode in Python 3, which of the following is incorrect ?

Answers:

  1. The `str` type contains Unicode characters, meaning any string created using «unicode rocks!», ‘unicode rocks!’, or the triple-quoted string syntax is stored as Unicode.
  2. One can create a string using the `decode()` method of `bytes` type, and it will use by default ‘latin_1’ encoding
  3. Python 3 supports using Unicode characters in identifiers.
  4. One can create a byte representation from a string by using the `encode()` method, and it will use by default ‘utf-8’ encoding.

131. Which of the following is the best way of checking if a string could be represented as a number?

Answers:

  1. def is_number(s):
    try:
    float(s)
    return True
    except ValueError:
    return False
  2. import re
    check_regexp = re.compile(«^\d*\.?\d*$»)
  3. def isNumber(token):
    for char in token:
    if not char in string.digits: return False
    return True
  4. import re
    check_replace = lambda x: x.replace(‘.’,»,1).isdigit()

132. Which of the following can be used to create a directory?

Answers:

  1. os.make_dir()
  2. os.create_dir()
  3. os.mkdir()
  4. All of the above

133. Which of the following will be the output of the below code snippet?
x = []
y = x
y.append(10)
z = 5
w = z
z = z — 1
print(y)
print(x)
print(z)
print(w)

Answers:

  1. [10]
    []
    [4]
    [5]
  2. [10]
    [10]
    [4]
    [5]
  3. [10]
    [[10]]
    [5]
    [5]
  4. [10]
    [None]
    [5]
    [4]

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

def f(x): return x % 2 != 0 and x % 3 != 0
result=filter(f, range(1, 20))
print result
Answers:

  1. [1, 3, 7, 10, 13, 16, 19]
  2. [1, 6, 9, 11, 15, 17, 19]
  3. [1, 5, 7, 11, 13, 17, 19]
  4. [1, 4, 7, 12, 15, 17, 19]

135. What are the states/features supported by a RLock object?

def f(x): return x % 2 != 0 and x % 3 != 0
result=filter(f, range(1, 20))
print result
Answers:

  1. Locked
  2. Owning thread
  3. Recursion level
  4. Unlocked
  5. All of the above

136. Which of the following is incorrect regarding modules in Python?

Answers:

  1. The interpreter searches for a module first at the directory of the top-level file, i.e. the file being executed.
  2. dir(__builtins__)` will return a list of all built-in functions, exceptions, and other objects.
  3. It’s possible to put several modules into a Package. A directory of Python code is said to be a package.

137. Which of the following is the best method for accessing the index of a list while executing in a loop?

Answers:

  1. for i in range(len(sequence)):
    print i

  2. for i,e in enumerate(sequence):
    print i
  3. for i, e in zip(range(len(sequence)), sequence):
    print i
  4. for i in xange(len(sequence)):
    print i

138. What gets printed in the code below ?
def f(x, l=[]):
for i in range(x):
l.append(i * i)
return l
f(2)
f(3, [3, 2, 1])
print f(3)

Answers:

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

139. What is the correct way to increment the value of the variable «i» by 1?

Answers:

  1. i += 1
  2. i++
  3. ++i
  4. inc(i)

140. Consider the code, and choose the correct statement:
class A:
def __init__(self, i = 0):
self.i = i
class B(A):
def __init__(self, j = 0):
self.j = j
def main():
b = B()
print(b.i)
print(b.j)
main()

Answers:

  1. Class B inherits A, but the data field i in A is not inherited.
  2. Class B inherits A and automatically inherits all data fields in A.
  3. When you create an object B, you have to pass an integer such as B(5).
  4. The data field j cannot be accessed by object b.

141. Which option in sqllite.connect() method avoids OperationalError telling that the database file is locked?

Answers:

  1. check_same_thread
  2. check_thread
  3. check_diff_thread
  4. check_same_threads

142. The __ function can be used to check if a file f exists?

Answers:

  1. os.path.isFile(f)
  2. os.path.exists(f)
  3. os.path.isfile(f)
  4. os.isFile(f)

143.What will be the output of following code?
print «\x48\x49!»

Answers:

  1. HI!
  2. 48 49!
  3. 4849!
  4. \x48\x49!(f)

144 Considering the following code snippet:-
def test (a, b, c): pass
Which of the following is a true statement?

Answers:

  1. It defines a function that will automatically pass to other function the three parameters it receives.
  2. It defines a function that essentially does nothing.
  3. It defines an empty class.
  4. It’s a native Python function that tests if any of the parameters evaluates to `True`.(f)

145.In Python, a string literal is enclosed in _____? (check all that apply)

Answers:

  1. parentheses
  2. brackets
  3. single-quotes
  4. double-quotes

146.Which of the following is the correct way to print to stderr in Python?

Answers:

  1. sys.stderr.write(‘my_error’)
  2. print >> sys.stderr, ‘my_error’
  3. from __future__ import print_function
    print(‘my_error’, file=sys.stderr)
  4. All of these

147.In Python 3, which of the following is correct regarding data types Lists, Tuples, Dictionaries and Sets ?

Answers:

  1. `add()` from a Dictionary object will add a new key-value pair to the end of the collection.
  2. If `a_set` is a Set instance, then `a_set.difference(a_set)` will always return an empty Set object.
  3. To add a new object to the end of a Tuple, one can use the method `append()`.
  4. List objects do not have a `pop()` method as this is typical of Stack data type.

148.Which of the following will be the output of the below code snippet?

Answers:

  1. def foo(x=[]):
    x.append(1)
    print(x)
    foo()
    foo()
    foo()

  2. [1, 1]
    [1, 1]
    [1, 1]
  3. [1, 1, 1]
    [1, 1, 1]
    [1, 1, 1]
  4. [1]
    [1]
    [1]
  5. [1]
    [1, 1]
    [1, 1, 1]

149.A hashing function ____?

Answers:

  1. stores an element in the hash table
  2. maps a key to an index in the hash table
  3. different index in the hash table

150.What is the method to retrieve the list of all active thread objects?

Answers:

  1. activethreads()
  2. getThreads()
  3. threads()

151. _____ measures how full the hash table is?

Answers:

  1. Load factor
  2. Threshold
  3. Dump
  4. Tuple

152.Which of the following will be the output of the below code snippet?

x = 10
def foo():
print(x)
x = x — 1
foo()
print(x)

Answers:

  1. 10
    11
  2. 10
    9
  3. UnboundLocalError: local variable ‘x’ referenced before assignment
  4. 9
    9

152.Which is the correct syntax for Python dictionary comprehension?

Answers:

  1. (dict in dict for sequence)
  2. dict((key, value) for dict in sequence)
  3. dict((key, value) for dict(key) in sequence)
  4. dict((key, value) for (key, value) in sequence)

153.Which user input method will act like a file-object on which read and readline functions can be called?

Answers:

  1. sys.stdin
  2. dict((key, value) for dict in sequence)
  3. input()
  4. sys.argv

154. What will be the output of following code?
def f2(n, result):
if n == 0:
return 0
else:
return f2(n — 1, n + result)
print(f2(2, 0))

Answers:

  1. 0
  2. 1
  3. 2
  4. 3

155. What is the best way to randomly select an item from list?

Answers:

  1. foo = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’]
    from random import choice
    print choice(foo)
  2. foo = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’]
    from random import randrange
    random_index = randrange(0,len(foo))
    print foo[random_index]

  3. foo = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’]
    import random
    print int(random.random() * len(foo))
  4. foo = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’]
    import random
    print foo[int(random.random() * len(foo)+1)]

156. Which code snippet below will not return True?

Answers:

  1. 1 in [1,0]
  2. 1 in [1,0] == True
  3. (1 in [1,0]) == True
  4. (1 in [1,0]) == True

157. What will be the output of following code?

import threading
k = 10
x = 0
m = threading.Lock()
def foo():
global x
for i in xrange(k):
with m:
x += 1
def bar():
global x
for i in xrange(k):
with m:
x -= 1
t1 = threading.Thread(target=foo)
t2 = threading.Thread(target=bar)
t1.start()
t2.start()
t1.join()
t2.join()
print x

Answers:

  1. It will raise an exception.
  2. 1
  3. 0
  4. It will randomly print a different value on every run.

158. Which of the following are the characteristics of the __init__.py file?

import threading
k = 10
x = 0
m = threading.Lock()
def foo():
global x
for i in xrange(k):
with m:
x += 1
def bar():
global x
for i in xrange(k):
with m:
x -= 1
t1 = threading.Thread(target=foo)
t2 = threading.Thread(target=bar)
t1.start()
t2.start()
t1.join()
t2.join()
print x

Answers:

  1. __init__.py can be an empty file, but it can also execute initialization code for the package or set the __all__ variable.
  2. The __init__.py files are used to override the classes’ initializations globally.
  3. The __init__.py files are required to make Python treat the directories as if they contain packages.
  4. The __init__.py files are used to define the classes’ basic initializations.

159. What will be the output of following code?

d = lambda p: p * 2
t = lambda p: p * 3
x = 2
x = d(x)
x = t(x)
x = d(x)
print x
Answers:

  1. 7
  2. 12
  3. 24
  4. 48

160. What is the output of «Dummy Text is my text».strip(‘Te’)

t=(1,2,4,3,5)
t[1:3]
Answers:

  1. ‘Dummy Text is my text’
  2. ‘Dummy xt is my xt’
  3. ‘Dummy xt is my text’
  4. None of these

161. What will be the following code output?

import math
res = math.pow(4, 3)
def addition(x, y):
return (x+y)
def subtract(x, y):
return (x-y)
def multiply(x, y):
return (x*y)
def divide(x, y):
return (x%y)
import mathExample
print mathExample.res
Answers:

  1. 64.0
  2. 43
  3. 4.0
  4. 3.0

162. Which of the following will be the output of the below code snippet?

class foo:
def normal_call(self):
print(«normal_call»)
def call(self):
print(«first_call»)
self.call = self.normal_call
y = foo()
y.call()
y.call()
y.call()
Answers:

  1. first_call
    normal_call
    normal_call
  2. first_call
    first_call
    first_call
  3. normal_call
    normal_call
    normal_call
  4. first_call
    normal_call
    first_call

163. What command is used to get the hostname of the computer the Python script is running on?

Answers:

  1. print hostname()
  2. import socket
    print gethostname()
  3. print socket.gethostname()
  4. import socket
    print socket.gethostname()

164.Which of the following is used to get the name of a thread?

Answers:

  1. getName()
  2. getthread()
  3. getThread()
  4. get_id()
  5. 85. orig = { ‘1’ : 1, ‘2’ : 2 }
    a_copy = orig.copy()
    orig[‘1’] = 5
    sum = orig[‘1’] + a_copy[‘1’]
    print sum

    What will be printed in the above Python code?

  6. 6
  7. 1
  8. 2
  9. 10
  10. none

165.Which of the following will clone a list in Python? (choose all that apply)

Answers:

  1. new_list = old_list[:]
  2. new_list = list(old_list)
  3. import copy
    new_list = copy.copy(old_list)
  4. import copy
    new_list = copy.deepcopy(old_list)

166. On a Unix-like system, what does Python’s sleep.time() function block?

Answers:

  1. The thread.
  2. The process.
  3. Nothing.
  4. It always blocks both.

167. From the following which is not a good recommendation for Threading in Python?

Answers:

  1. Use multitasking module
  2. use Queue.Queue
  3. Use an event model, such as Twisted
  4. Use the threading module

168.Which piece of code best describes the way to parse data from JSON file?

Answers:

  1. import json
    from pprint import pprint
    with open(‘data.json’) as data_file:
    data = json.load(data_file)
    pprint(data)
  2. import json
    from pprint import pprint
    json_data=open(‘json_data’)
    data = json.load(json_data)
    pprint(data)
  3. data = []
    with codecs.open(‘d:\output.txt’,’rU’,’utf-8′) as f:
    for line in f:
    data.append(json.loads(line))
  4. None of the above

168.What will be the output of following code?
def val1(param):
return param
def val2(param):
return param * 2
def val3(param):
return param + 5
result = val1(val2(val3(1)))
print(result)

Answers:

  1. 8
  2. 12
  3. 10
  4. 6

170. Which of the following code snippets can be used to get the multiples of 2 from the list
a = [1, 2, 3, 4, 5, 6, 7, 8, 9] ?

Answers:

  1. b = filter(lambda x: x % 2 == 0, a)
  2. b = [x for x in a if x % 2 == 0]
  3. def filterfunc(x):
    return x % 2 == 0
    b = filter(filterfunc, a)
  4. All of these

171. Which of the following code snippets converts the hexademical number 0x1000 to a decimal correctly?

Answers:

  1. int(‘1000’, 16)
  2. int(1000)
  3. 1 * (16 ** 4) + 0 + 0 + 0
  4. int.fromhex(‘0x1000’)

172. Which of the function immediately terminates the program?

Answers:

  1. sys.stop()
  2. sys.close()
  3. sys.exit()
  4. sys.terminate()

173. Which of the following is the proper way to declare custom exceptions in modern Python?

Answers:

  1. class MyException(Exception):
    pass
  2. class MyException():
    pass
  3. class MyException(Error):
    pass
  4. class MyException:
    pass

173. Considering Python 2.5, what will be the output of following code?

fp = None
with open(‘file.data’, ‘r’) as fp:
cont = f.read()
print fp.closed

Answers:

  1. True
  2. False
  3. None
  4. It raises AttributeError: object has no attribute ‘closed’

174. What will be the output of following code?

def addItem(l):
l += [0]
mylist = [1, 2, 3, 4, 5]
addItem(mylist)
print len(mylist)

Answers:

  1. 12345
  2. 1234
  3. 01234
  4. 6

175.What is the result of the following code:

listOne = [1, 3, 5]
listTwo = [2, 4, 6]
listNew = listOne + listTwo
print listNew

Answers:

  1. [3, 7, 11]
  2. [1, 2, 3, 4, 5, 6]
  3. [1, 3, 5, 2, 4, 6]
  4. [ [1, 3, 5], [2, 4, 6] ]

176.Regarding the code below, what’s correct statement ?

class Book:
def __init__(self, isbn):
self.isbn = isbn
isbn = ‘test’
book = Book(12345)
Answers:

  1. book.isbn will contain the value 12345.
  2. book.isbn will contain the value ‘test’.
  3. This program won’t run the Book class expects a string instead of integer.
  4. None of the above is correct.

177.hat will be the output of the code below?

s = ‘messha’
for i in range(len(s)):
print(i)
Answers:

  1. m e s s h a
  2. 0 1 2 3 4 5
  3. 6
  4. 5

178.Which of the following will remove duplicate elements from a list (O(n)), whilst preserving order?

s = ‘messha’
for i in range(len(s)):
print(i)
Answers:

  1. mylist = [x for i,x in enumerate(mylist) if x not in mylist[i+1:]]
  2. mylist = reduce(lambda x, y: x if y in x else x + [y], mylist, [])
  3. seen = set()
    seen_add = seen.add
    mylist = [ x for x in mylist if x not in seen and not seen_add(x)]
  4. mylist = [x for i,x in enumerate(mylist) if x not in mylist[:i]]

179.Consider the following Python code:
test = 1/2
What is the value of ‘test’ in Python 2.7 and 3.5, respectively ?

s = ‘messha’
for i in range(len(s)):
print(i)
Answers:

  1. 0 and 1
  2. 0 and 0.5
  3. 0.5 and 0
  4. 1 and 0

180.Which of the following is the correct method for changing a global variable inside a function?

Answers:

  1. def change_globvar():
    globvar = 1
  2. def change_globvar():
    global globvar
    globvar = 1
  3. def change_globvar():
    import globvar
    globvar = 1
  4. def change_globvar():
    global globvar = 1

181. Which one of these answers will catch an exception, but do nothing with it?

Answers:

  1. doSomething()
  2. try:
    doSomething()
  3. try:
    doSomething()
    except:
  4. try:
    doSomething()
    except:
    pass

182.Suppose we have a User class, how do we make a new User object?

Answers:

  1. a = new User()
  2. User a = new User()
  3. User.new(Object)
  4. a = User()

183.Suppose we have a User class, how do we make a new User object?
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
new_list = list(filter(lambda x: (x%2 == 0) , my_list))
print(new_list)

Answers:

  1. [1, 3, 5, 6, 9]
  2. [1, 5, 7, 9, 10]
  3. [2, 4, 6, 8, 10]
  4. [0, 4, 6, 8, 10]

184.Given the two dictionaries ‘x’ and ‘y’, which of these codes would not create a final, merged dictionary ‘z’?
x = {‘a’:1, ‘b’: 2}
y = {‘b’:10, ‘c’: 11}
z = {‘a’: 1, ‘c’: 11, ‘b’: 10}

Answers:

  1. z = dict(x.items() + y.items())
  2. z = x.copy()
    z.update(y)
  3. z = dict(x, **y)
  4. z = x.update(y)
  5. z = dict(list(x.items()) + list(y.items()))

184.Which of the following is NOT correct regarding unittest in Python 3?
x = {‘a’:1, ‘b’: 2}
y = {‘b’:10, ‘c’: 11}
z = {‘a’: 1, ‘c’: 11, ‘b’: 10}

Answers:

  1. Each test case must be defined inside a class that inherits from unittest.TestCase
  2. @unittest.skip is a decorator designed to disable the specific test unit from running.
  3. setUp() from unittest.TestCase can be overridden and is called immediately before calling the test method
  4. tearDown() from unittest.TestCase is called only once per class, immediately before the first test method.

184.Which of the following would create an instance of Firm class correctly?
x = {‘a’:1, ‘b’: 2}
y = {‘b’:10, ‘c’: 11}
z = {‘a’: 1, ‘c’: 11, ‘b’: 10}

Answers:

  1. Firm = Firm(‘client’, 2000)
  2. Firm = Firm()
  3. Firm = Firm(‘server’, 2000)
  4. None of the above

185. What will be the output of the following code?
def name(X, Y, Z, **opt):
if opt.get(«number») == «Y»:
return Y
res = name(1, 2, 3, action = «sum», number = «Y»)
print «Result: %d» % res

Answers:

  1. Result: 1
  2. Result: 2
  3. Result: 3
  4. Result: 0

186. What is the type of x?
x = 10.0//5

Answers:

  1. int
  2. float
  3. long
  4. number

187. What is the output if the following code is executed?
a1 = 0
b2 = 1
c3 = 2
def fru_box():
a1 = b2 + c3
print((a1, ‘\t’, b2, ‘\t’, c3))
return
fru_box()

Answers:

  1. (1, ‘\t’, 2, ‘\t’, 3)
  2. (2, ‘\t’, 1, ‘\t’, 3)
  3. (1, ‘\t’, 3, ‘\t’, 2)
  4. (3, ‘\t’, 1, ‘\t’, 2)

188. In the following code, what will be printed ?
class parent:
def __init__(self, param):
self.v1 = param
class child(parent):
def __init__(self, param):
self.v2 = param
obj = child(5)
print «%d %d» % (obj.v1, obj.v2)

Answers:

  1. None None
  2. (2, ‘\t’, 1, ‘\t’, 3)
  3. None 5
  4. 5 None
  5. 5 5

189. Which of the following snippets will return the list of all occurances of ‘b’ in
a = [‘a’,’b’,’c’,’b’] ?

class parent:
def __init__(self, param):
self.v1 = param
class child(parent):
def __init__(self, param):
self.v2 = param
obj = child(5)
print «%d %d» % (obj.v1, obj.v2)

Answers:

  1. b = [item for item in a if a == ‘b’][0]
  2. b = [item for item in a if a[] == ‘b’]
  3. None 5
  4. 5 None
  5. 5 5

5,607 total views, 7 views today