1. Which of the following will disable output buffering in Python?
Answers:
a. Using the -u command line switch
a. 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)
a. Setting the PYTHONUNBUFFERED environment variable
a. sys.stdout = os.fdopen(sys.stdout.fileno(), ‘w’, 0)
2. Which of the following members of the object class compare two parameters?
Answers:
a. object.__eq__(self, other)
a. object.__ne__(self, other)
a. object.__compare__(self, other)
a. object.__equals__(self, other)
a. object.__co__(self, other)
a. 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:
a. object.__eq__(self, other)
a. object.__ne__(self, other)
a. object.__nz__(self)
a. object.__repr__(self)
a. None of these
4. In Python, what is the default maximum level of recursion?
Answers:
a. 500
a. 1000
a. 10000
a. 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:
a. mailstruct
a. emailarch
a. emailfolders
a. mailbox
6. Which of the following are the main features of Python?
Answers:
a. Cross-platform
a. Extensible
a. Object-oriented, with multiple inheritance
a. Written in Java
a. Overloading of common operators
a. All of these
7. Which of the following variables store parameters passed from outside?
Answers:
a. sys.param
a. sys.arg
a. sys.argv
a. sys.prm
8. Which of the following functions can change the maximum level of recursion?
Answers:
a. setmaxrecursion function in the sys module
a. setrecursionlimit function in the sys module
a. setmaximumrecursion function in the sys module
a. None of these
9. Read the following statements:
Answers:
a. Using the -u command line switch
a. 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)
a. Setting the PYTHONUNBUFFERED environment variable
a. sys.stdout = os.fdopen(sys.stdout.fileno(), ‘w’, 0)
2. Which of the following members of the object class compare two parameters?
Answers:
a. object.__eq__(self, other)
a. object.__ne__(self, other)
a. object.__compare__(self, other)
a. object.__equals__(self, other)
a. object.__co__(self, other)
a. 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:
a. object.__eq__(self, other)
a. object.__ne__(self, other)
a. object.__nz__(self)
a. object.__repr__(self)
a. None of these
4. In Python, what is the default maximum level of recursion?
Answers:
a. 500
a. 1000
a. 10000
a. 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:
a. mailstruct
a. emailarch
a. emailfolders
a. mailbox
6. Which of the following are the main features of Python?
Answers:
a. Cross-platform
a. Extensible
a. Object-oriented, with multiple inheritance
a. Written in Java
a. Overloading of common operators
a. All of these
7. Which of the following variables store parameters passed from outside?
Answers:
a. sys.param
a. sys.arg
a. sys.argv
a. sys.prm
8. Which of the following functions can change the maximum level of recursion?
Answers:
a. setmaxrecursion function in the sys module
a. setrecursionlimit function in the sys module
a. setmaximumrecursion function in the sys module
a. 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)
>>> 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:
a. Spam and toast
a. spam and toast
a. Spam and eggs
a. spam and eggs
a. spamandtoast
a. spamandeggs
10. How can a numeric String (eg. “545.2222”) be converted to Float or Integer?
Answers:
a. 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”)
a. def convert(n): try: return int(n) except ValueError: return float(n + 0.5) convert(“545.2222”)
a. a = “545.2222” float(a) int(float(a))
a. def parseIntOrFloat(s): return eval(s)
11. Which of the following is the correct prototype of the string.find() function?
Answers:
a. string.find(s, sub ,start ,end)
a. string.find(s, sub ,start [,end])
a. string.find(s, sub [,start [,end]])
a. 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:
a. coding: iso-8859-15
a. # -*- iso-8859-15 -*-
a. # -*- coding: iso-8859-15 -*-
a. None of these
13. How can a null object be declared in Python?
Answers:
a. none
a. None
a. null
a. Null
14. Which of the following modules lets you check whether two files are identical, and whether two directories contain some identical files?
Answers:
a. dircomp
a. filecompare
a. filecmp
a. structcomp
15. Which function could be used to list every file and folder in the current directory?
Answers:
a. os.dirnames(‘.’)
a. os.listdir(‘.’)
a. os.listdir(‘/’)
a. 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:
a. MimeWriter
a. mimify
a. Both MimeWriter and mimify
a. 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:
a. open(fname [,mode [,buffering]])
a. open(fname [,buffering [,mode]])
a. open(fname [,mode])
a. open(fname,mode,buffering)
a. open(fname,buffering,mode)
a. None of these
18. Which user input method will act like a file-object on which read and readline functions can be called?
Answers:
a. sys.stdin
a. raw_input()
a. input()
a. sys.argv
19. Which of the following protocol libraries can be used for an email implementation in a Python application?
Answers:
a. telnetlib
a. smtplib
a. ftplib
a. None of these
20. Which of the following statements imports every name in a module namespace into the current namespace?
Answers:
a. from modname import All
a. from modname import *
a. from modname import ?
a. from modname import All as *
21. Which is the correct way to remove an installed Python package?
Answers:
a. easy_install -v a. pip uninstall
a. easy_install -u a. pip -m 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:
a. try: code to be verified will come here exception :
a. try: code to be verified will come here except :
a. try: code to be verified will come here exception:
a. try: code to be verified will come here exception :
23. Which of the following is the correct way to get the size of a list in Python?
Answers:
a. list.length()
a. len(list)
a. sizeof(list)
a. list.size()
24. What will be the output of the following statements:
Answers:
a. Spam and toast
a. spam and toast
a. Spam and eggs
a. spam and eggs
a. spamandtoast
a. spamandeggs
10. How can a numeric String (eg. “545.2222”) be converted to Float or Integer?
Answers:
a. 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”)
a. def convert(n): try: return int(n) except ValueError: return float(n + 0.5) convert(“545.2222”)
a. a = “545.2222” float(a) int(float(a))
a. def parseIntOrFloat(s): return eval(s)
11. Which of the following is the correct prototype of the string.find() function?
Answers:
a. string.find(s, sub ,start ,end)
a. string.find(s, sub ,start [,end])
a. string.find(s, sub [,start [,end]])
a. 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:
a. coding: iso-8859-15
a. # -*- iso-8859-15 -*-
a. # -*- coding: iso-8859-15 -*-
a. None of these
13. How can a null object be declared in Python?
Answers:
a. none
a. None
a. null
a. Null
14. Which of the following modules lets you check whether two files are identical, and whether two directories contain some identical files?
Answers:
a. dircomp
a. filecompare
a. filecmp
a. structcomp
15. Which function could be used to list every file and folder in the current directory?
Answers:
a. os.dirnames(‘.’)
a. os.listdir(‘.’)
a. os.listdir(‘/’)
a. 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:
a. MimeWriter
a. mimify
a. Both MimeWriter and mimify
a. 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:
a. open(fname [,mode [,buffering]])
a. open(fname [,buffering [,mode]])
a. open(fname [,mode])
a. open(fname,mode,buffering)
a. open(fname,buffering,mode)
a. None of these
18. Which user input method will act like a file-object on which read and readline functions can be called?
Answers:
a. sys.stdin
a. raw_input()
a. input()
a. sys.argv
19. Which of the following protocol libraries can be used for an email implementation in a Python application?
Answers:
a. telnetlib
a. smtplib
a. ftplib
a. None of these
20. Which of the following statements imports every name in a module namespace into the current namespace?
Answers:
a. from modname import All
a. from modname import *
a. from modname import ?
a. from modname import All as *
21. Which is the correct way to remove an installed Python package?
Answers:
a. easy_install -v a. pip uninstall
a. easy_install -u a. pip -m 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:
a. try: code to be verified will come here exception :
a. try: code to be verified will come here except :
a. try: code to be verified will come here exception:
a. try: code to be verified will come here exception :
23. Which of the following is the correct way to get the size of a list in Python?
Answers:
a. list.length()
a. len(list)
a. sizeof(list)
a. 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:
a. ‘Mary had a little lamb ‘
a. ‘Mary had a little lamb’
a. ‘ Mary had a little lamb’
a. 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:
a. email.Message
a. email.message.Message
a. email.messages
a. email.emailmessage
26. Consider the function:
>>> string.ljust(width=30,s=”Mary had a little lamb”)
Answers:
a. ‘Mary had a little lamb ‘
a. ‘Mary had a little lamb’
a. ‘ Mary had a little lamb’
a. 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:
a. email.Message
a. email.message.Message
a. email.messages
a. email.emailmessage
26. Consider the function:
def hello():
return “Hello, world!”
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:
a. def hello(): return “#Hello, world!#”
a. def hashes(fn): def wrapped(): return “#” + fn() + “#” return wrapped @hashes def hello(): return “Hello, world!”
a. def hashes(fn): def wrapped(): return “#” + “#” return wrapped @hashes def hello(): return “Hello, world!”
a. 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:
a. object.__eq__(self, other)
a. object.__notequal__(self, other)
a. object.__repr__(self)
a. 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:
a. sys
a. FileSys
a. dirsys
a. dircache
29. Which of the following modules is used internally to determine whether a path matches?
Answers:
a. dircmp
a. filecompare
a. fncmp
a. fnmatch
30. Examine the following prototype for the ‘open’ function of the file class in Python 2.2+:
Answers:
a. def hello(): return “#Hello, world!#”
a. def hashes(fn): def wrapped(): return “#” + fn() + “#” return wrapped @hashes def hello(): return “Hello, world!”
a. def hashes(fn): def wrapped(): return “#” + “#” return wrapped @hashes def hello(): return “Hello, world!”
a. 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:
a. object.__eq__(self, other)
a. object.__notequal__(self, other)
a. object.__repr__(self)
a. 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:
a. sys
a. FileSys
a. dirsys
a. dircache
29. Which of the following modules is used internally to determine whether a path matches?
Answers:
a. dircmp
a. filecompare
a. fncmp
a. 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:
a. 0 for none
a. 1 for line oriented
a. An integer larger than 1 for number of bytes
a. All of these
31. Which of the following statements copy the contents of a list and not just a reference to the list?
Answers:
a. newlist = oldlist
a. newlist = oldlist[:]
a. newlist = oldlist(dummy)
a. None of these
32. Which of the following functions is used to send audio data via the Internet?
Answers:
a. email.MIMEAudio(audiodata [,subtype [,encoder [,**params]]])
a. email.SendAudio(audiodata [,subtype [,encoder [,**params]]])
a. email.MIMEAudio.MIMEAudio(audiodata [,subtype [,encoder [,**params]]])
a. email.MIMEAudio.SendAudio(audiodata [,subtype [,encoder [,**params]]])
33. Read the following statements:
Answers:
a. 0 for none
a. 1 for line oriented
a. An integer larger than 1 for number of bytes
a. All of these
31. Which of the following statements copy the contents of a list and not just a reference to the list?
Answers:
a. newlist = oldlist
a. newlist = oldlist[:]
a. newlist = oldlist(dummy)
a. None of these
32. Which of the following functions is used to send audio data via the Internet?
Answers:
a. email.MIMEAudio(audiodata [,subtype [,encoder [,**params]]])
a. email.SendAudio(audiodata [,subtype [,encoder [,**params]]])
a. email.MIMEAudio.MIMEAudio(audiodata [,subtype [,encoder [,**params]]])
a. 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.
Statement 2: A name declared as global is bound to the global (module-level) namespace.
Which of the following is correct?
Answers:
a. Statement 1 is true, but statement 2 is false.
a. Statement 2 is true, but statement 1 is false.
a. Both statements are true.
a. Both statements are false.
34. Which of the following commands would produce the following result:
result: ‘line 1\nline 2’
Answers:
a. result = ‘\nline 1\nline 2\n’.rstrip()
a. result = ‘\nline 1\nline 2\n’.split()
a. result = ‘\nline 1\nline 2\n’.strip()
a. result = ‘\nline 1\nline 2\n’.lstrip()
a. result = ‘\nline 1\nline 2\n’.splitlines()
35. Which is not used to install Python packages?
Answers:
a. easy_install
a. pip
a. distribute
a. installtools
36. Which of the following exceptions occurs while importing a module?
Answers:
a. ModuleError
a. ImportError
a. ImportModuleError
a. ReferenceError
37. Which of the following statements can be used to remove an item from a list by giving the index?
Answers:
a. remove listname[index]
a. del listname[index]
a. kill listname[index]
a. None of these
38. Read the following statements:
Answers:
a. Statement 1 is true, but statement 2 is false.
a. Statement 2 is true, but statement 1 is false.
a. Both statements are true.
a. Both statements are false.
34. Which of the following commands would produce the following result:
result: ‘line 1\nline 2’
Answers:
a. result = ‘\nline 1\nline 2\n’.rstrip()
a. result = ‘\nline 1\nline 2\n’.split()
a. result = ‘\nline 1\nline 2\n’.strip()
a. result = ‘\nline 1\nline 2\n’.lstrip()
a. result = ‘\nline 1\nline 2\n’.splitlines()
35. Which is not used to install Python packages?
Answers:
a. easy_install
a. pip
a. distribute
a. installtools
36. Which of the following exceptions occurs while importing a module?
Answers:
a. ModuleError
a. ImportError
a. ImportModuleError
a. ReferenceError
37. Which of the following statements can be used to remove an item from a list by giving the index?
Answers:
a. remove listname[index]
a. del listname[index]
a. kill listname[index]
a. None of these
38. Read the following statements:
>>> word = ‘Help’ + ‘A’
>>> ‘<‘ + word*5 + ‘>’
>>> ‘<‘ + word*5 + ‘>’
Which of the following will be the output of the above code snippet?
Answers:
a. ”
a. ”
a. ‘<HelpA*5>’
a. An error
a. 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:
a. STDOUT
a. STDERR
a. STDPRN
a. STDFIL
40. Which of the following options are true regarding these two code samples?
Answers:
a. ”
a. ”
a. ‘<HelpA*5>’
a. An error
a. 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:
a. STDOUT
a. STDERR
a. STDPRN
a. 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()
def main():
for i in xrange(10**8):
pass
main()
Code sample 2:
for i in xrange(10**8):
pass
Answers:
a. 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.
a. 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.
a. 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.
a. None of these.
41. How many arguments can a print statement handle?
Answers:
a. One
a. Any number of string arguments only
a. Any number of numeric arguments only
a. Any number of string or numeric arguments
42. When is the “yield” keyword used in Python?
Answers:
a. When other processes need to take precedence over the Python script
a. To break out of a loop
a. When a function needs to return a list that only needs to be read through once
a. Never
43. What is the best way to check if the object ‘myobject’ is iterable in Python?
Answers:
a. myobject.isIter()
a. try: [ e for e in myobject] except TypeError: print myobject, ‘is not iterable’
a. try: iter.myobject except: print myobject, ‘is not iterable’
a. 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:
a. Exceptions
a. BaseException
a. Exception
a. 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:
a. d = os.path.dirname(“/temp_files”) if not os.path.exists(d): os.makedirs(d)
a. d = os.path(“/temp_files”) if not os.path(d): os.makedirs(d)
a. d = os.path.dirname(“/temp_files”) if os.path.exists(d): os.makedirs(d)
a. if not os.path.exists(“/temp_files”): os.makedirs(d)
46. Read the following statements:
for i in xrange(10**8):
pass
Answers:
a. 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.
a. 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.
a. 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.
a. None of these.
41. How many arguments can a print statement handle?
Answers:
a. One
a. Any number of string arguments only
a. Any number of numeric arguments only
a. Any number of string or numeric arguments
42. When is the “yield” keyword used in Python?
Answers:
a. When other processes need to take precedence over the Python script
a. To break out of a loop
a. When a function needs to return a list that only needs to be read through once
a. Never
43. What is the best way to check if the object ‘myobject’ is iterable in Python?
Answers:
a. myobject.isIter()
a. try: [ e for e in myobject] except TypeError: print myobject, ‘is not iterable’
a. try: iter.myobject except: print myobject, ‘is not iterable’
a. 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:
a. Exceptions
a. BaseException
a. Exception
a. 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:
a. d = os.path.dirname(“/temp_files”) if not os.path.exists(d): os.makedirs(d)
a. d = os.path(“/temp_files”) if not os.path(d): os.makedirs(d)
a. d = os.path.dirname(“/temp_files”) if os.path.exists(d): os.makedirs(d)
a. 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)
>>> 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:
a. spam and eggs
a. spamandeggs
a. spamandtoast
a. spam and toast
47. Read the following statements:
Answers:
a. spam and eggs
a. spamandeggs
a. spamandtoast
a. spam and toast
47. Read the following statements:
>>> import string
>>> s = ‘mary\011had a little lamb’
>>> print s
>>> s = ‘mary\011had a little lamb’
>>> print s
Which of the following will be the output of the above code snippet?
Answers:
a. mary had a little lamb
a. mary\011 had a little lamb
a. mary had a little lamb
a. mary\011had a little lamb
48. Read the following statements:
Answers:
a. mary had a little lamb
a. mary\011 had a little lamb
a. mary had a little lamb
a. mary\011had 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.
Statement 2: To use string object methods, there is no need to import the string module.
Which of the following is correct?
Answers:
a. Statement 1 is true, but statement 2 is false.
a. Statement 2 is true, but statement 1 is false.
a. Both statements are true.
a. 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:
a. A dictionary sorted by the second element.
a. A list of Tuples sorted by the second element.
a. A list of dictionaries sorted by the first element.
a. A dictionary sorted by the first element.
a. 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:
a. base
a. object
a. dict
a. custom
a. None of these
51. How can a list be split into equal sized chunks?
Answers:
a. f = lambda x, n, acc=[]: f(x[n:], n, acc+[(x[:n])]) if x else acc
a. def chunks(l, n): for i in xrange(0, len(l), n): yield l[i:i+n]
a. 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
a. 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:
a. 1
a. 2
a. 7
a. Any number
53. Which of the following is the best way to reverse the string ‘Test String’ in Python?
Answers:
a. string.reverse(‘Test String’)
a. ‘Test String'[::-1]
a. reversed(‘Test String’)
a. ‘Test String'[-1:0]
54. What is the result of the following code:
>>> import itertools
>>> x = itertools.count(0)
>>> x.__class__.__name__
Answers:
a. Nothing
a. ‘count’
a. ‘Object’
a. ‘None’
55. What is the most flexible way to call the external command “ls -l” in Python?
Answers:
a. from subprocess import call call([“ls”, “-l”])
a. from subprocess import call call(“ls -l”)
a. os.system(“ls -l”)
a. os.system([“ls”], [“-l”])
56. Which of the following is the correct method for changing a global variable inside a function?
Answers:
a. def change_globvar(): globvar = 1
a. def change_globvar(): global globvar globvar = 1
a. def change_globvar(): import globvar globvar = 1
a. def change_globvar(): global globvar = 1
57. Which list flattening method will have the shortest running time?
Answers:
a. l = [ [1, 2, 3], [4, 5, 6], [7], [8, 9] ] * 99 import itertools list( itertools.chain.from_iterable( l ) )
a. l = [ [1, 2, 3], [4, 5, 6], [7], [8, 9] ] * 99 reduce( lambda x, y: x + y, l )
a. l = [ [1, 2, 3], [4, 5, 6], [7], [8, 9] ] * 99 sum( l, [ ] )
a. 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:
a. import sys sys.stdout.flush()
a. 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)
a. import sys sys.stdout = os.fdopen(sys.stdout.fileno(), ‘w’, 0)
a. 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:
a. import re indices = [occurance.start() for occurance in re.finditer(word, line)]
a. 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))
a. indices = [i – 1 for i in range(len(line)) if line.startswith(word, i – 1)]
a. 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:
a. assert isinstance(x, basestring)
a. assert not isinstance(x, basestring)
a. assert not instance(x, basestring)
a. assert not x.isinstance(basestring)
61. Which of the following will throw an exception in Python?
Answers:
a. call Exception(“Here is an Exception!”)
a. throw Exception(“Here is an Exception!”)
a. raise Exception(“Here is an Exception!”)
a. 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:
a. dircache.listdir(path, lst)
a. dircache.annotate(path, lst)
a. dircache.filter(path, lst)
a. dircache.scan(path, lst)
63. Which Python module can be used for copying files?
Answers:
a. util
a. shutil
a. copy
a. filecopy
64. Which of the following statements are true?
Answers:
a. Statement 1 is true, but statement 2 is false.
a. Statement 2 is true, but statement 1 is false.
a. Both statements are true.
a. 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:
a. A dictionary sorted by the second element.
a. A list of Tuples sorted by the second element.
a. A list of dictionaries sorted by the first element.
a. A dictionary sorted by the first element.
a. 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:
a. base
a. object
a. dict
a. custom
a. None of these
51. How can a list be split into equal sized chunks?
Answers:
a. f = lambda x, n, acc=[]: f(x[n:], n, acc+[(x[:n])]) if x else acc
a. def chunks(l, n): for i in xrange(0, len(l), n): yield l[i:i+n]
a. 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
a. 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:
a. 1
a. 2
a. 7
a. Any number
53. Which of the following is the best way to reverse the string ‘Test String’ in Python?
Answers:
a. string.reverse(‘Test String’)
a. ‘Test String'[::-1]
a. reversed(‘Test String’)
a. ‘Test String'[-1:0]
54. What is the result of the following code:
>>> import itertools
>>> x = itertools.count(0)
>>> x.__class__.__name__
Answers:
a. Nothing
a. ‘count’
a. ‘Object’
a. ‘None’
55. What is the most flexible way to call the external command “ls -l” in Python?
Answers:
a. from subprocess import call call([“ls”, “-l”])
a. from subprocess import call call(“ls -l”)
a. os.system(“ls -l”)
a. os.system([“ls”], [“-l”])
56. Which of the following is the correct method for changing a global variable inside a function?
Answers:
a. def change_globvar(): globvar = 1
a. def change_globvar(): global globvar globvar = 1
a. def change_globvar(): import globvar globvar = 1
a. def change_globvar(): global globvar = 1
57. Which list flattening method will have the shortest running time?
Answers:
a. l = [ [1, 2, 3], [4, 5, 6], [7], [8, 9] ] * 99 import itertools list( itertools.chain.from_iterable( l ) )
a. l = [ [1, 2, 3], [4, 5, 6], [7], [8, 9] ] * 99 reduce( lambda x, y: x + y, l )
a. l = [ [1, 2, 3], [4, 5, 6], [7], [8, 9] ] * 99 sum( l, [ ] )
a. 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:
a. import sys sys.stdout.flush()
a. 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)
a. import sys sys.stdout = os.fdopen(sys.stdout.fileno(), ‘w’, 0)
a. 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:
a. import re indices = [occurance.start() for occurance in re.finditer(word, line)]
a. 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))
a. indices = [i – 1 for i in range(len(line)) if line.startswith(word, i – 1)]
a. 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:
a. assert isinstance(x, basestring)
a. assert not isinstance(x, basestring)
a. assert not instance(x, basestring)
a. assert not x.isinstance(basestring)
61. Which of the following will throw an exception in Python?
Answers:
a. call Exception(“Here is an Exception!”)
a. throw Exception(“Here is an Exception!”)
a. raise Exception(“Here is an Exception!”)
a. 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:
a. dircache.listdir(path, lst)
a. dircache.annotate(path, lst)
a. dircache.filter(path, lst)
a. dircache.scan(path, lst)
63. Which Python module can be used for copying files?
Answers:
a. util
a. shutil
a. copy
a. 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:
a. A
a. B
a. C
a. A, B, and C
65. How can an element be removed from a list using its list index?
Answers:
a. myList.remove(index)
a. pop myList[index]
a. del myList[index]
a. myList.delete(index)
66. Which of the following is the correct way to check to see if the variable theVar is an integer?
Answers:
a. isinstance(theVar, int)
a. theVar.isinstance(int)
a. int.isinstance(theVar)
a. is(theVar, int)
67. Which of the following is the base class for new-style file objects?
Answers:
a. base
a. file
a. fileobject
a. filebase
68. Which of the following methods returns the ASCII value of a character in Python?
Answers:
a. ascii
a. ord
a. asciicode
a. None of these
69. What is the output of the following code:
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:
a. A
a. B
a. C
a. A, B, and C
65. How can an element be removed from a list using its list index?
Answers:
a. myList.remove(index)
a. pop myList[index]
a. del myList[index]
a. myList.delete(index)
66. Which of the following is the correct way to check to see if the variable theVar is an integer?
Answers:
a. isinstance(theVar, int)
a. theVar.isinstance(int)
a. int.isinstance(theVar)
a. is(theVar, int)
67. Which of the following is the base class for new-style file objects?
Answers:
a. base
a. file
a. fileobject
a. filebase
68. Which of the following methods returns the ASCII value of a character in Python?
Answers:
a. ascii
a. ord
a. asciicode
a. None of these
69. What is the output of the following code:
name = ‘Jon’
name.rjust(4, ‘A’)
Answers:
a. ‘Jon A’
a. ‘A Jon’
a. ‘AJon’
a. ‘JonA’
70. Which of the following is a way to find a local computer’s IP address with Python?
Answers:
a. import socket socket.gethostbyname(socket.gethostname())
a. socket.gethostbyname(socket.gethostname())
a. import socket gethostbyname(socket.gethostname())
a. import ifconfig print (ifconfig -a)
71. What is a metaclass in Python?
Answers:
a. A class that is inherited from
a. A class that inherits from another class
a. Something that can be attached to any class, that gives it a constant set of attributes
a. 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)?
name.rjust(4, ‘A’)
Answers:
a. ‘Jon A’
a. ‘A Jon’
a. ‘AJon’
a. ‘JonA’
70. Which of the following is a way to find a local computer’s IP address with Python?
Answers:
a. import socket socket.gethostbyname(socket.gethostname())
a. socket.gethostbyname(socket.gethostname())
a. import socket gethostbyname(socket.gethostname())
a. import ifconfig print (ifconfig -a)
71. What is a metaclass in Python?
Answers:
a. A class that is inherited from
a. A class that inherits from another class
a. Something that can be attached to any class, that gives it a constant set of attributes
a. 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”
def __myPrivateMethod(self):
print “Private Method”
obj = MyClass()
print dir(obj)
Answers:
a. __myPrivateMethod
a. _MyClass__myPrivateMethod
a. myPrivateMethod
a. A private method will not be shown in the output.
73. What is the output of the following code?
print dir(obj)
Answers:
a. __myPrivateMethod
a. _MyClass__myPrivateMethod
a. myPrivateMethod
a. 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
print param1
print param2
def bar(param1, **param2):
print param1
print param2
print param1
print param2
foo(1,2,3,4,5)
bar(1,a=2,b=3)
Answers:
a. TypeError: foo() got multiple values for keyword argument ‘param1’
a. 1 (2, 3, 4, 5) 1 (2, 3)
a. 1 (2, 3, 4, 5) 1 {‘a’: 2, ‘b’: 3}
a. 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:
a. import subprocess subprocess.call(‘C:\\Temp\\a b c\\Notepad.exe’, ‘C:\\test.txt’)
a. os.call([‘C:\\Temp\\a b c\\Notepad.exe’, ‘C:\\test.txt’])
a. import subprocess subprocess.call([‘C:\\Temp\\a b c\\Notepad.exe’, ‘C:\\test.txt’])
a. 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:
a. os.remove(‘/directory’)
a. os.rmtree(‘/directory’)
a. shutil.rmtree(‘/directory’)
a. 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:
a. def onehundred(start, end): current = start while current <= end: yield current current += 1 for x in onehundred(1, 100): print x
a. def onehundred(start, end): current = start while current <= end: return current current += 1 for x in onehundred(1, 100): print x
a. def onehundred(start, end): current = start while current <= end: yield current current += 2 for x in onehundred(1, 100): print x
a. 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:
a. a_list + a_tuple
a. a_list.extend(a_tuple)
a. a_list.append(a_tuple)
a. a_list.append(*a_tuple)
78. Which of the following will determine the number of CPUs available in the operating environment?
Answers:
a. import os os..cpu_count()
a. import sys sys..cpu_count()
a. import psutil sutil.NUM_CPUS
a. import multiprocessing multiprocessing.cpu_count()
bar(1,a=2,b=3)
Answers:
a. TypeError: foo() got multiple values for keyword argument ‘param1’
a. 1 (2, 3, 4, 5) 1 (2, 3)
a. 1 (2, 3, 4, 5) 1 {‘a’: 2, ‘b’: 3}
a. 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:
a. import subprocess subprocess.call(‘C:\\Temp\\a b c\\Notepad.exe’, ‘C:\\test.txt’)
a. os.call([‘C:\\Temp\\a b c\\Notepad.exe’, ‘C:\\test.txt’])
a. import subprocess subprocess.call([‘C:\\Temp\\a b c\\Notepad.exe’, ‘C:\\test.txt’])
a. 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:
a. os.remove(‘/directory’)
a. os.rmtree(‘/directory’)
a. shutil.rmtree(‘/directory’)
a. 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:
a. def onehundred(start, end): current = start while current <= end: yield current current += 1 for x in onehundred(1, 100): print x
a. def onehundred(start, end): current = start while current <= end: return current current += 1 for x in onehundred(1, 100): print x
a. def onehundred(start, end): current = start while current <= end: yield current current += 2 for x in onehundred(1, 100): print x
a. 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:
a. a_list + a_tuple
a. a_list.extend(a_tuple)
a. a_list.append(a_tuple)
a. a_list.append(*a_tuple)
78. Which of the following will determine the number of CPUs available in the operating environment?
Answers:
a. import os os..cpu_count()
a. import sys sys..cpu_count()
a. import psutil sutil.NUM_CPUS
a. import multiprocessing multiprocessing.cpu_count()
13 NOT Answered Yet Test Questions:
(hold on, will be updated soon)
79. Read the following code snippet:
(hold on, will be updated soon)
79. Read the following code snippet:
>>> o1 = C()
>>> o1.lst = [1,2,3]
>>> o3 = copy.deepcopy(o1)
>>> o1.lst.append(17)
>>> o1.lst = [1,2,3]
>>> o3 = copy.deepcopy(o1)
>>> o1.lst.append(17)
What will be the output of ‘>>> o3.lst’ and ‘>>> o1.lst’?
Answers:
a. [1, 2, 3] and [1, 2, 3, 17]
a. [1, 2, 3, 17] and [1, 2, 3, 17]
a. [1, 2, 3] and [1, 2, 3]
a. None of these
80. While running an application, a user pressed the interrupt key (Ctrl + C). Which of the following exceptions will occur?
Answers:
a. InterruptError
a. KeyboardInterrupt
a. KeyboardInterruptError
a. None of these
81. Which of the following statements will redirect the output of the print statement into a file-like object named ‘test’?
Answers:
a. print >> open(‘test’,’w’), “Pi: %.3f” % 3.1415, 27+11
a. print ‘test’, “Pi: %.3f” % 3.1415, 27+11
a. print open(‘test’,’w’), “Pi: %.3f” % 3.1415, 27+11
a. print $$ open(‘test’,’w’), “Pi: %.3f” % 3.1415, 27+11
82. Read the following statements:
Answers:
a. [1, 2, 3] and [1, 2, 3, 17]
a. [1, 2, 3, 17] and [1, 2, 3, 17]
a. [1, 2, 3] and [1, 2, 3]
a. None of these
80. While running an application, a user pressed the interrupt key (Ctrl + C). Which of the following exceptions will occur?
Answers:
a. InterruptError
a. KeyboardInterrupt
a. KeyboardInterruptError
a. None of these
81. Which of the following statements will redirect the output of the print statement into a file-like object named ‘test’?
Answers:
a. print >> open(‘test’,’w’), “Pi: %.3f” % 3.1415, 27+11
a. print ‘test’, “Pi: %.3f” % 3.1415, 27+11
a. print open(‘test’,’w’), “Pi: %.3f” % 3.1415, 27+11
a. print $$ open(‘test’,’w’), “Pi: %.3f” % 3.1415, 27+11
82. Read the following statements:
>>> word = ‘Help’ + ‘A’
>>> word[2:]
>>> word[2:]
Which of the following will be the output of the above code?
Answers:
a. lpA
a. He
a. pA
a. lp
83. What will be the output of the following statement:
Answers:
a. lpA
a. He
a. pA
a. lp
83. What will be the output of the following statement:
>>> “ab123”.islower(), ‘123’.islower(), ‘Ab123’.islower()
Answers:
a. (True,True,False)
a. (True,False,True)
a. (True,False,False)
a. (False,False,False)
84. Which of the following code samples will read arguments if the script is run from the command line?
Answers:
a. import argparse parser = argparse.ArgumentParser() print parser.arguments()
a. from optparse import OptionParser parser = OptionParser() print parser.arguments()
a. import sys print sys.argv
a. import os print os.argv
85. Divide by zero is a very common error. Which of the following handles this exception?
Answers:
a. DivideByZeroError
a. DivisionZeroError
a. ZeroDivisionError
a. DivisionError
86. Which option will import a module which is not in PYTHONPATH or the current directory?
Answers:
a. import
a. Add the path in program by sys.path.insert()
a. import *
a. Put __init__.py file in the module path and import it using the import statement
87. Which of the following is the correct way to output the name of any function (including builtin functions) using Python?
Answers:
a. theFunction.func_name
a. theFunction.__name__
a. theFunction.name()
a. theFunction.__func_name__
88. What is the best way to randomly select an item from list?
Answers:
a. foo = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’] from random import choice print choice(foo)
a. foo = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’] from random import randrange random_index = randrange(0,len(foo)) print foo[random_index]
a. foo = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’] import random print int(random.random() * len(foo))
a. foo = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’] import random print foo[int(random.random() * len(foo)+1)]
89. Which of the following snippets will return the list of all occurances of ‘b’ in
a = [‘a’,’b’,’c’,’b’] ?
Answers:
a. b = [item for item in a if a == ‘b’][0]
a. b = [item for item in a if a[] == ‘b’]
a. b = [item for item in a if ‘b’ in a]
a. b = [item for item in a if item == ‘b’]
90. Which of the following exceptions is raised while using sys.exit()?
Answers:
a. SysExit
a. SystemExit
a. Exit
a. ExceptExit
91. Which of the following code snippets converts the hexademical number 0x1000 to a decimal correctly?
Answers:
a. int(‘1000’, 16)
a. int(1000)
a. 1 * (16 ** 4) + 0 + 0 + 0
a. int.fromhex(‘0x1000’)
Answers:
a. (True,True,False)
a. (True,False,True)
a. (True,False,False)
a. (False,False,False)
84. Which of the following code samples will read arguments if the script is run from the command line?
Answers:
a. import argparse parser = argparse.ArgumentParser() print parser.arguments()
a. from optparse import OptionParser parser = OptionParser() print parser.arguments()
a. import sys print sys.argv
a. import os print os.argv
85. Divide by zero is a very common error. Which of the following handles this exception?
Answers:
a. DivideByZeroError
a. DivisionZeroError
a. ZeroDivisionError
a. DivisionError
86. Which option will import a module which is not in PYTHONPATH or the current directory?
Answers:
a. import
a. Add the path in program by sys.path.insert()
a. import *
a. Put __init__.py file in the module path and import it using the import statement
87. Which of the following is the correct way to output the name of any function (including builtin functions) using Python?
Answers:
a. theFunction.func_name
a. theFunction.__name__
a. theFunction.name()
a. theFunction.__func_name__
88. What is the best way to randomly select an item from list?
Answers:
a. foo = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’] from random import choice print choice(foo)
a. foo = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’] from random import randrange random_index = randrange(0,len(foo)) print foo[random_index]
a. foo = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’] import random print int(random.random() * len(foo))
a. foo = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’] import random print foo[int(random.random() * len(foo)+1)]
89. Which of the following snippets will return the list of all occurances of ‘b’ in
a = [‘a’,’b’,’c’,’b’] ?
Answers:
a. b = [item for item in a if a == ‘b’][0]
a. b = [item for item in a if a[] == ‘b’]
a. b = [item for item in a if ‘b’ in a]
a. b = [item for item in a if item == ‘b’]
90. Which of the following exceptions is raised while using sys.exit()?
Answers:
a. SysExit
a. SystemExit
a. Exit
a. ExceptExit
91. Which of the following code snippets converts the hexademical number 0x1000 to a decimal correctly?
Answers:
a. int(‘1000’, 16)
a. int(1000)
a. 1 * (16 ** 4) + 0 + 0 + 0
a. int.fromhex(‘0x1000’)
1. Which function could be used to list every file and folder in the current directory?
Answers:
• os.dirnames(‘.’)
• os.listdir(‘.’)
• os.listdir(‘/’)
• os.ls()
• os.listdir(‘.’)
• os.listdir(‘/’)
• os.ls()
2. Which of the following will be returned by readlines() method?
Answers:
• str
• a list of lines
• a list of single characters
• a list of integers
• a list of lines
• a list of single characters
• a list of integers
3. What function do you use to read a string?
Answers:
• input(«Enter a string»)
• eval(input(«Enter a string»))
• enter(«Enter a string»)
• print(enter(«Enter a string»))
• eval(input(«Enter a string»))
• enter(«Enter a string»)
• print(enter(«Enter a string»))
4. Which function do you use to read data using binary input?
Answers:
• write
• output
• dump
• send
• output
• dump
• send
5. Which of the following statements are true?
Note: There may be more than one right answer.
Answers:
• open a file for reading, if the file does not exist, an error occurs.
• open a file for writing, if the file does not exist, an error occurs.
• open a file for reading, if the file does not exist, the program will open an empty file.
• open a file for writing, if the file does not exist, a new file is created.
• open a file for writing, if the file exists, the existing file is overwritten with the new file.
• open a file for writing, if the file does not exist, an error occurs.
• open a file for reading, if the file does not exist, the program will open an empty file.
• open a file for writing, if the file does not exist, a new file is created.
• open a file for writing, if the file exists, the existing file is overwritten with the new file.
6. Which of the following is the correct way to change the current working directory in Python?
Answers:
• import os
os.chdir(«/path/to/change/to»)
• os.chdir(«/path/to/change/to»)
• chdir(«/path/to/change/to»)
• import os
os.cd(«/path/to/change/to»)
os.chdir(«/path/to/change/to»)
• os.chdir(«/path/to/change/to»)
• chdir(«/path/to/change/to»)
• import os
os.cd(«/path/to/change/to»)
7. Invoking the ___ method converts raw byte data to a string?
Answers:
• encode()
• decode()
• convertString()
• toString()
• decode()
• convertString()
• toString()
8. Which of the following exception raised for an error that doesn’t fall in any of the categories?
Answers:
• SyntaxError
• RuntimeError
• SystemError
• CodeError
• RuntimeError
• SystemError
• CodeError
9. Which is correct about getting a free port number?
Answers:
• use sock.getsockname() to get a free port number
• Do not bind to a specific port, or bind to port 0, e.g. sock.bind((», 0))
• Directly use a desired port number in bind function, e.g. sock.bind((», port_number))
• We cannot get a free port number
• Do not bind to a specific port, or bind to port 0, e.g. sock.bind((», 0))
• Directly use a desired port number in bind function, e.g. sock.bind((», port_number))
• We cannot get a free port number
10. Which of the following statements are true regarding __slots__ in Python?
Note: There may be more than one right answer.
Answers:
• __slots__ can be useful when many small object creations are needed, with predefined structures and with memory limitations.
• __slots__ is an optimized dynamic structure.
• __slots__ is a memory optimization tool.
• __slots__ breaks multiple inheritance.
• __slots__ is an optimized dynamic structure.
• __slots__ is a memory optimization tool.
• __slots__ breaks multiple inheritance.
11. 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:
• [‘one’, ‘two’, ‘three’, ‘four’]
[‘we’, ‘like’, ‘proper’, ‘English’]
[‘we’, ‘like’, ‘proper’, ‘English’]
• [‘one’, ‘two’, ‘three’, ‘four’]
[‘and’, ‘we’, ‘can’, ‘not’, ‘lie’]
[‘and’, ‘we’, ‘can’, ‘not’, ‘lie’]
• [‘one’, ‘two’, ‘three’]
[‘we’, ‘like’, ‘proper’, ‘English’]
[‘we’, ‘like’, ‘proper’, ‘English’]
• [‘one’, ‘two’, ‘three’]
[‘and’, ‘we’, ‘can’, ‘not’, ‘lie’]
[‘and’, ‘we’, ‘can’, ‘not’, ‘lie’]
12. The side option of the pack manager may be _____?
Note: There may be more than one right answer.
Answers:
• LEFT
• RIGHT
• BOTTOM
• TOP
• All of the above
• RIGHT
• BOTTOM
• TOP
• All of the above
13. How to get JSON to load into an OrderedDict in python?
Answers:
• By simply using json.loads(D) where D is Ordered dictionary
• By specifying the object_pairs_hook argument to JSONDecoder
• Ordered dictionary is not supported yet
• By simply using json.dumps(D) where D is Ordered dictionary
• By specifying the object_pairs_hook argument to JSONDecoder
• Ordered dictionary is not supported yet
• By simply using json.dumps(D) where D is Ordered dictionary
14. 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]
Note: There may be more than one right answer.
Answers:
• g = str(L).replace(‘[‘, »).replace(‘]’, »
flattenedList = [int(x) for x in g.split(‘,’) if x.strip()]
flattenedList = [int(x) for x in g.split(‘,’) if x.strip()]
• 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
for el in L:
if isinstance(el, collections.Iterable) and not isinstance(el, basestring):
for sub in flatten(el):
yield sub
else:
yield el
• 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
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
• 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)
def Flatten(L):
a = str(L)
b,crap = re.subn(r'[\[,\]]’, ‘ ‘, a)
c = b.split()
d = [int(x) for x in c]
return(d)
15. Which statement is true regarding the __all__ module level variable?
Answers:
• It is a list of strings defining all symbols in a module.
• It is a dictionary defining all functions in a module.
• It is a list of strings defining what symbols in a module will be exported when from <module> import * is used on the module.
• It is a dictionary defining what functions in a module will be exported when from <module> import * is used on the module.
• It is a dictionary defining all functions in a module.
• It is a list of strings defining what symbols in a module will be exported when from <module> import * is used on the module.
• It is a dictionary defining what functions in a module will be exported when from <module> import * is used on the module.
16. Regarding Secure hashes and message digests in Python 3 using standard module hashlib, which of the following is true ?
Answers:
• hashlib.sha224(b»test») will return the sha224 hash (as string) of the value «test».
• `hexdigest()` function will return a hexadecimal string representation of the underlying hash algorithm.
• Feeding string objects into update() is supported, as hashes work on both bytes and strings.
• `hexdigest()` function will return a hexadecimal string representation of the underlying hash algorithm.
• Feeding string objects into update() is supported, as hashes work on both bytes and strings.
17. Regarding Thread Synchronization Primitives in Python, which of the following is incorrect ?
Answers:
• 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.
• Reentrant Mutex Lock (`threading.RLock`) are similar to a normal mutex lock except that it can be reacquired multiple times by the same thread.
• 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.
• 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).
• Reentrant Mutex Lock (`threading.RLock`) are similar to a normal mutex lock except that it can be reacquired multiple times by the same thread.
• 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.
• 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).
18. Which method in the following is used to convert raw json objects to Json in python?
Answers:
• json.dumps()
• JSONEncoder().encode()
• json.loads()
• json.default()
• JSONEncoder().encode()
• json.loads()
• json.default()
19. 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:
• «is» always returns True if it compares the same object instance whereas the value returned by «==» is determined by the __eq__() method.
• «==» always returns True if it compares the same object instance whereas the value returned by «is» is determined by the __eq__() method.
• There is no difference between the two, but «==» is preferred by convention.
• There is no difference between the two, but «is» is preferred by convention.
• «==» always returns True if it compares the same object instance whereas the value returned by «is» is determined by the __eq__() method.
• There is no difference between the two, but «==» is preferred by convention.
• There is no difference between the two, but «is» is preferred by convention.
20. Which of the following environment variable for Python is an alternative module search path?
Answers:
• PYTHONCASEOK
• PYTHONHOME
• PYTHONSEARCH
• PYTHONURL
• PYTHONHOME
• PYTHONSEARCH
• PYTHONURL
21. Which of the following is the correct way to empty a list, using theList as an example?
Answers:
• del theList[] = []
• theList = []
• del theList[:]
• del theList[]
• theList = []
• del theList[:]
• del theList[]
22. sys.path is initialized from which of the following locations ?
Answers:
• The directory containing the input script .
• PYTHONPATH enviroment variable.
• The installation-dependent default.
• All of the above
• PYTHONPATH enviroment variable.
• The installation-dependent default.
• All of the above
23. Which of the following is true regarding urlopen function from the standard module urllib in Python 2?
Answers:
• Open a network object denoted by a URL for reading, but it cannot be used to open local files.
• If the connection cannot be made the LookupError exception is raised.
• If the connection is successful, this function returns the content of the object as string.
• When opening HTTPS URLs, it does not attempt to validate the server certificate.
• If the connection cannot be made the LookupError exception is raised.
• If the connection is successful, this function returns the content of the object as string.
• When opening HTTPS URLs, it does not attempt to validate the server certificate.
24. What is the type of inf?
Answers:
• Boolean
• Integer
• Float
• Complex
• Integer
• Float
• Complex
25. Which of the following data types is not supported in python ?
Answers:
• List
• Generics
• Numbers
• Tuple
• Generics
• Numbers
• Tuple
26. To add a new element to a list?
Answers:
• list.add(1)
• list.addValue(1)
• list.append(1)
• list.addItem(1)
• list.addValue(1)
• list.append(1)
• list.addItem(1)
27. Check whether an object x is an instance of class A, use _____.?
Answers:
• x.instance(A)
• A.instance(x)
• isinstance(x, A)
• instance(A, x)
• A.instance(x)
• isinstance(x, A)
• instance(A, x)
28. How to convert a json string to Python object?
Answers:
• simplejson.load()
• json.load()
• json.dumps()
• json.loads()
• json.load()
• json.dumps()
• json.loads()
29. Which of the following is the correct way to output the name of any function (including builtin functions) using Python?
Answers:
• theFunction.func_name
• theFunction.__name__
• theFunction.name()
• theFunction.__func_name__
• theFunction.__name__
• theFunction.name()
• theFunction.__func_name__
30. Which of the following is incorrect to say about CPython’s garbage collection mechanism ?
Answers:
• 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.
• 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.
• The garbage collector is a deterministic process, so that heuristics are never used to improve performance of garbage collection.
• All of the above are correct.
• 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.
• The garbage collector is a deterministic process, so that heuristics are never used to improve performance of garbage collection.
• All of the above are correct.
31. Which of the following statement is incorrect regarding Concurrency in Python?
Answers:
• A Thread can be defined by subclassing the `threading.Thread` and overriding the method `run()`
• A Thread instance is launched when the method `begin()` from `threading.Thread` is called.
• Once you start a Thread, it runs independently, and one can use `join()` to wait for a thread to exit
• 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.
• A Thread instance is launched when the method `begin()` from `threading.Thread` is called.
• Once you start a Thread, it runs independently, and one can use `join()` to wait for a thread to exit
• 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.
32. 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:
• a executed
[1]
a executed
[1, 1]
a executed
[1, 1, 1]
[1]
a executed
[1, 1]
a executed
[1, 1, 1]
• a executed
[5, 1]
[5, 1, 5, 1]
[5, 1, 5, 1, 5, 1]
[5, 1]
[5, 1, 5, 1]
[5, 1, 5, 1, 5, 1]
• a executed
[5, 1]
[5, 1]
[5, 1]
[5, 1]
[5, 1]
[5, 1]
• a executed
[5, 1]
a executed
[5, 1]
a executed
[5, 1]
[5, 1]
a executed
[5, 1]
a executed
[5, 1]
• a executed
[5, 1]
a executed
[5, 1, 5, 1]
a executed
[5, 1, 5, 1, 5, 1]
[5, 1]
a executed
[5, 1, 5, 1]
a executed
[5, 1, 5, 1, 5, 1]
33. The output of executing string.ascii_letters can also be achieved by ____?
Answers:
• string.letters.ascii
• string.ascii_lowercase+string.ascii_upercase
• string.ascii.letters
• string.ascii_lowercase+string.ascii_upercase
• string.ascii.letters
34. 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:
• If doWork() raise a TypeError, then the program will print ‘General exception’, as TypeError is subclass of Exception.
• 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.
• KeyboardInterrupt is the instance name for the exception class GeneratorExit. Therefore KeyboardInterrupt is never handled on this code.
• 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.
• 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.
• KeyboardInterrupt is the instance name for the exception class GeneratorExit. Therefore KeyboardInterrupt is never handled on this code.
• 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.
35. What will be the output of following code?
x, y = 15, 45
res = x if x < y else y
print(res)
Answers:
• 45
• 1
• Error
• 15
• 1
• Error
• 15
36. Which of the following statements are correct about assertions in Python?
Note: There may be more than one right answer.
Answers:
• Asserts are used to control program flow.
• The «assert» statements are removed when the compilation is optimized.
• Asserts should be used to test conditions that should never happen.
• Asserts are used to define custom exceptions that are to be caught.
• The «assert» statements are removed when the compilation is optimized.
• Asserts should be used to test conditions that should never happen.
• Asserts are used to define custom exceptions that are to be caught.
37. 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:
• This function takes the name of a directory and prints out the absolute paths for the files and sub-directories.
• 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.
• This function takes the name of a directory and prints out the paths for the files and sub-directories.
• This function will get stuck in the recursive calls and will eventually throw a runtime error.
• 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.
• This function takes the name of a directory and prints out the paths for the files and sub-directories.
• This function will get stuck in the recursive calls and will eventually throw a runtime error.
38. 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
4
9
16
25
4
9
16
25
• 64
64
64
64
64
64
64
64
64
• UnboundLocalError: local variable ‘x’ referenced before assignment
• 64
4
9
16
25
4
9
16
25
39. How can a list of dictionaries be sorted by the values of the dictionaries?
Answers:
• from operator import itemgetter
sortedlist = sorted(a_list_of_dicts, key = itemgetter(‘name’))
• import operator
sortedlist = a_list_of_dicts.sort(key = operator.itemgetter(‘name’))
• def mykey(adictionary):
return adictionary[‘name’]
sortedlist = sorted(a_list_of_dicts, key=mykey)
• sortedlist = a_list_of_dicts.sort(lambda x,y : cmp(x[‘name’], y[‘name’]))
sortedlist = sorted(a_list_of_dicts, key = itemgetter(‘name’))
• import operator
sortedlist = a_list_of_dicts.sort(key = operator.itemgetter(‘name’))
• def mykey(adictionary):
return adictionary[‘name’]
sortedlist = sorted(a_list_of_dicts, key=mykey)
• sortedlist = a_list_of_dicts.sort(lambda x,y : cmp(x[‘name’], y[‘name’]))
40. Which of the following statement is incorrect regarding Python language?
Answers:
• 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.
• 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.
• Python is well suited to object orientated programming in that it allows the definition of classes along with composition and inheritance.
• In Python, functions are not objects. This means that they cannot be assigned to variables, returned from other functions and passed into functions.
• 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.
• Python is well suited to object orientated programming in that it allows the definition of classes along with composition and inheritance.
• In Python, functions are not objects. This means that they cannot be assigned to variables, returned from other functions and passed into functions.
41. Which is not used to install Python packages?
Answers:
• easy_install
• pip
• distribute
• installtools
• pip
• distribute
• installtools
42. What is the correct way to delete a directory that is not empty using Python?
Answers:
• os.remove(‘/directory’)
• os.rmtree(‘/directory’)
• shutil.rmtree(‘/directory’)
• import shutil shutil.rmtree(‘/directory’)
• os.rmtree(‘/directory’)
• shutil.rmtree(‘/directory’)
• import shutil shutil.rmtree(‘/directory’)
43. Which of the following is false regarding urlretrieve function from the standard module urllib in Python 2?
Answers:
• It copies a network object denoted by a URL to a local file, if necessary.
• If the target URL points to a local file, or a valid cached copy of the object exists, the object is not copied.
• It returns a tuple (filename, headers, filesize) where filename is the local file name under which the object can be found.
• It’s possible to define a custom path for the local file, where the object will be saved.
• If the target URL points to a local file, or a valid cached copy of the object exists, the object is not copied.
• It returns a tuple (filename, headers, filesize) where filename is the local file name under which the object can be found.
• It’s possible to define a custom path for the local file, where the object will be saved.
44. Which of the following is the correct way to determine a variable’s type in Python?
Answers:
• type(variable_name)
• dir(variable_name)
• var(variable_name)
• typevar(variable_name)
• dir(variable_name)
• var(variable_name)
• typevar(variable_name)
45. 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:
• [[0, 0], [1, 1], [2, 4], [3, 9], [4, 16]]
• [{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}]
• [[1, 2, 3, 4, 9, 16]]
• [[0, 0], [1, 1], [2, 2], [3, 3], [4, 4]]
• [{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}]
• [[1, 2, 3, 4, 9, 16]]
• [[0, 0], [1, 1], [2, 2], [3, 3], [4, 4]]
46. What will be the output of following code?
items = set()
items.add(«google»)
items.add(«apple»)
items.add(«microsoft»)
print(items)
Answers:
• set([‘google’, ‘apple’, ‘microsoft’])
• set[‘google’, ‘apple’, ‘microsoft’]
• set(‘google’, ‘apple’, ‘microsoft’)
• set{‘google’, ‘apple’, ‘microsoft’}
• set[‘google’, ‘apple’, ‘microsoft’]
• set(‘google’, ‘apple’, ‘microsoft’)
• set{‘google’, ‘apple’, ‘microsoft’}
47. Regarding Unicode in Python 3, which of the following is incorrect ?
Answers:
• 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.
• One can create a string using the `decode()` method of `bytes` type, and it will use by default ‘latin_1’ encoding.
• Python 3 supports using Unicode characters in identifiers.
• One can create a byte representation from a string by using the `encode()` method, and it will use by default ‘utf-8’ encoding.
• One can create a string using the `decode()` method of `bytes` type, and it will use by default ‘latin_1’ encoding.
• Python 3 supports using Unicode characters in identifiers.
• One can create a byte representation from a string by using the `encode()` method, and it will use by default ‘utf-8’ encoding.
48. Which of the following is the best way of checking if a string could be represented as a number?
Answers:
• def is_number(s):
try:
float(s)
return True
except ValueError:
return False
try:
float(s)
return True
except ValueError:
return False
• import re
check_regexp = re.compile(«^\d*\.?\d*$»)
check_regexp = re.compile(«^\d*\.?\d*$»)
• def isNumber(token):
for char in token:
if not char in string.digits: return False
return True
for char in token:
if not char in string.digits: return False
return True
• import re
check_replace = lambda x: x.replace(‘.’,»,1).isdigit()
check_replace = lambda x: x.replace(‘.’,»,1).isdigit()
49. Which of the following can be used to create a directory?
Answers:
• os.make_dir()
• os.create_dir()
• os.mkdir()
• All of the above
• os.create_dir()
• os.mkdir()
• All of the above
50. 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:
• [10]
[]
[4]
[5]
[]
[4]
[5]
• [10]
[10]
[4]
[5]
[10]
[4]
[5]
• [10]
[[10]]
[5]
[5]
[[10]]
[5]
[5]
• [10]
[None]
[5]
[4]
[None]
[5]
[4]
51. 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, 3, 7, 10, 13, 16, 19]
• [1, 6, 9, 11, 15, 17, 19]
• [1, 5, 7, 11, 13, 17, 19]
• [1, 4, 7, 12, 15, 17, 19]
• [1, 6, 9, 11, 15, 17, 19]
• [1, 5, 7, 11, 13, 17, 19]
• [1, 4, 7, 12, 15, 17, 19]
52. What are the states/features supported by a RLock object?
Answers:
• Locked
• Owning thread
• Recursion level
• Unlocked
• All of the above
• Owning thread
• Recursion level
• Unlocked
• All of the above
53. Which of the following is incorrect regarding modules in Python?
Answers:
• Each module can only be imported once per interpreter session. And If you change a module the interpreter will automatically reload it for you.
• The interpreter searches for a module first at the directory of the top-level file, i.e. the file being executed.
• `dir(__builtins__)` will return a list of all built-in functions, exceptions, and other objects.
• It’s possible to put several modules into a Package. A directory of Python code is said to be a package.
• The interpreter searches for a module first at the directory of the top-level file, i.e. the file being executed.
• `dir(__builtins__)` will return a list of all built-in functions, exceptions, and other objects.
• It’s possible to put several modules into a Package. A directory of Python code is said to be a package.
54. Which of the following is the best method for accessing the index of a list while executing in a loop?
Answers:
• for i in range(len(sequence)):
print i
• for i,e in enumerate(sequence):
print i
• for i, e in zip(range(len(sequence)), sequence):
print i
• for i in xange(len(sequence)):
print i
print i
• for i,e in enumerate(sequence):
print i
• for i, e in zip(range(len(sequence)), sequence):
print i
• for i in xange(len(sequence)):
print i
55. 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:
• [0, 1, 4]
• [0, 1, 0, 1, 4]
• [0, 1, 0]
• [3, 2, 1, 0, 1, 4]
• [0, 1, 0, 1, 4]
• [0, 1, 0]
• [3, 2, 1, 0, 1, 4]
56. What is the correct way to increment the value of the variable «i» by 1?
Answers:
• i += 1
• i++
• ++i
• inc(i)
• i++
• ++i
• inc(i)
57. 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:
• Class B inherits A, but the data field i in A is not inherited.
• Class B inherits A and automatically inherits all data fields in A.
• When you create an object B, you have to pass an integer such as B(5).
• The data field j cannot be accessed by object b.
• Class B inherits A and automatically inherits all data fields in A.
• When you create an object B, you have to pass an integer such as B(5).
• The data field j cannot be accessed by object b.
58. Which option in sqllite.connect() method avoids OperationalError telling that the database file is locked?
Answers:
• check_same_thread
• check_thread
• check_diff_thread
• check_same_threads
• check_thread
• check_diff_thread
• check_same_threads
59. The __ function can be used to check if a file f exists?
Answers:
• os.path.isFile(f)
• os.path.exists(f)
• os.path.isfile(f)
• os.isFile(f)
• os.path.exists(f)
• os.path.isfile(f)
• os.isFile(f)
60. What will be the output of following code?
print «\x48\x49!»
Answers:
• HI!
• 48 49!
• 4849!
• \x48\x49!
• 4849
• 48 49!
• 4849!
• \x48\x49!
• 4849
61. Considering the following code snippet:-
def test (a, b, c): pass
Which of the following is a true statement?
Answers:
• It defines a function that will automatically pass to other function the three parameters it receives.
• It defines a function that essentially does nothing.
• It defines an empty class.
• It’s a native Python function that tests if any of the parameters evaluates to `True`.
• It defines a function that essentially does nothing.
• It defines an empty class.
• It’s a native Python function that tests if any of the parameters evaluates to `True`.
62. In Python, a string literal is enclosed in _____? (check all that apply)
Note: There may be more than one right answer.
Answers:
• parentheses
• brackets
• single-quotes
• double-quotes
• brackets
• single-quotes
• double-quotes
63. Which of the following is the correct way to print to stderr in Python?
Answers:
• sys.stderr.write(‘my_error’)
• print >> sys.stderr, ‘my_error’
• from __future__ import print_function
print(‘my_error’, file=sys.stderr)
• All of these
• print >> sys.stderr, ‘my_error’
• from __future__ import print_function
print(‘my_error’, file=sys.stderr)
• All of these
64. In Python 3, which of the following is correct regarding data types Lists, Tuples, Dictionaries and Sets ?
Answers:
• `add()` from a Dictionary object will add a new key-value pair to the end of the collection.
• If `a_set` is a Set instance, then `a_set.difference(a_set)` will always return an empty Set object.
• To add a new object to the end of a Tuple, one can use the method `append()`.
• List objects do not have a `pop()` method as this is typical of Stack data type.
• If `a_set` is a Set instance, then `a_set.difference(a_set)` will always return an empty Set object.
• To add a new object to the end of a Tuple, one can use the method `append()`.
• List objects do not have a `pop()` method as this is typical of Stack data type.
65. Which of the following will be the output of the below code snippet?
def foo(x=[]):
x.append(1)
print(x)
foo()
foo()
foo()
Answers:
• [1, 1]
[1, 1]
[1, 1]
[1, 1]
[1, 1]
• [1, 1, 1]
[1, 1, 1]
[1, 1, 1]
[1, 1, 1]
[1, 1, 1]
• [1]
[1]
[1]
[1]
[1]
• [1]
[1, 1]
[1, 1, 1]
[1, 1]
[1, 1, 1]
66. Which of the following is the correct way to flush output of Python print?
Answers:
• import sys sys.stdout.flush()
• 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)
• import sys sys.stdout = os.fdopen(sys.stdout.fileno(), ‘w’, 0)
• Running python with the -u command-line switch
• 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)
• import sys sys.stdout = os.fdopen(sys.stdout.fileno(), ‘w’, 0)
• Running python with the -u command-line switch
67. A hashing function ____?
Answers:
• stores an element in the hash table
• maps a key to an index in the hash table
• different index in the hash table
• maps a key to an index in the hash table
• different index in the hash table
68. What is the method to retrieve the list of all active thread objects?
Answers:
• activethreads()
• getThreads()
• enumerate()
• threads()
• getThreads()
• enumerate()
• threads()
69. _____ measures how full the hash table is?
Answers:
• Load factor
• Threshold
• Dump
• Tuple
• Threshold
• Dump
• Tuple
70. 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:
• 10
11
• 10
9
• UnboundLocalError: local variable ‘x’ referenced before assignment
• 9
9
11
• 10
9
• UnboundLocalError: local variable ‘x’ referenced before assignment
• 9
9
71. Which is the correct syntax for Python dictionary comprehension?
Answers:
• (dict in dict for sequence)
• dict((key, value) for dict in sequence)
• dict((key, value) for dict(key) in sequence)
• dict((key, value) for (key, value) in sequence)
• dict((key, value) for dict in sequence)
• dict((key, value) for dict(key) in sequence)
• dict((key, value) for (key, value) in sequence)
72. Which user input method will act like a file-object on which read and readline functions can be called?
Answers:
• sys.stdin
• raw_input()
• input()
• sys.argv
• raw_input()
• input()
• sys.argv
73. 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:
• 0
• 1
• 2
• 3
• 1
• 2
• 3
74. What is the best way to randomly select an item from list?
Answers:
• foo = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’]
from random import choice
print choice(foo)
• foo = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’]
from random import randrange
random_index = randrange(0,len(foo))
print foo[random_index]
• foo = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’]
import random
print int(random.random() * len(foo))
• foo = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’]
import random
print foo[int(random.random() * len(foo)+1)]
from random import choice
print choice(foo)
• foo = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’]
from random import randrange
random_index = randrange(0,len(foo))
print foo[random_index]
• foo = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’]
import random
print int(random.random() * len(foo))
• foo = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’]
import random
print foo[int(random.random() * len(foo)+1)]
75. Which code snippet below will not return True?
Answers:
• 1 in [1,0]
• 1 in [1,0] == True
• (1 in [1,0]) == True
• 1 in [1, 2, 3]
• 1 in [1,0] == True
• (1 in [1,0]) == True
• 1 in [1, 2, 3]
76. 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:
• It will raise an exception.
• 1
• 0
• It will randomly print a different value on every run.
• 1
• 0
• It will randomly print a different value on every run.
77. Which of the following are the characteristics of the __init__.py file?
Note: There may be more than one right answer.
Answers:
• __init__.py can be an empty file, but it can also execute initialization code for the package or set the __all__ variable.
• The __init__.py files are used to override the classes’ initializations globally.
• The __init__.py files are required to make Python treat the directories as if they contain packages.
• The __init__.py files are used to define the classes’ basic initializations.
• The __init__.py files are used to override the classes’ initializations globally.
• The __init__.py files are required to make Python treat the directories as if they contain packages.
• The __init__.py files are used to define the classes’ basic initializations.
78. 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:
• 7
• 12
• 24
• 36
• 48
• 12
• 24
• 36
• 48
79. What is the output of the following?
t=(1,2,4,3,5)
t[1:3]
Answers:
• (1, 4)
• (1, 4, 3)
• (2, 4)
• (2, 4, 3)
• (1, 4, 3)
• (2, 4)
• (2, 4, 3)
80. What is the output of «Dummy Text is my text».strip(‘Te’) —
Answers:
• ‘Dummy Text is my text’
• ‘Dummy xt is my xt’
• ‘Dummy xt is my text’
• None of these
• ‘Dummy xt is my xt’
• ‘Dummy xt is my text’
• None of these
81. 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:
• 64.0
• 43
• 4.0
• 3.0
• 43
• 4.0
• 3.0
82. 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:
• first_call
normal_call
normal_call
• first_call
first_call
first_call
• normal_call
normal_call
normal_call
• first_call
normal_call
first_call
normal_call
normal_call
• first_call
first_call
first_call
• normal_call
normal_call
normal_call
• first_call
normal_call
first_call
83. What command is used to get the hostname of the computer the Python script is running on?
Answers:
• print hostname()
• import socket
print gethostname()
• print socket.gethostname()
• import socket
print socket.gethostname()
• import socket
print gethostname()
• print socket.gethostname()
• import socket
print socket.gethostname()
84. Which of the following is used to get the name of a thread?
Answers:
• getName()
• getthread()
• getThread()
• get_id()
• getthread()
• getThread()
• get_id()
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?
Answers:
• 6
• 1
• 2
• 10
• None
• 1
• 2
• 10
• None
86. Which of the following will clone a list in Python? (choose all that apply)
Note: There may be more than one right answer.
Answers:
• new_list = old_list[:]
• new_list = list(old_list)
• import copy
new_list = copy.copy(old_list)
• import copy
new_list = copy.deepcopy(old_list)
• new_list = list(old_list)
• import copy
new_list = copy.copy(old_list)
• import copy
new_list = copy.deepcopy(old_list)
87. On a Unix-like system, what does Python’s sleep.time() function block?
Answers:
• The thread.
• The process.
• Nothing.
• It always blocks both.
• The process.
• Nothing.
• It always blocks both.
88. From the following which is not a good recommendation for Threading in Python?
Answers:
• Use multitasking module
• use Queue.Queue
• Use an event model, such as Twisted
• Use the threading module
• use Queue.Queue
• Use an event model, such as Twisted
• Use the threading module
89. Which piece of code best describes the way to parse data from JSON file?
Answers:
• import json
from pprint import pprint
with open(‘data.json’) as data_file:
data = json.load(data_file)
pprint(data)
from pprint import pprint
with open(‘data.json’) as data_file:
data = json.load(data_file)
pprint(data)
• import json
from pprint import pprint
json_data=open(‘json_data’)
data = json.load(json_data)
pprint(data)
from pprint import pprint
json_data=open(‘json_data’)
data = json.load(json_data)
pprint(data)
• data = []
with codecs.open(‘d:\output.txt’,’rU’,’utf-8′) as f:
for line in f:
data.append(json.loads(line))
with codecs.open(‘d:\output.txt’,’rU’,’utf-8′) as f:
for line in f:
data.append(json.loads(line))
• None of the above
90. 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:
• 8
• 12
• 10
• 6
• 12
• 10
• 6
91. 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:
• b = filter(lambda x: x % 2 == 0, a)
• b = [x for x in a if x % 2 == 0]
• def filterfunc(x):
return x % 2 == 0
b = filter(filterfunc, a)
• All of these
• b = [x for x in a if x % 2 == 0]
• def filterfunc(x):
return x % 2 == 0
b = filter(filterfunc, a)
• All of these
92. Which of the following code snippets converts the hexademical number 0x1000 to a decimal correctly?
Answers:
• int(‘1000’, 16)
• int(1000)
• 1 * (16 ** 4) + 0 + 0 + 0
• int.fromhex(‘0x1000’)
• int(1000)
• 1 * (16 ** 4) + 0 + 0 + 0
• int.fromhex(‘0x1000’)
93. Which of the function immediately terminates the program?
Answers:
• sys.stop()
• sys.close()
• sys.exit()
• sys.terminate()
• sys.close()
• sys.exit()
• sys.terminate()
94. Which of the following is the proper way to declare custom exceptions in modern Python?
Answers:
• class MyException(Exception):
pass
• class MyException():
pass
• class MyException(Error):
pass
• class MyException:
pass
pass
• class MyException():
pass
• class MyException(Error):
pass
• class MyException:
pass
95. 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:
• True
• False
• None
• It raises AttributeError: object has no attribute ‘closed’
• False
• None
• It raises AttributeError: object has no attribute ‘closed’
96. 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:
• 12345
• 1234
• 01234
• 6
• 1234
• 01234
• 6
97. What is the result of the following code:
listOne = [1, 3, 5]
listTwo = [2, 4, 6]
listNew = listOne + listTwo
print listNew
Answers:
• [3, 7, 11]
• [1, 2, 3, 4, 5, 6]
• [1, 3, 5, 2, 4, 6]
• [ [1, 3, 5], [2, 4, 6] ]
• [1, 2, 3, 4, 5, 6]
• [1, 3, 5, 2, 4, 6]
• [ [1, 3, 5], [2, 4, 6] ]
98. Regarding the code below, what’s correct statement ?
class Book:
def __init__(self, isbn):
self.isbn = isbn
isbn = ‘test’
book = Book(12345)
Answers:
• book.isbn will contain the value 12345.
• book.isbn will contain the value ‘test’.
• This program won’t run the Book class expects a string instead of integer.
• None of the above is correct.
• book.isbn will contain the value ‘test’.
• This program won’t run the Book class expects a string instead of integer.
• None of the above is correct.
99. hat will be the output of the code below?
s = ‘messha’
for i in range(len(s)):
print(i)
Answers:
• m e s s h a
• 0 1 2 3 4 5
• 6
• 5
• 0 1 2 3 4 5
• 6
• 5
100. Which of the following will remove duplicate elements from a list (O(n)), whilst preserving order?
Answers:
• mylist = [x for i,x in enumerate(mylist) if x not in mylist[i+1:]]
• mylist = reduce(lambda x, y: x if y in x else x + [y], mylist, [])
• seen = set()
seen_add = seen.add
mylist = [ x for x in mylist if x not in seen and not seen_add(x)]
• mylist = [x for i,x in enumerate(mylist) if x not in mylist[:i]]
• mylist = reduce(lambda x, y: x if y in x else x + [y], mylist, [])
• seen = set()
seen_add = seen.add
mylist = [ x for x in mylist if x not in seen and not seen_add(x)]
• mylist = [x for i,x in enumerate(mylist) if x not in mylist[:i]]
101. Consider the following Python code:
test = 1/2
What is the value of ‘test’ in Python 2.7 and 3.5, respectively ?
Answers:
• 0 and 1
• 0 and 0.5
• 0.5 and 0
• 1 and 0
• 0 and 0.5
• 0.5 and 0
• 1 and 0
102. Which of the following is the correct method for changing a global variable inside a function?
Answers:
• def change_globvar():
globvar = 1
globvar = 1
• def change_globvar():
global globvar
globvar = 1
global globvar
globvar = 1
• def change_globvar():
import globvar
globvar = 1
import globvar
globvar = 1
• def change_globvar():
global globvar = 1
global globvar = 1
103. Which one of these answers will catch an exception, but do nothing with it?
Answers:
• doSomething()
• try:
doSomething()
• try:
doSomething()
except:
• try:
doSomething()
except:
pass
• try:
doSomething()
• try:
doSomething()
except:
• try:
doSomething()
except:
pass
104. Suppose we have a User class, how do we make a new User object?
Answers:
• a = new User()
• User a = new User()
• User.new(Object)
• a = User()
• User a = new User()
• User.new(Object)
• a = User()
105. What will be the output of the following?
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, 3, 5, 6, 9]
• [1, 5, 7, 9, 10]
• [2, 4, 6, 8, 10]
• [0, 4, 6, 8, 10]
• [1, 5, 7, 9, 10]
• [2, 4, 6, 8, 10]
• [0, 4, 6, 8, 10]
106. Which of the following one is reentrant lock type?
Answers:
• RLock
• UnLock
• Lock
• Condition
• UnLock
• Lock
• Condition
107. 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:
• z = dict(x.items() + y.items())
• z = x.copy()
z.update(y)
• z = dict(x, **y)
• z = x.update(y)
• z = dict(list(x.items()) + list(y.items()))
• z = x.copy()
z.update(y)
• z = dict(x, **y)
• z = x.update(y)
• z = dict(list(x.items()) + list(y.items()))
108. How can an element be removed from a list using its list index?
Answers:
• myList.remove(index)
• pop myList[index]
• del myList[index]
• myList.delete(index)
• pop myList[index]
• del myList[index]
• myList.delete(index)
109. Which of the following is NOT correct regarding unittest in Python 3?
Answers:
• Each test case must be defined inside a class that inherits from unittest.TestCase
• @unittest.skip is a decorator designed to disable the specific test unit from running.
• setUp() from unittest.TestCase can be overridden and is called immediately before calling the test method.
• tearDown() from unittest.TestCase is called only once per class, immediately before the first test method.
• @unittest.skip is a decorator designed to disable the specific test unit from running.
• setUp() from unittest.TestCase can be overridden and is called immediately before calling the test method.
• tearDown() from unittest.TestCase is called only once per class, immediately before the first test method.
110. Which of the following would create an instance of Firm class correctly?
Answers:
• Firm = Firm(‘client’, 2000)
• Firm = Firm()
• Firm = Firm(‘server’, 2000)
• None of the above
• Firm = Firm()
• Firm = Firm(‘server’, 2000)
• None of the above
111. 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:
• Result: 1
• Result: 2
• Result: 3
• Result: 0
• Result: 2
• Result: 3
• Result: 0
112. Which of the following will throw an exception in Python?
Answers:
• call Exception(«Here is an Exception!»)
• throw Exception(«Here is an Exception!»)
• raise Exception(«Here is an Exception!»)
• create Exception(«Here is an Exception!»)
• throw Exception(«Here is an Exception!»)
• raise Exception(«Here is an Exception!»)
• create Exception(«Here is an Exception!»)
113. What is the output of the following code?
class A(object):
def __init__(self):
print «Constructor A was called»
class B(A):
def __init__(self):
print «Constructor B was called»
class C(B):
def __init__(self):
super(C,self).__init__()
print «Constructor C was called»
class D(C):
def __init__(self):
super(D,self).__init__()
print «Constructor D was called»
Answers:
• Constructor D was called
• Constructor A was called
Constructor B was called
Constructor C was called
Constructor D was called
Constructor B was called
Constructor C was called
Constructor D was called
• Constructor B was called
Constructor C was called
Constructor D was called
Constructor C was called
Constructor D was called
• Constructor B was called
114. In Python 3, which of the following is incorrect regarding data structures ?
Answers:
• Lists are ordered collections that can hold arbitrary objects and can expand dynamically as new items are added.
• Tuples are ordered collections that can hold arbitrary objects, but are immutable.
• A set is an unordered collection of unique values and support standard Set operations such as union, intersection, and difference.
• A Dictionary is an unordered set of key-value pairs, but becomes essentially immutable once a key already exists.
• Tuples are ordered collections that can hold arbitrary objects, but are immutable.
• A set is an unordered collection of unique values and support standard Set operations such as union, intersection, and difference.
• A Dictionary is an unordered set of key-value pairs, but becomes essentially immutable once a key already exists.
115. What is the correct syntax that will set the variable «var1» to the value «correct» if variable «a» is greater than 1?
Answers:
• var1 = «correct» if a > 1
• var1 = «correct» if a > 1 else None
• var1 = «correct» if a > 1 else if None
• var1 = «correct» if a > 1 else
• var1 = «correct» if a > 1 else None
• var1 = «correct» if a > 1 else if None
• var1 = «correct» if a > 1 else
116. What will be the output of following code?
counter = 1
def count():
global counter
t = (1, 2, 3)
for i, v in enumerate(t):
counter += i + v
count()
print counter
Answers:
• 9
• 10
• 11
• 12
• 13
• 10
• 11
• 12
• 13
117. 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:
• assert isinstance(x, basestring)
• assert not isinstance(x, basestring)
• assert not instance(x, basestring)
• assert not x.isinstance(basestring)
• assert not isinstance(x, basestring)
• assert not instance(x, basestring)
• assert not x.isinstance(basestring)
118. What is the type of x?
x = 10.0//5
Answers:
• int
• float
• long
• number
• float
• long
• number
119. 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, ‘\t’, 2, ‘\t’, 3)
• (2, ‘\t’, 1, ‘\t’, 3)
• (1, ‘\t’, 3, ‘\t’, 2)
• (3, ‘\t’, 1, ‘\t’, 2)
• (2, ‘\t’, 1, ‘\t’, 3)
• (1, ‘\t’, 3, ‘\t’, 2)
• (3, ‘\t’, 1, ‘\t’, 2)
120. 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:
• AttributeError will be raised.
• None None
• None 5
• 5 None
• 5 5
• None None
• None 5
• 5 None
• 5 5
121. Which of the following snippets will return the list of all occurances of ‘b’ in
a = [‘a’,’b’,’c’,’b’] ?
Answers:
• b = [item for item in a if a == ‘b’][0]
• b = [item for item in a if a[] == ‘b’]
• b = [item for item in a if ‘b’ in a]
• b = [item for item in a if item == ‘b’]
• b = [item for item in a if a[] == ‘b’]
• b = [item for item in a if ‘b’ in a]
• b = [item for item in a if item == ‘b’]
Comments
Post a Comment