Хотите пройти тесты на Upwork на хороший результат?
Подавайте заявку и мы поможем Вам это сделать!

Do You want to pass tests on Upwork with good scores?
Leave the request and we will help You to do that!

Python Test 2017

Share on RedditPin on PinterestEmail this to someoneShare on TumblrShare on LinkedInShare on Google+Tweet about this on TwitterShare on FacebookShare on VK

Мы не гарантируем правильность всех предоставленных ответов.


121 Test Questions:

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()

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

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»))

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

Answers:

• write
• 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.

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»)

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

Answers:

• encode()
• 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

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

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.

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’]

• [‘one’, ‘two’, ‘three’, ‘four’]
[‘and’, ‘we’, ‘can’, ‘not’, ‘lie’]

• [‘one’, ‘two’, ‘three’]
[‘we’, ‘like’, ‘proper’, ‘English’]

• [‘one’, ‘two’, ‘three’]
[‘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

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

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()]

• 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

• 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

• 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)

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.

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.

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).

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()

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.

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

Answers:

• PYTHONCASEOK
• 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[]

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

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.

24. What is the type of inf?

Answers:

• Boolean
• Integer
• Float
• Complex

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

Answers:

• List
• 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)

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)

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

Answers:

• simplejson.load()
• 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__

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.

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.

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]

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

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

• a executed
[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]

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

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.

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

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.

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.

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

• 64
64
64
64
64

• UnboundLocalError: local variable ‘x’ referenced before assignment

• 64
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’]))

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.

41. Which is not used to install Python packages?

Answers:

• easy_install
• 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’)

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.

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)

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]]

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’}

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.

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

• import re
check_regexp = re.compile(«^\d*\.?\d*$»)

• def isNumber(token):
for char in token:
if not char in string.digits: return False
return True

• import re
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

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]

• [10]
[10]
[4]
[5]

• [10]
[[10]]
[5]
[5]

• [10]
[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]

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

Answers:

• Locked
• 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.

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

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]

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

Answers:

• i += 1
• 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.

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

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)

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

Answers:

• HI!
• 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`.

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

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

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.

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]

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

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

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

Answers:

• activethreads()
• getThreads()
• enumerate()
• threads()

69. _____ measures how full the hash table is?

Answers:

• Load factor
• 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

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)

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

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

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)]

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]

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.

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.

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

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)

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

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

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

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()

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

Answers:

• getName()
• 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

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)

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

Answers:

• The thread.
• 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

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)

• import json
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))

• 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

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

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’)

93. Which of the function immediately terminates the program?

Answers:

• sys.stop()
• 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

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’

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

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] ]

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.

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

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]]

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

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

Answers:

• def change_globvar():
globvar = 1

• def change_globvar():
global globvar
globvar = 1

• def change_globvar():
import globvar
globvar = 1

• def change_globvar():
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

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()

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]

106. Which of the following one is reentrant lock type?

Answers:

• RLock
• 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()))

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)

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.

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

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

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!»)

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

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.

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

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

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)

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

Answers:

• int
• 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)

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

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’]

  • Ilya Paskhover

    Only 31 first questions have answers. «Great» work…
    What is the price of all answers?

    • Upworktestru

      Leave request on our website and we will write you the price and results of this test

    • hi bro. if u have python question. please send me. on my email. furqanlatif200@gmail.com