Test answers for Python 2015 Elance


Test answers for Python 2015

Elance • IT & Programming

1. What is a correct term for the following piece of Python syntax: 3 + 4
Answers:
• A suite.
• A lambda.
• A closure.
• An expression.
• A statement.

2. What will the following print?  a = [1,2,3] b = a a[-2] = 0 print(b)
Answers:
• [1,2,3]
• [1,0,3]
• [1,2,0]
• [0,2,3]


3. What is a 'docstring'?
Answers:
• Any string literal in python code is often referred to as a 'docstring'.
• A library that's used to automatically generate documentation from function definitions.
• Documentation found on python's official websites and tutorials describing parts of the standard library.
• A string literal that occurs as the first statement in a module, function, class, or method definition that serves to describe it's function.
4. After executing the following statements, what is the value of var?  var = "dlrow olleh" var = var[::-1]
Answers:
• The interpreter will crash
• 'hello world'
• "dlrow olle"
• Syntax Error
5. If you want to enter accented characters, what is put in front of the string the character?
Answers:
• G
• d
• g
• u
6. What is the type of the expression [" "]?
Answers:
• list
• array
• tuple
• string
7. What function is used to convert integer numbers to floats?
Answers:
• floatize
• int2float
• int_to_float
• float
8. What is the type of the expression (' ', )?
Answers:
• string
• This expression will result in a syntax error.
• tuple
• integer
9. What does Python use type declarations for?
Answers:
• strings
• Python does not have type declarations
• structures
• numbers
10. PEP8 style guidelines include:
Answers:
• All of these
• CapWords for class names, lowercase for function names
• Limit all lines to a maximum of 79 characters
• Don't use spaces around the '=' sign when used to indicate a keyword argument or a default parameter value
• Use 4 spaces per indentation level
11. PEP8 provides:
Answers:
• A style guide for writing Python Programs
• The deprecation of Python modules
• Instructions on how to Introduce New PEP's
12. Which method of file objects will return the next line?
Answers:
• read
• readline
• get
• echo
13. When is the function __init__ called?
Answers:
• When an instance of a class is destroyed.
• At a program's end.
• When an instance of a class is created.
• At a program's start.
14. How can you open text file "wilma" for reading in Python 2.x?
Answers:
• open('wilma', 'r')
• fopen("wilma", "rb");
• open 'wilma', 'rb'
• fopen 'wilma', 'r'
15. What is a regular expression?
Answers:
• A set of programming language expressions that are used by a programmer on a regular basis.
• Any correct expression that is possible in Python.
• A tool for matching strings of text, such as particular characters, words, or patterns of characters.
• An algorithm for quick retrieval of data from Python dictionaries.
16. What keywords are used in Python's assignment statements?
Answers:
• There are no keywords in assignment statements.
• let
• assume
• assign
17. Which of the following is not a supported compression format provided by the standard library?
Answers:
• zip
• bzip
• lzma
• gzip
18. Which of the following is NOT a valid part of an "if" block?
Answers:
• if:
• elseif:
• elif:
• else:
19. How are the results of '12 ** 3' and 'pow(12,3)' related?
Answers:
• The second expression will produce a NameError exception.
• The first expression will produce a SyntaxError exception.
• They are equivalent.
• They are different.
20. What function do you use to determine the size of a tuple, a list, or a string?
Answers:
• size
• length
• len
• Tuplen for tuples, listlen for lists, strlen for strings
21. What will typing the following at the Python interpreter produce? [3]*3
Answers:
• '333'
• [9]
• [3, 3, 3]
• '9'
22. Which of these will result in an error?
Answers:
• "hello" + "hello"
• len ( "hello" )
• "hello" * 2
• "hello" ** 2
23. True or False: Python holds the current working directory in memory.
Answers:
• True
• False
24. When opening the Python shell, the prompt you see is
Answers:
• >>>
• $
• #
• >
25. What does the sys module include?
Answers:
• The name of the operating system where your Python code is run.
• All are correct.
• The Python interpreter's version number.
• The largest integer the machine's architecture supports.
26. What keyword is needed to use an external module?
Answers:
• external
• use
• package
• import
27. If you want a function you define to return "a",  what should be put on the last line of the function (correctly indented)?
Answers:
• ret("a")
• a
• "a"
• return "a"
28. What data type is the following: [1, 2, 3] ?
Answers:
• Counter.
• Set.
• Tuple.
• Dictionary.
• List.
29. Which of these values equates to True?
Answers:
• {}
• ()
• ""
• None of these
30. What is a variable?
Answers:
• A collection of elements, each identified by an index
• An object containing data whose value cannot be altered by the program
• An object which may contain some data
• A statement which allows you to choose one variant from a given set
31. It is possible to create a while loop that will never stop?
Answers:
• No
• Yes
32. What does the print statement do?
Answers:
• Evaluates its parameters and writes the resulting objects to standard output.
• Prints the source code on the default printer.
• Allows users to input data.
• Returns the status of all printers installed on the network.
33. Is it possible to call a function from within another function?
Answers:
• Yes.
• Yes, but only when the program runs on a remote server.
• Yes, but only in the interactive shell.
• No.
34. How does one print the string "fred" on a line by itself in Python 2.x?
Answers:
• print 'fred'
• println('fred')
• write('fred')
• cout << "fred" << endl;
35. Which Python implementation is best for testing Java code?
Answers:
• Jython
• CPython
• IronPython
• PyPy
36. What will be the value of a variable x after executing the expression x = y = 1?
Answers:
• 0
• Undefined
• This expression will result in a syntax error.
• 1
37. What keyword is used to define a function?
Answers:
• function
• define
• def
• None of these
• sub
38. What kind of type system does Python have?
Answers:
• Loading.
• Proportional.
• Inverse.
• Static.
• Dynamic.
39. What is the purpose of an 'if' statement?
Answers:
• Repeatedly execute a block of code
• Conditionally execute a block of code
• Execute code from more than one place in a program
40. What will be printed as the result of: animals = ['bear', 'tiger', 'penguin', 'zebra'] print animals[2] ?
Answers:
• penguin
• zebra
• bear
• tiger
41. Python files typically have which extension?
Answers:
• py
• pl
• pie
• pt
• pil
42. What keyword is used to define a function?
Answers:
• def
• func
• proc
• sub
43. What is the index of the first item in a tuple or list?
Answers:
• -1
• 1
• 0
• -2,147,483,648
44. Python variables are references to objects.
Answers:
• Always
• Never
45. What character is used to denote the beginning of a comment?
Answers:
• #
• //
• {
• /*
46. Functions are first-class objects in Python.
Answers:
• Never
• Always
47. Which of the following data structures supports the 'in' operator: list, dictionary, set ?
Answers:
• None.
• All three.
• dictionary
• list
• set
48. What will be returned when the following command is run: print 5 <= -2 ?
Answers:
• True
• False
• '5 <= -2'
• 3
49. When defining a class, what controls which parameters that may be passed when the class is instantiated?
Answers:
• There is no way to pass parameters to a class instance.
• Writing the desired values after the class name when the class instance is created.
• Specifying those parameters after the class name.
• Specifying those parameters in the definition of an __init__ method of the class.
50. What does the expression string1 + string2 do?
Answers:
• Concatenates string1 and string2.
• Repeats string1 string2 times (string2 must be in numeric format).
• It's a syntax error.
• Adds string1 to string2 (both must be in numeric format).
51. What is the del statement used for?
Answers:
• To remove a function from a list given its name.
• To delete a file from the file system given its path.
• To remove an item from a list given its index.
• To delete a user if you are a privileged user.
52. What is the difference between using single quotes and double quotes in Python strings?
Answers:
• Double quotes are for constants. Single quotes are for variables.
• There is no difference.
• Single quotes are for short strings. Double quotes are for long strings.
• In Python you can use only single quotes.
53. What is the result of "z1" + str(2) ?
Answers:
• 'z12.00'
• 'z12'
• the exception SyntaxError: invalid syntax
• the exception NameError: name '2' is not defined
54. What does the break keyword do?
Answers:
• Jumps out of the closest enclosing loop.
• Nothing.
• Starts a block of code that will run if the loop is exited normally.
• Jumps to the top of the closest enclosing loop.
55. How are non-anonymous Python functions declared?
Answers:
• With the "def" keyword.
• With function prototypes declared in header files.
• With the "function" keyword.
• With "do function ... done".
56. Which one of following Internet protocols is supported by Python libraries: HTTP, FTP, SMTP, POP3, IMAP4, NNTP, Telnet?
Answers:
• None of them
• All of them
• Only HTTP, FTP, POP3, IMAP4
• Only HTTP
57. How are comments denoted in Python?
Answers:
• /* text */
• // text
• # text
• <!-- text -->
• ^^ text ^^
58. What is the maximum recursion limit in Python?
Answers:
• 100
• 1000000
• It's configurable.
• 100000
• 10000
59. If N==100, what is used to read the next N bytes into a string?
Answers:
• open('file').readline()
• open('file').read()
• open('file').readlines()
• open('file').read(N)
60. What is a string delimited by?
Answers:
• "
• All of these are correct,
• """
• '''
• '
61. True or False. in python you can run linux command
Answers:
• True
• False
62. What is a socket in Python?
Answers:
• An area on the computer where a certain GUI widget is located
• An object that hides network connections under a single interface
• A signal sent from one GUI widget to another
• A block of data which is retrieved from a database via an SQL query
63. Which of the following will open a file for editing?
Answers:
• open("file.txt","e")
• open("file.txt","w")
• open("file.txt","r")
• open("file.txt")
64. How would you declare a list x in Python with predefined values of 1, 2 and 3 ?
Answers:
• x = [1, 2, 3]
• x = new list (1, 2, 3)
• x = list(1, 2, 3)
• x = {'1', '2', '3'}
• x = list{'1', '2', '3'}
65. What operator checks the inequality of two values?
Answers:
• !=
• isn't
• =/=
• ><
• >=
66. What keyword do you use to define a class?
Answers:
• def
• block
• object
• class
67. What file must a directory have in order to be an importable Python package?
Answers:
• __vars__.py
• __init__.py
• __class__.py
• init
68. What is the difference between an index in dictionaries and in tuples and lists?
Answers:
• There is no difference
• Tuples and lists are indexed by keys, while dictionaries are indexed by ordered numbers
• Tuples and lists are indexed by arbitrary letters, while dicitonaries are indexed by ordered numbers
• Tuples and lists are indexed by ordered numbers, while dictionaries are indexed by keys
69. Is it possible to work with databases in Jython?
Answers:
• Yes, using JDBC only
• Yes, using Python DB API only
• Yes, using both JDBC and Python DB API
• No
70. Are there tools available to help find bugs, or perform static analysis?
Answers:
• Yes, PyErrs.
• Yes, PyStats.
• No, you must find the bugs on your own.
• Yes, PyChecker and Pylint.
71. What are assertions?
Answers:
• Statements in which only boolean operations are used.
• Statements that can be used to test the validity of the code, which cause the program to stop if they are not true.
• Statements that can result in a syntax error.
• Comments that are written at the beginning of each class and functions to declare the intentions of their developers.
72. If variables a and b are initialized using an assignment (a, b) = (4, 6), what value will be stored in a variable c by using a statement c = eval("a*b")?
Answers:
• This statement will result in a syntax error.
• "a*b"
• 444444
• 24
73. A for loop is executed over the values of a
Answers:
• list only
• none of these
• set only
• any iterable
• tuple only
74. How does one pause the execution of a program for 5 seconds?
Answers:
• import time time.sleep(5)
• import date date.pause(5)
• import date date.pause(5.0)
75. How add comentaries in Python ?
Answers:
• ^^ text ^^
• // text
• # text or ' ' ' text' ' '
• <!-- text -->
• /* text */
76. What are wxPython, pyQT, and pyGTK?
Answers:
• GUI programming toolkits for Python
• Test suites for Python
• System administrators' toolkits for Python
• Names of popular Python repositories
77. In Python 2, What does the following statement return?  map(lambda x : x*2, [1, 2, 3])
Answers:
• [3, 2, 1]
• [6, 4, 2]
• None. It modifies the list in place.
• [2, 4, 6]
• [1, 2, 3]
78. Which will find how many elements are in a dictionary?
Answers:
• count = 1 for key in dict_.keys(): count += 1
• len(dict_)
• |dict_|
• dict_.entries()
79. Python has both == and is, what is the difference?
Answers:
• They are the same
• == checks for equality, is checks for identity
• == checks for identity, is checks for equality
80. What is the result of string.split('111+bb+c', '+') ?
Answers:
• none are correct
• ['c', 'bb', '111']
• ['111+bb+c']
• ['111', 'bb', 'c']
81. How are tuples enclosed?
Answers:
• Curly braces {}
• Square brackets []
• Parentheses ()
• Backquotes ``
82. The statement 'a,b = b,a' is a valid way to successfuly switch the values of the variables a and b in Python.
Answers:
• True
• False
83. Given the list "li = ["a", "Sir Robin", "Sir Gawaine", "Sir Not Appearing in this film", "cb", "rabbits"]", what does the following list comprehension return "[item for item in li if len(item) > 2]"?
Answers:
• ['Sir Robin', 'Sir Gawaine', 'Sir Not Appearing in this film']
• 4
• True
• ['Sir Robin', 'Sir Gawaine', 'Sir Not Appearing in this film', 'rabbits']
• ['Sir Robin', 'Sir Gawaine', 'Sir Not Appearing in this film', 'cb', 'rabbits']
84. Which of the following will start a multi-line string in python?
Answers:
• /*
• """
• <<EOF
• //
• #
85. What is the name of a feature invoked by the following: "This is a string"[3:9]
Answers:
• Multi-indexing
• Slices
• Pieces
• Pathfinding
86. After executing the following statements, what is the value of x?  x = [x for x in range(1,100,7)] x = x x = "0"
Answers:
• Syntax Error
• "0"
• [x for x in range(1,100,7)]
• x
87. How is Python's code is organized?
Answers:
• Logical blocks share the same indentation.
• Logical blocks are indented and enclosed in parentheses ().
• Logical blocks are separated by keywords.
• Logical blocks are enclosed in brackets { }.
88. There is only one Python interpreter.
Answers:
• True
• False
89. What data type is the following: (1, 2, 3) ?
Answers:
• List.
• Set.
• Map.
• Tuple.
• Counter.
90. Given a X = 'a b c', what does X.split() return?
Answers:
• ['a b c']
• ('a', 'b', 'c')
• ''a', 'b', 'c''
• ['a', 'b', 'c']
91. What will typing the following at the Python interpreter produce? >>> url = 'http://docs.python.org' >>> url[-4:]
Answers:
• 'python.org'
• 'docs'
• 'http'
• IndexError: string index out of range
• '.org'
92. In an if-statement, which of the following is a valid start to a line that ends with a ':' (colon) ?
Answers:
• elif
• elseif
• elsif
• eliff
93. In a Python project, what is the setup.py file is used for?
Answers:
• Document the project.
• Project installation.
• Set up of class variables.
• Create classes and functions.
94. a = []  How will you add an element to the list a?
Answers:
• a = 1
• a[0] = 1
• a.append(0)
• a(0) = 1
95. What is PyXML?
Answers:
• A Python package that allows processing XML documents.
• A tool for generating documentation in XML format from Python source code.
• A tool for automatic programs testing.
• A tool for displaying the structure of a Python program in a form of an XML document.
96. How can the elements in a list be reversed?
Answers:
• list_ = list_[-1::]
• list_[-1:-len(a)]
• list_.flip()
• list_.reverse()
97. Is it possible to catch AssertionError exceptions?
Answers:
• Yes, but only in Python's interactive shell
• Yes
• Yes, but only when not in Python's interactive shell
• No
98. Everything in Python is an object.
Answers:
• False.
• True.
• Everything but base numeric types like Int and Float.
• Everything but modules.
99. If i and j are numbers, which statement evaluates to the remainder of i divided by j?
Answers:
• i % j
• i / j
• i // j
• i mod j
100. Which of the following commands declares a dictionary literal?
Answers:
• my_dictionary = {"a": 123, "b": "value", "c":"test"}
• my_dictionary = "a" => 123, "b" => "value", "c" => "test"
• my_dictionary = array({"a": 123, "b": "value", "c":"test"})
• my_dictionary = ["a": 123, "b": "value", "c":"test"]
101. What will happen if you try to add an integer to a long number?
Answers:
• The result will be a long number.
• The result will be an integer.
• This operation will result in an overflow error.
• Python will warn you about a type mismatch and ask if you want to convert an integer to a long.
• The result of this operation is undefined.
102. In a class, which of the following is preferable because it follows conventions?
Answers:
• def __init__(self):
• def __init__(myarg):
• def __init__(arg):
• def __init__():
103. Is it possible to send MIME multipart messages from within a Python program?
Answers:
• Yes
• No
• Yes, but with no more than 16 parts
• Yes, but the size of the message may not exceed 640 KB
104. In Python the MRO is:
Answers:
• The order of classes that Python searches when looking for an attribute or method of a class.
• A member of the math library.
• A mail library that makes it easy to parse email headers.
105. There are 2 lists, a=[1,2,3]  and b=['a','b','c']  What will be the value of list 'a' after execution of this statement, a.extend(b)
Answers:
• Error message. Invalid List method
• ['a','b','c']
• [1,2,3,'a','b','c']
• ['a','b','c',1,2,3]
• [1,2,3]
106. Does the elif statement require a logical expression?
Answers:
• No, there is no elif statement in Python
• Yes, unless it is used in place of an else statement
• Yes
• No
107. What is the name of the standard Python GUI interpreter?
Answers:
• PyTerpret
• Guithon
• PyDE
• IDLE
108. According to PEP8 python programs should generally be indented with:
Answers:
• 4 spaces
• 8 spaces
• 1 tab
• 2 spaces
109. What will typing the following at the Python interpreter produce? sequence = ['A','B','C','D','E','F'] ; "D" in sequence
Answers:
• True
• ['A','B','C',True,'E','F']
• NameError exception
• False
110. What is the value of the variable a after the following statement:  a=(1,2,3); a=a[2];
Answers:
• 1
• None
• 3
• None and the system generates an error (exception)
• 2
111. Which of these lines properly checks the length of a variable named "l"?
Answers:
• len(l)
• l.len()
• length(l)
• l.length()
112. In Python (v2.6 and later), the 'json' module is a part of the standard library.
Answers:
• False
• True
113. After executing the following statement, what is the value of x?  x = "9" * 3
Answers:
• 27
• 333
• Syntax Error
• "999"
114. What does a function definition header end with?
Answers:
• ;
• nothing
• end of line
• :
115. What is a fundamental difference between a list and a tuple?
Answers:
• Lists can be mutated, while tuples cannot.
• Only list can be subclassed.
• Lists cannot be mutated, while tuples can.
• Lists have no length limit.
• Lists can be nested, tuples not.
116. What is used to read the next line in a file up to the '\n'?
Answers:
• open('file').readline()
• open('file').readlines()
• open('file').read()
• open('file').read('\n')
117. What is the exponentiation (power) operator?
Answers:
• ^
• Both are correct.
• None are correct.
• **
118. What is a string in Python?
Answers:
• A line of source code
• Any text put in double-quotes
• The same thing as a statement, just an argument
• An object which is a sequence of characters
119. How do you print from 0 to 10 in python?
Answers:
• for i in range(11): print i
• for( x = 0; x < 11; x++) printf("%s",x);
• while x < 10: print x
• for i in range(10): print i
120. How can each line of an already-opened text file be printed?
Answers:
• print file_
• cat file_
• while True: if not line: break line = file_.readline()
• for line in file_: print line
121. What character marks a decorator?
Answers:
• .
• @
• ()
• $
• !
122. What is the purpose of the map function?
Answers:
• To construct a directory of a Python package.
• To take a list and remove elements based on some criteria.
• To integrate geographical data (such as Google Maps) in Python programs.
• To perform a specific action on each element of a list without writing a loop.
123. What will typing the following at the Python interpreter produce? sequence = ['A','B','C','D','E','F'] ; sequence[:]
Answers:
• ('A', 'B', 'C', 'D', 'E', 'F')
• ['A', 'B', 'C', 'D', 'E', 'F']
• SyntaxError exception
• ['A', 'B', 'C', 'D', 'E']
124. How are the following strings related?  '123', "123", and """123"""
Answers:
• They are integers and not strings.
• They are equivalent.
• They are different.
• The third is not a string.
125. What will typing the following at the Python interpreter will produce? lang = "Python" ; lang[3]
Answers:
• 'h'
• 't'
• 'Pyth'
• 'Pyt'
126. Which method is used to get to the beginning of a file?
Answers:
• f.seek()
• f.seek(1)
• f.seek(0)
• f.rewind()
127. What will be the last value printed for i in range(1, 10):     print i
Answers:
• 11
• 9
• 1
• 8
• 10
128. Which of these lines will return 125?
Answers:
• 5 ** 3
• 5 ^ 3
• pow( "5 ^ 3")
• Math.pow( 5, 3)
129. What is the statement that can be used in Python if a statement is required syntactically but the program requires no action?
Answers:
• pass
• yield
• continue
• return
• break
130. The range(n) function returns values from...
Answers:
• n-1 to n
• 0 to n-1
• Syntax error: missing arguments
• 0 to n
131. What is a package?
Answers:
• All Python programs that are available on the computer.
• A folder with module files that can be imported together.
• Any folder with Python source code files in it.
• Any Python program which imports external modules.
132. How would you assign the last element of a list to the variable 'x' without modifying the list?
Answers:
• x = aList[-1]
• x = last(aList)
• x = aList.last()
• x = aList.pop()
133. What will typing the following at the Python interpreter produce? sequence = ['A','B','C','D','E','F'] ; sequence[-6]
Answers:
• 'A'
• 'B'
• IndexError exception
• 'F'
134. What does the expression "(lambda x: x + 3)(1)" return?
Answers:
• 13
• An anonymous function.
• 4
• A syntax error.
• 'lambda lambda lambda'
135. Assume dictionary mydict = {'foo': 'Hello', 'bar': 'World!'} Which of the below would change the value of foo to 'Goodbye' ?
Answers:
• mydict.foo = 'Goodbye'
• mydict.update('foo', 'Goodbye')
• mydict['foo'] = 'Goodbye'
• mydict.foo.update('Goodbye')
• mydict[foo] = 'Goodbye'
136. How is a default value to a function's parameter provided?
Answers:
• By writing the desired value in curly brackets after the parameter's name.
• It is impossible to provide a default value to a function's parameter.
• By writing an equal sign after the parameter's name and then the desired value.
• By writing the desired value in parentheses after the parameter's name.
137. What is the result of string.lower('RR')?
Answers:
• rr
• RR'
• 'rr'
• an AttributeError exception
• 'lower'
138. Which keywords can be used to define a function?
Answers:
• def, letrec
• def, lambda
• def, proc
• def, import
• def, defun
139. True or False; you can't create async program in python
Answers:
• True
• False
140. What is the main difference between a tuple and a list?
Answers:
• Lists are changeable sequences of data, while tuples are not changeable.
• Tuples can contain no more than 16 elements, lists can contain more than that.
• Tuples are created with square brackets and lists are create with square with parentheses.
• Tuples are created with parentheses and lists are create with square brackets.
141. What does the spawn family of functions do?
Answers:
• These functions allow a Python program to stop the current process.
• There are no such functions in Python.
• These functions allow a Python program to start another process.
• These functions allow a Python program to stop another process.
142. What will be result of 3/2 in Python 2.x?
Answers:
• 1.5
• 1
• 2
143. What would be the result of: print not (True or False) ?
Answers:
• TRUE
• 0
• 1
• False
144. Which of the following is not a valid data type in Python?
Answers:
• bool
• float
• str
• double
• int
145. What syntax do you use when you create a subclass of an existing class?
Answers:
• SubclassName is subclass of BasicClassName
• class SubclassName(BasicClassName):
• You cannot extend classes in Python
• class BasicClassName(SubclassName):
146. By convention, where are internal variables set in a Python class?
Answers:
• global variables
• the init function
• the __init__ function
• the __class__ function
147. If the body of a function func consists of only one statement pass, what will be the output of the expression print func()?
Answers:
• None
• Empty string
• This expression will result in a syntax error
• 0
148. Given the following assignment: s = ('xxx', 'abcxxxabc', 'xyx', 'abc', 'x.x', 'axa', 'axxxxa', 'axxya'), what is the result of the expression filter ((lambda s: re.search(r'xxx', s)), s)?
Answers:
• ('x.x')
• This expression will result in a syntax error.
• ('xxx')
• ('xxx', 'abcxxxabc', 'axxxxa')
149. Is it possible to swap values of variables a and b by using the expression 'a, b = b, a' ?
Answers:
• No.
• It is always possible.
• Yes, but only for string variables
• Yes, but only for numeric variables
150. Which of these two operations can be applied to a string: +, * ?
Answers:
• Neither.
• Both of them.
• Only *
• Only +
151. How can you open a binary file named dino?
Answers:
• open 'dino', 'r'
• fopen 'dino', 'r'
• open('dino', 'rb')
• open('dino', 'r')
152. What is the syntax of assertions in Python?
Answers:
• check Expression[, Arguments]
• test Expression[, Arguments]
• Any statement in which only boolean operations are used.
• assert Expression[, Arguments]
153. What is a DBM in Python?
Answers:
• Database manager
• Database mirroring
• Distributed buffer manager
• Database machine
154. What kind of functions are created with a lambda expression?
Answers:
• Precompiled
• There is no lambda expression in Python.
• Boolean
• Anonymous
155. What are decorators?
Answers:
• A way of applying transformations to a function or method definition using higher-order functions.
• Certain classes of identifiers (besides keywords) that have special meanings.
• Strings printed to standard out in the intermediate stages of processing.
• Detailed comments written in the lines directly preceding definitions.
156. What does the following code do sys.path.append('/usr/local') ?
Answers:
• Changes the current working directory.
• Adds a new directory to search for imported Python modules
• Changes the location from which the Python executable is run.
• Changes the location where subprocesses are searched for after they are launched.
• Changes the location where Python binaries are stored.
157. The built in Python mapping type is called
Answers:
• set
• dict
• hash
• list
158. Where does 'pip install' retrieve modules from?
Answers:
• the lowest-latency Sourceforge download mirror
• $PIP_PKG_DIR - your local database of Python packages (by default /var/cache/pip on UNIX and C:\pypackaging\pip on Windows)
• PyPI - the Python Package Index
• packages.debian.org - the Debian package archive
• 'pip' does not have an 'install' subcommand
159. Which of these structures cannot contain duplicates?
Answers:
• A Tuple
• A Sequence
• A List
• A Set
160. A decorator in python ________
Answers:
• is a sub-class on object in an inherited class
• reformats a source code according to python formatting rules
• Provides static documentation about an object.
• dynamically alters the functionality of a function, method, or class.
161. Assume myList = [1, 2, 3, 4, 5]  and myVar = 3  How would you check if myVar is contained in myList?
Answers:
• myVar.exists(myList)
• myVar.in(myList)
• myList.has_item(myVar)
• myVar in myList
• myList.contains(myVar)
162. Why might a Python module have the following code at the end: if __name__ == '__main__'?
Answers:
• This code prevents a module from being executed directly.
• Some of the viruses that infect Python files do not affect modules with such a statement.
• Code that is written after this statement is ignored by the interpreter, so comments are usually added after it.
• Code that is written after this statement is executed only when the module is used directly.
163. True or False: Python has private instance variables.
Answers:
• True when prefixed with the private keyword.
• False, but convention states that variable names starting with underscores should be treated as non-public.
• True. All variables are private instance variables.
• Only in "private" mode.
164. What does the pass statement do?
Answers:
• There is no such statement in Python.
• Nothing. It can be used when a statement is needed syntactically.
• It is a function which asks the user to enter a password.
• It passes control flow of the program to the debugger.
• Jumps to the top of the closest enclosing loop.
165. How would you check if the file 'myFile.txt' exists?
Answers:
• os.exists("myFile.txt")
• path_exists("myFile.txt")
• os.path.exists("myFile.txt")
• file_exists("myFile.txt")
166. When do you use strings in triple quotes?
Answers:
• They are used for strings containing Unicode symbols.
• They are used for strings containing regular expressions.
• Strings in triple quotes can span multiple lines without escaping newlines.
• (all of these)
167. How can one convert [1,2,3] to '1 - 2 - 3' ?
Answers:
• [1, 2, 3].merge()
• [1, 2, 3].merge(' - ')
• ' - '.merge([1,2,3])
• ' - '.join([1,2,3])
• merge([1,2,3], ' - ')
168. From which module can a user import classes and methods to work with regular expressions?
Answers:
• regularexpressions
• regexp
• sys
• re
169. What standard library module is used for manipulating path names?
Answers:
• paths
• stdpath
• sys.path
• pathname
• os.path
170. Which example would return "Python Supremacy"?
Answers:
• "Python _".substitute("_", "Supremacy")
• "Python _".replace("_", "Supremacy")
• "Python _".find("_", "Supremacy")
171. What kinds of variables can be used in Python programs?
Answers:
• Integers, longs, floats and imaginary numbers.
• Integers only.
• Integers and floats.
• Floats only.
172. The md5 and sha modules have been deprecated in favor of which module?
Answers:
• libhash
• hmac
• hashlib
• hasher
• hash
173. The 'distutils' module provides
Answers:
• the packaging tools for Python
• utility functions for calculating distance
• utility functions for higher order math functions.
174. Suppose a= [1,2,3]. What will be the value of 'a' after executing this command, a=a*3  ?
Answers:
• None
• Lists are Immutable. So, this will result in an error message.
• [3,6,9]
• [1,2,3,1,2,3,1,2,3]
175. Python standard library comes with which RDMS library?
Answers:
• sqlite
• mysql
• postgresql
• oracle
176. What is the correct form for the first line of the switch operator?
Answers:
• switch?
• switch:
• switch
• There is no switch operator in Python
177. Given str="hello" , what will be the result of an expression str[4:100]?
Answers:
• "o"
• "hell"
• It results in a syntax error.
• "hello"
178. What is the basic difference between theses two operations in 're' module: match() and search()?
Answers:
• re.search() operation checks for a match anywhere in the string. re.match() operation checks for a match only at the begining of the string.
• There is no difference between the two operations.
• The only difference is that re.match() has much more parameters than re.search()
• re.search() operation checks for a match only at the begining of the string. re.match() operation checks for a match anywhere in the string.
• The only difference is that re.search() has much more parameters than re.match()
179. Which of the following is a valid class declaration?
Answers:
• class NameClass(object): def __init__(var1, var2): self.var1 = var1 self.var2 = var2
• class NameClass(self, var1, var2): self.var1 = var1 self.var2 = var2
• class NameClass(var1, var2): self.var1 = var1 self.var2 = var2
• class NameClass(object): def __init__(self, var1, var2): self.var1 = var1 self.var2 = var2
• class NameClass(object): def __init__(var1, var2): this.var1 = var1 this.var2 = var2
180. How can you define a tuple having one element?
Answers:
• (1,)
• (1)
• 1
181. What is delegation?
Answers:
• Applying a function to a list of lists.
• An object oriented technique to implement a method by calling another method instead.
• Chaining together several function outputs.
• Passing the output of one function to another function.
182. What does mro stand for in Python?
Answers:
• Modular Rapid Object
• Method Resolution Order
• Massive Rounded Object
• Mercurial Research Orientation
183. If somewhere in a script is the statement f.close(), which of the following may have come before it?
Answers:
• none are correct
• f=open("tmp.tmp")
• open("tmp.tmp")
• f.open("tmp.tmp")
184. What is returned by the following expression: ("123",)[0]
Answers:
• ('123')
• None and the system generates an error (exception)
• None
• '123'
• '1'
185. What is htmllib?
Answers:
• An HTML parser based on the sgmllib SGML parser.
• A library of ready to use Python code snippets available for download from the web.
• A part of Python network library which allows to display HTML pages.
• A tool which is used to link web pages to relational databases.
186. What is returned by: ("123")[0]
Answers:
• None and the system generates an error (exception)
• '123'
• '1'
• ("123")
• None
187. Which of these will obtain a list of the distinct values in a list?
Answers:
• uniques = list(list_)
• uniques = list(x | x not in list_[_:])
• uniques = list(set(list_))
• uniques = list_.distinct()
188. You need to run two applications which have conflicting dependencies. What Python tool would you use to solve this problem?
Answers:
• there is no simple way to solve this problem using Python
• appengine
• virtualenv
• aptitude
• celery
189. What does PEP stand for?
Answers:
• Particularly Egregious Practices
• Python Echoes Python
• Python Engagement Pattern
• Python Enhancement Proposal
190. What part of an if, elif, else statement is optional?
Answers:
• else
• elif
• elif, else
• All parts are mandatory.
191. True or False? you can create Android programs with Python.
Answers:
• False
• True
192. Assume myDict = {'name': 'Foo', 'surname': 'Bar'}  How would you check for the presence of the 'name' key in myDict ?
Answers:
• has_attribute(name, myDict)
• 'name' in myDict
• hasattr(myDict, 'name')
• has_attribute('name', myDict)
• has_attribute(myDict, 'name')
193. What will be the value of the element a[0] after executing this set of commands?  a=[1,2,3] b=a b[0]=11
Answers:
• 1
• 11
194. 'chr' is the inverse of:
Answers:
• 'int'
• 'bin'
• 'ord'
• 'id'
195. If d = set( [ 0, 0, 1, 2, 2, 3, 4] ), what is the value of len(d) ?
Answers:
• 7
• 6
• 8
• 4
• 5
196. Given the expression monty = ('cave', 'of', 'arghhh'). Which of the following statments about this expression is true?
Answers:
• You can add "wizard tim" to monty using monty.extend("wizard tim").
• 'monty' points to an object that is immutable once declared.
• 'monty' is equivalent to the string "cave of arghhh".
• monty.pop() will return "arghhh" and remove it from monty.
197. When looping over a dictionary,  entries are found in which order? for k,v in mydict.items():     print k,v
Answers:
• sorted in order of the key
• sorted in order of the value
• in the order they were added to the dictionary
• Last In, First Out
• unsorted
198. What will an octal number and hexadecimal number start with?
Answers:
• Any digit
• 0 (zero)
• sign (plus or minus)
• There are no octal numbers in Python.
199. Which of these expressions produce the same results in Python 2.x? 5/3 5.0/3.0 5.0/3
Answers:
• 5 / 3 and 5.0 / 3
• All results are different.
• All results are the same.
• 5.0 / 3.0 and 5.0 / 3
• 5.0 / 3.0 and 5 / 3
200. In what way can Python interoperate with C code?
Answers:
• Cython
• Python C/API
• ctypes
• All of these
201. Given a dictionary 'unordered', which of these will sort the dictionary in descending order?
Answers:
• Dictionaries cannot be ordered.
• unordered.sort()
• unordered.sort(descending)
• unordered.sort("descending")
202. What is a pickle?
Answers:
• A name of a central Python repository.
• A Python package precompiled for faster loading.
• A Python interpreter which can be embedded into a C program.
• A representation of a Python object as a string of bytes.
203. Python comes with a UI Toolkit in its standard library. This toolkit is:
Answers:
• QT
• Tkinter
• Winforms
• GTK
204. Which of these list declarations will result in error?
Answers:
• l = [1, 2, 4]
• l = [1, 2, 4, ]
• None of these
• l = [1, 2, "four"]
205. In which of the following may a continue statement occur?
Answers:
• Function definitions, for and while loops, and finally clauses.
• For and while loops.
• Class definitions, function definitions, and for and while loops.
• For and while loops and finally clauses.
• Functions definitions and for and while loops.
206. What kind of language is Python?
Answers:
• Logical
• Multiparadigm
• Functional
• Procedural
207. The with keyword allows you to:
Answers:
• Invoke a Context Manager
• Assign a Value to a Variable
• Create a Pointer
208. How would you convert the string below to title case and remove all heading/trailing spaces ?  myStr = ' ThIs iS a samPle String. '
Answers:
• myStr.title().strip()
• title.strip(myStr)
• title(myStr).strip()
• myStr.striptitle()
• myStr.to_title().strip()
209. Which of these should you include in order to pass variables to a script?
Answers:
• from sys import args
• from sys import argv
• from sys import getarg
• from system import argv
210. Which is NOT an implementation of the Python Language?
Answers:
• PyPy
• PyPi
• CPython
• Jython
• IronPython
211. Which of the following is not an interface for a web server to communicate with a Python program?
Answers:
• cgi
• webcat
• wsgi
• fcgi
212. What function is used to list the contents of a directory or a folder?
Answers:
• os.foldercontents
• os.dir
• os.listdir
• On Windows computers win.listdir, on Unix computers unix.listdir, on Macs mac.listdir
213. Which will return the 10th element of a list, or None if no such element exists?
Answers:
• if 10 in list_: return list_[10] else: return None
• return list_[10:]
• All of the above.
• try: return list_[9] except IndexError: return None
214. How many lists are created from the following? a = [] b = a c = a[:]
Answers:
• None.
• 3
• 2
• 1
215. Which of the following statements will output the following line, exactly as shown: python is fun\n
Answers:
• print r"python is fun\n"
• print @"python is fun\n"
• str = 'python is fun\n'; print str
• print 'python is fun\n'
• print "python is fun\n"
216. Which of these is not a common Python web framework?
Answers:
• web.py
• PyScripts
• Pylons
• Django
217. The Python 'pickle' module is always safe to use.
Answers:
• False
• True
218. Assume s = ' Hello World  '  Which of the following would remove only trailing whitespace?
Answers:
• ' '.join(s.rsplit())
• s.rstrip()
• s.strip()
• s.replace(" ", "")
• s.removeright(' ')
219. What is the result of the following expression: print((1, 2, 3) < (1, 2, 4))?
Answers:
• False.
• True.
• This expression will result in a syntax error.
• None.
220. What is the difference between using list comprehensions and generator expressions?
Answers:
• List comprehension produce the result as a list. Generator expressions produce a single value that is not a sequence.
• List comprehensions produce the result as a mutable list. Generator expressions produce the result as an immutable tuple.
• There is no difference between list comprehensions and generator expressions.
• List comprehensions produce the result as a list all at once in memory. Generator expressions do not produce the result all at once.
221. Distutils uses a file called ____ to act as the entry point to managing a package.
Answers:
• package.py
• setup.py
• install.py
• distutils.py
• run.py
222. What will typing the following at the Python interpreter produce? s1 = "Good" ; s2 = "Morning" ; s1 s2
Answers:
• 'Good Morning'
• GoodMorning
• SyntaxError exception
• 'GoodMorning'
223. When running a python script what is sys.argv[0] equal to?
Answers:
• The name of the script that was executed
• The first argument passed to the script
• The last argument passed to the script
224. Python's implementation for .NET is:
Answers:
• VisualPython
• there isn't one
• Python.NET
• IronPython
• P#.NET
225. What value will be stored in a variable arr after the expression arr = range(0, 6, 2) is executed?
Answers:
• [0, 2, 4]
• [0, 1, 2, 3, 4, 5, 6]
• [0, 2, 4, 6]
• [2, 3, 4, 5]
226. What does the following do: a=1,2,3
Answers:
• Generates an execution error
• Creates or updates the variable "a" with the sequence (1,2,3)
• Generates a compilation error
• Creates or updates the variable "a" with the number 3
• Creates or updates the variable "a" with the list [1,2,3]
227. Which of these functions is a generator that will produce an endless sequence of odd numbers?
Answers:
• def odds(): value = 1 while True: yield value value += 2
• def odds(): for value in xrange(1, maxint): yield value
• def odds(): value = 1 while True: return value += 2
228. Which of these are built-in test modules of Python?
Answers:
• unittest, doctest, testclient
• unittest, doctest, django.test
• unittest, doctest, __test__
• unittest, doctest
229. In Python, what does the 'dir' builtin do?
Answers:
• Lists the contents of a directory.
• Returns the name of the current working directory.
• Looks up the current user's directory record.
• Changes the current working directory.
• Lists the attribute names of an object.
230. Given dictionary:  a =  {'foo': 1, 'bar': 10}  Which of the following removes the last key pair value ?
Answers:
• del a[2]
• a.remove(bar)
• del a['bar']
• a.remove('bar')
• a.remove(2)
231. Which of the following is the correct import statement for the "exists" function?
Answers:
• from os.path import exists
• from os import exists
• from sys import exists
• from dir import exists
232. Which datatypes are immutable in Python
Answers:
• Dict, List, Set, Int
• Dict, Tuple, String, Set
• Float, Tuple, List, String
• Set, Tuple, Float, List
• Tuple, Int, Float, String
233. Which Python string formatting example is correct?
Answers:
• "{0}".format("Python!")
• "%s" & "Python!"
• print("%s", "Python!")
234. How can one serve current directory in http?
Answers:
• python -m SimpleHTTPServer
• python HTTPServer
• python -m HTTPServer
• python SimpleHTTPServer
235. If a file is opened by calling "input = open('data')", what does the line "aString = input.read()" do?
Answers:
• Read entire file into aString as a single string
• Read entire file into aString as a list of line strings (with \n)
• Read next line (including \n newline) into aString as a string
• "input.read()" is not a valid command
236. In order to create a string representation of a datetime object, you would use:
Answers:
• The datetime's strftime
• The datetime's strptime
237. What will typing the following at the Python interpreter produce? ['A','B','C','D','E','F'] + 'G'
Answers:
• TypeError exception
• 'ABCDEFG'
• ['G','A','B','C','D','E','F']
• ['A','B','C','D','E','F','G']
238. What is printed by the following: print type(lambda:None) ?
Answers:
• <type 'object'>
• <type 'function'>
• <type 'type'>
• <type 'NoneType'>
• <type 'bool'>
239. Which is the correct code for obtaining a random whole number from 1 to 1,000,000 in Python 2.x?
Answers:
• import random; x = random.choice(range(1000000))
• import random; x = random.random(1000000)
• import random; x = random.randint(1,1000000)
• import random; x = random.rand(1,1000000)
240. Which is the reference implementation of Python?
Answers:
• PyPy
• IronPython
• CPython
• Jython
241. What is a persistent dictionary?
Answers:
• A dictionary which is loaded automatically when Python's interpreter is started.
• A dictionary of a rather small size which is loaded to a cache memory for a faster performance.
• A sequence of name and value pairs which is saved to a disk, that will endure between multiple program runs.
• A dictionary in which data are stored in a sorted order.
242. What is the difference between the regular expression functions match and search?
Answers:
• match looks for matches only at the start of its input, search finds strings anywhere in the input.
• These functions are the same.
• There is no function search in a regular expression module.
• search looks for matches only at the start of its input, match finds strings anywhere in the input.
243. What does a function glob.glob do?
Answers:
• This function search for parameters on the Internet.
• There is no such function in Python.
• This function takes a wildcard pattern and returns a list of matching filenames or paths.
• This function runs a global file search on the computer.
244. What is the default SimpleHTTPServer port?
Answers:
• 3000
• 8000
• 9090
• 80
• 9000
245. After executing the following code, what is the value of d?   d = [0]   l = lambda x: d.append(x)   d.pop()   l(1)
Answers:
• [1]
• None.
• This expression will produce an exception.
• [2]
246. What gets printed:  a = b = [1, 2, 3] b[2] = 4 print(a)
Answers:
• [1, 4, 3]
• A syntax error.
• [1, 2, 3, 4]
• [1, 2, 4]
• [1, 2, 3]
247. Which is _not_ a way to control how Python finds the implementation of modules for import?
Answers:
• Change the contents of sys.meta_path
• Change the contents of sys.api_version
• Change the PYTHONPATH environment variable
• Change the contents of sys.path_hooks
• Change the contents of sys.path
248. What is the result of eval("7"), string.atoi("4"), int("7") ?
Answers:
• ("7", 4, 7)
• ("7", 4, 7.0)
• (7, 4, 7.0)
• (7, 4, 7)
249. What does range(6)[::2] return?
Answers:
• [2,4,6]
• [0,2,4]
• SyntaxError
• [5,6]
• [0,1]
250. What is the result of ("%g" % 74), '7' ?
Answers:
• ('74', '7')
• ('74', '7.00')
• (74, 7)
• ('74', '7.0')
251. Which of these is a valid way to implement switch-case in Python?
Answers:
• Define functions and then refer to them by key with a dict.
• All of the provided answers are technically correct.
• Use a list comprehension like [x for x in {1,2,3}]
• Python already has the "switch" keyword.
252. What is a list comprehension?
Answers:
• A tool to concisely create lists without using common constructs, like map or filter.
• A level of programming when one uses all aspects of lists with confidence.
• A term used to designate situations when filter (or map) are used together with lambda.
• A name of a paradigm of a list usage in Python.
253. After you enter the following in a Python script and run the script, what would get printed?  formatter = "%s" print formatter % (formatter)
Answers:
• s
• none are correct
• %%s
• %s
254. When opening a file, what is the difference between text mode and binary mode?
Answers:
• In text mode, the contents are first decoded using a platform-dependent encoding.
• In binary mode, new line characters are converted to an OS-specific representation.
• In text mode, carriage returns are always converted to linefeed characters.
• There is no difference.
255. Which of these will allow you to put more than one statement in one line of text?
Answers:
• A colon
• A semicolon
• None of these
• An extra indent
• A triple-quoted string
256. What does the following code do:  @something def some_function(): pass
Answers:
• Calls `something`, passing in `some_function` and rebinds the name `some_function` to the return value of `something`.
• It raises a `SyntaxError`
• Adds `something` to `some_function`'s `__annotations__` field
• Calls `something`, passing in `some_function` (`some_function` remains unchanged).
• Silences all errors raised by `something` while it is called.
257. filter(function, iterable) is equivalent to:
Answers:
• [item for item in iterable if function(item)] if function is None
• [item for item in iterable if function(item)] if function is not None
• [item for item in iterable if item] if function is not None
258. True or False: Python packages can be imported from inside a Zip file.
Answers:
• False
• True
259. Is it possible to check for more than one error in one except line?
Answers:
• Yes, if the exception types are enclosed in curly braces.
• Yes, if the exception types are enclosed in square brackets.
• Yes, if the exception types are enclosed in parentheses.
• No, it is not possible.
260. What is the output of the following script?  def f(a, L=[]):     L.append(a)     return L   print(f(1))  print(f(2))  print(f(3))
Answers:
• None
• [1] [1, 2] [1, 2, 3]
• AttributeError
• [1] [2] [3]
261. In Python 3.x, does 3/2 == 3.0/2.0?
Answers:
• Always.
• Never.
262. What will typing r"Python's great" at the Python interpreter produce?
Answers:
• Python\'s great
• Python is great
• Python's great
• Python\\'s great
263. def fn(a, *b, **c):     print(c)  fn(5)  What will be the output?
Answers:
• 25
• 5
• {}
• Error
• 255
264. In the Python interpreter, if the code "L = [4, 5, 6]; Y = [L] * 2; L[1] = 0" is executed, what would be stored in Y?
Answers:
• Y = [[4, 0, 6], [4, 0, 6]]
• Y = [[4, 5, 6], [4, 5, 6]]
• Y = [4, 0, 6, 4, 5, 6]
• Y = [8, 10, 12]
265. What gets printed:  a = [0] b = [a]  *4 a[0] = 2 print(b)
Answers:
• [[2], [2], [2], [2]]
• [0]
• [2]
• [[0], [0], [0], [0]]
• [[2], [0], [0], [0]]
266. What is 3/2?
Answers:
• 1
• It depends on the Python version
• 1.5
267. What type of error does "type('1') is int" return?
Answers:
• None; it returns False
• TypeError
• NameError
• SyntaxError
• None; it returns True
268. What does the function sys.modules.keys() do?
Answers:
• Reloads a module and passed a parameter to a function.
• Returns a list of all available modules.
• Loads a list of all modules in central repository.
• Returns a list of all loaded modules.
269. Which of the following can be used as a dictionary key?
Answers:
• list
• set
• None of Above
• dictionary
• tuple
270. The following lines do the same work. What is the difference between them? lines = string.split(text, '\n') and lines = text.split('\n')
Answers:
• No import is required by the second line.
• There is no difference.
• An import is required by the second line.
• No import is required by the first line.
271. What method is usually used to return unicode representation of an object?
Answers:
• str
• utf-8
• unicode
• __str__
• __unicode__
272. In a Python 2 new-style class declared as "Child(Base)", what is the correct way for a method "foo()" to call its base implementation?
Answers:
• super(Child, self).foo()
• super(Child).frob()
• Child.frob(self)
• super(Base, self).foo()
• Child.frob(super)
273. What is the correct way to get the exception as variable in except statement?
Answers:
• C is correct in Python 2, D is correct in Python 3, and Python 2.6 and 2.7 accepts both.
• D) except Exception as e:
• B) except (Exception, e):
• C) except Exception, e:
• A) except Exception<e>:
274. How is the ternary operator written in Python 2.5+?
Answers:
• 'equal' if a == b : 'not equal'
• 'equal' if a == b else 'not equal'
• if a == b then 'equal' else 'not equal'
• a == b? 'equal': 'not equal'
275. Given str="code", what will be the result of the expression str[0] = 'm'?
Answers:
• A TypeError. Strings in Python are immutable.
• "code"
• "mcode"
• "mode"
276. Python is a garbage collected language.  The CPython implementation primarily accomplishes this memory management via  _____.
Answers:
• the mark and sweep algorithm
• overridable __del__ methods called finalizers
• reference counting
• the gc garbage collection interface
277. If you wanted to copy a tree of files with the Python standard library, you would look at which module?
Answers:
• shlex
• shutil
• cmd
• sys
278. How do you increase a datetime variable called "dt" with three days?
Answers:
• dt += datetime.timedelta(3)
• dt += 3
• dt = datetime.datetime(dt.year, dt.month, dt.day + 3, dt.hour, dt.minute, dt.second)
• dt = dt.future(days=3)
• dt += (0, 0, 3, 0, 0, 0)
279. How can one merge two dicts?  >>> x = {'a':1, 'b': 2} >>> y = {'b':10, 'c': 11}  result: {'a': 1, 'b': 10, 'c': 11}
Answers:
• z = dict(x, **y)
• z = dict(list(x.items()) + list(y.items()))
• z = x.copy() z.update(y)
• All of these.
280. What will typing the following at the Python interpreter produce? lang = list('Python') ; lang[:-4]
Answers:
• ['P', 'y', 't', 'h']
• ['t', 'h', 'o', 'n']
• ['P', 'y']
• ['o', 'n']
281. In order to display a value in the interactive interpreter, Python uses what method of a class?
Answers:
• __str__
• __repr__
• __hash__
• __unicode__
282. What will be returned by the statement "12345"[1:-1] ?
Answers:
• 12345
• 234
• '1234'
• '234'
• 1234
283. Which will raise 2 to the 24th power?
Answers:
• x = 2 ** 24
• (Any Of These)
• x = 1 << 24
• import math; x = math.pow(2, 24)
284. Assume myList = [1,  2,  3,  4]  What line of code will print myList in reverse?
Answers:
• print myList.tail()
• print myList[-1]
• print myList.sort(reverse=True)
• print myList[::-1]
285. Is it possible to link a Python program to code written in C?
Answers:
• Yes; the C code can be in a form of a dynamically or a statically linked library.
• No, it is impossible.
• Yes, but C code must be provided in a form of statically linked library.
• Yes, but the C code must be provided in a form of a dynamically linked library.
286. True or False; you can sort dict by key
Answers:
• False
• True
287. Given the list called my_list, what would the following slice notation give you: my_list[-1:-5:-1]
Answers:
• No items, since the beginning and ending indices are the same
• A subset of the list, from the 4th item to the end of the list, in reverse order.
• Up to 4 items, starting from the last item in the list and indexed in reverse order.
• An IndexError exception. Negative numbers in slice notation have no meaning.
• 2 items, starting from the 5th index from the end of the list
288. What is " __doc__" for in Python?
Answers:
• return documentation string of object or none
• return documentation string of class or none
• return class information or none
• return object document or none
289. What will typing the following at the Python interpreter produce? sequence = ['A','B','C','D','E','F'] ; sequence[1:2:3]
Answers:
• 'B'
• []
• ['B']
• ['B', 'C']
290. Which of the following is NOT python ORM?
Answers:
• peewee
• SQLAlchemy
• Storm
• Doctrine
291. Given array = [1, 2, 3, 4, 5, 6] what is the value of array after the following statement?  del array[1:3]
Answers:
• [4, 5, 6]
• [1, 4, 5, 6]
• [3, 4, 5, 6]
• [1, 5, 6]
292. In Python, 'round(1)' and 'abs(-1)' will produce identical results.
Answers:
• True, both quantities are identical.
• False, the round() produces a float while the abs() produces an integer.
• The first expression will produce a NameError exception.
• The second expression will produce a SyntaxError exception.
293. Which of the following words are standard library functions? apply, complex, has, min, setaddr
Answers:
• All of them.
• apply, complex, min
• apply, has, setaddr
294. If a="holy",  b="grail", and c=None, what does the following expression return? a or b or c
Answers:
• None
• 'holy'
• True
• False
• 'grail'
295. How would you write the following with a list comprehension?  x = [] for i in range(5):     x.append([])     for j in range(10):          x[-1].append(j)
Answers:
• x = [[i for i in range(10)] for j in range(5)]
• x = [i for i in range(10) for j in range(5)]
• x = [i for i in range(5) for j in range(10)]
• x = [[i for i in range(5)] for j in range(10)]
296. What will typing the following at the Python interpreter produce? >>> num = [2,3,5,7,11] >>> len(num) // min(num)
Answers:
• 2
• 10.0
• 2.0
• 2.5
• SyntaxError exception
297. How can the whole numbers from 1 to 10 be totaled?
Answers:
• sum(i for i in range(1, 10))
• sum(i for i in xrange(1, 11))
• sum(range(1,10))
• total = 0 for i in range(1,11): for j in range(i): total++
298. What will be the value of a in: a = set(); a.add(['b'])?
Answers:
• set(['b'])
• TypeError: unhashable type: 'list'
• ['b']
• ('b')
299. What will the output of the following statement be?  print "%s is awesome !" % python
Answers:
• None
• %s is awesome !
• NameError
• pythons is awesome !
• python is awesome !
300. What will be the output:  a = [1, 2, 3, 4] for (i, x) in enumerate(a):     for (j, y) in enumerate(a[i:]):         print j,     print
Answers:
• 0 1 2 3 1 2 3 2 3 3
• 0 1 2 3 0 1 2 0 1 0
• 1 2 3 4 2 3 4 3 4 4
• 1 2 3 4 1 2 3 1 2 1
301. What is a future statement?
Answers:
• A declaration of a method that has not yet been implemented.
• A reference to a variable that has not yet been instantiated.
• A variable assignment for an instance of a class that has not yet been created.
• A directive to the compiler that a particular module should be compiled using syntax or semantics that will be available in a specified future release of Python.
• A proposal for a feature that should be implemented in the Python Standard Library in future releases.
302. Which of these can sort the following by value? sample_dict
Answers:
• sorted(sample_dict.items(), key=lambda d:d[0])
• sorted(sample_dict.items(), value=lambda d:d[0] )
• sorted(sample_dict.items(), key=lambda d:d[1])
• sorted(sample_dict.items(), value=lambda d:d[1] )
303. Assume:  a = 1 b = 4 c = (a == 'text') and a or b.  What is the value of c?
Answers:
• 'text1'
• 4
• 1
• 'text'
• None
304. What do you do to implicitly concatenate two literal strings?
Answers:
• Separate them with '*' characters
• Put the whole expression in triple-quotes """
• Write them one after another
• Separate them with commas
305. What is the result of print(2 <> 3) in Python 3?
Answers:
• 1
• False
• -1
• True
• SyntaxError
306. Which of these lines will reverse a list named "foo"?
Answers:
• All of these
• foo = foo ** -1
• foo = reverse(foo)
• foo = foo[::-1]
307. The super() function works for:
Answers:
• old style classes
• new style classes
• Both new and old style classes
308. What does a method name that starts with two underscores but does not end with two underscores signify?
Answers:
• It is an internal method of a class. It can be called directly and indirectly.
• There is no reason to do that.
• The method's name will be mangled to make it unlikely the method will be overridden in a subclass.
• This construction denotes a method in a class which can be called from within other classes.
309. If you use UTF-8 characters in your source file, what should you do to make it work under Python 2?
Answers:
• # -*- coding: utf-8 -*-
• # coding:utf-8
• # vim: set fileencoding=utf-8 :
• Any of these
310. Which of the following if statements will result in an error?
Answers:
• if ( None and 1/0 ):
• if ( 0 & 1/0 ):
• if ( 1 ): ... elif ( 1/0 ):
• if ( 0 and 1/0 ):
311. When resolving a name to an object in a function, which of these is not a scope considered?
Answers:
• Global
• Closed over
• Builtin
• Local
• Class
312. The code 'lambda x: return x' will do what?
Answers:
• Raise a ValueError Exception
• Raise a TypeError Exception
• Return x
• Raise a NameError Exception
• Raise a SyntaxError Exception
313. A function can be declared using "def double(x): return x+x" or using "double = lambda x: x+x". What is the difference between these declarations?
Answers:
• The second (lambda) can be used as a function argument, as in "map(double, l)", but the first (def) cannot.
• The first (def) defines "double" in the global or class namespace, while the second (lambda) only sets a local variable.
• The first (def) has its "__name__" attribute initialized to "double", but the second (lambda) does not.
• No difference: the declarations have the same effect.
• CPython can optimize and execute the first (def) more efficiently than the second (lambda).
314. Which of the following will produce the same output?
Answers:
• print ("word" in []) == False and print "word" in ([] == False)
• None of these combinations.
• print "word" in [] == False and print "word" in ([] == False)
• All three will produce the same output.
• print "word" in ([] == False) and print "word" in [] == False
315. At minimum, what must a metaclass be?
Answers:
• An instance of itself.
• A callable object.
• A class defined within a class.
• A class with a 'meta' attribute.
316. How are imaginary numbers denoted in Python?
Answers:
• Using escape sequence \n
• Using suffix i
• Using suffix j
• Using escape sequence \j
317. What standard library module would you use to find the names and default values of a function’s arguments?
Answers:
• argsig
• signature
• sys.argv
• inspect
• functools
318. What common convention do Python programs use to indicate internal-only APIs?
Answers:
• A prefix of "private_"
• Two leading and two trailing underscores
• A suffix of "_private"
• A double underscore prefix
• A single underscore prefix
319. In Python 2.7 the Counter object acts most like a:
Answers:
• list
• dictionary
• set
320. What is the result of the expression: print [k(1) for k in [lambda x: x + p for p in range(3)]]?
Answers:
• [1, 2, 3]
• This expression will produce a syntax error.
• [3, 3, 3]
• [4, 4, 4]
321. If I do "x = X(); y = x[1, 2:3, 4:5:6]", what type is passed to x.__getitem__?
Answers:
• plain slice
• extended slice
• list of ints
• dict of ints
• tuple
322. What's the difference between input() and raw_input() in Python 2.x?
Answers:
• raw_input() preserves invisible characters, linebreaks, etc., while input() cleans them up.
• raw_input() evaluates input as Python code, while input() reads input as a string.
• raw_input() reads input as a string, while input() reads it as unicode.
• raw_input() reads input as a string, while input() evaluates input as Python code.
• raw_input() doesn't cook input, while input() sears it to a nice medium-rare.
323. Python has both a math library and a cmath library. How are they related?
Answers:
• cmath is for complex numbers while math is for rational numbers
• cmath is the math library written in C for speed
324. Which of the following built-in identifiers may not be assigned to (as of Python 2.4)?
Answers:
• __builtins__
• None
• NotImplemented
• type
• object
325. x =  reduce(lambda x,y:x+y,[int(x) for x in "1"*10]) What is the value of x?
Answers:
• 2568988
• 10
• "1111111111"
• Syntax Error
326. print max([3,4,-5,0],key=abs) returns?
Answers:
• 5
• -5
• 0
• 4
• Syntax error
327. What is the Python 3 equivalent of the following Python 2 code: print >> f, "Smarterer", "Tests",
Answers:
• print("Smarterer", "Tests", end="") >> f
• print("Smarterer", "Tests", file=f, end=" ")
• print(("Smarterer", "Tests"), file=f, end="")
• fileprint(f, ("Smarterer", "Tests"))
• print("Smarterer", "Tests", file=f, end="\n")
328. How often is the value of y initialized in the following class?  >>>    class X(): >>>        def x(self,y = []): >>>            return y
Answers:
• Once per function call.
• Twice.
• Once.
• Once per class instance.
329. Using the python string module, what would the following return: string.join(['Python', 'is', 'great']) ?
Answers:
• 'Python is great'
• Python is great
• ''Python''is''great'
• A 'SyntaxError: invalid syntax' exception
330. For reading Comma Separated Value files you use the csv module. In which more must files be opened for use of the cvs module?
Answers:
• Binary mode in Python 2, text mode in Python 3
• Text mode
• Text mode in Python 2, binary mode in Python 3
• Binary mode
331. Which of the following is not a Python standard library module for processing arguments to a program?
Answers:
• getopt
• getargs
• optparse
• argparse
332. Which of these arguments is not passed to a metaclass when it is instantiated?
Answers:
• Class module
• Class bases
• Class name
• Class dictionary
333. What is printed by print( r"\nthing" )?
Answers:
• "\nthing"
• r\nthing
• r"\nthing"
• \nthing
• A new line and then the string: thing
334. Which option creates a list of key value tuples from a dictionary sorted by value?  d = {'a':1, 'b':2, 'c':3}
Answers:
• sorted(d.items(), key=operator.itemgetter(1))
• sorted(d.items(), value=operator.itemgetter(1))
• sorted(d.items(), value=operator.itemgetter(0))
• sorted(d.items(), key=lambda x[1])
335. This decorated function in python:  @foo def bar():     ...  is equal to:
Answers:
• def bar(): ... bar = foo()(bar)
• def bar(): ... foo()(bar)
• def bar(): ... foo(bar)
• def bar(): ... bar = foo(bar)
336. Given      mydict = {'foo': 'hello', 'bar': 'world'}  Which of the below would evaluate to True ?
Answers:
• type(mydict) = {}
• type(mydict) == {}
• mydict.type == {}
• import types type(mydict) = types.DictionaryType
• import types type(mydict) == types.DictionaryType
337. If a and b are strings, which of the following is equivalent to [a] + [b] ?
Answers:
• [a + b]
• [a].append(b)
• [a,b]
• [a].extend([b])
338. Given a list: lst = ['alpha', 'beta', '', 'gamma']. What will be returned by the function: filter(None, lst)?
Answers:
• A NameError exception
• ['alpha', 'beta', '', 'gamma']
• ['alpha', 'beta', 'gamma']
• ['']
339. When searching for imports Python searches what path?
Answers:
• os.import_path
• All of these
• sys.path
• sys.PYTHONPATH
340. The distribute library is a fork of
Answers:
• distutils2
• distutils
• setuptools
• pip
341. Which statement change the variable line from   "<table><td>td main</td>" to   "<table><tr>td main</tr>"
Answers:
• line.replace("td","tr")
• line.replace("td>","tr>")
• line = "tr>".join(line.split("td>")
• line = line.replace("td","tr")
342. All Exceptions in Python are subclassed from
Answers:
• Exception
• BaseException
• AbstractException
343. Which of these Python 2.7 APIs provides a high (for the platform) resolution wall-clock timer?
Answers:
• time.clock()
• All of these
• None of these
• ntmodule.QueryPerformanceCounter()
• posix.clock_gettime()
344. Consider a method x.foo decorated with @classmethod: What would x.foo.__class__ return?
Answers:
• <type 'method'>
• <type 'instancemethod'>
• <type 'object'>
• <type 'dictionary'>
• <type 'classmethod'>
345. In Python 3.2's stand CPython implementation, all built-in types support weak-referencing.
Answers:
• False
• True
346. If a = 1 and b = 2, what does the expression "a and b" return?
Answers:
• True.
• 1
• 2
• 3
• False.
347. In the Python 2.x interpreter, which piece of code will print "hello world" with only a space between the words?
Answers:
• print "hello"; print "world"
• print "hello\tworld"
• print "hello" + "world"
• print "hello",; print "world"
• None of these
348. Suppose a= [1,2,3,4]. What will be the value of 'a' after we execute this statement  a= a.append(5) ?
Answers:
• [1,2,3,4,5]
• None
• [1,2,3,4]
• Error message
349. The CPython implementation garbage collector detects reference cycles by ___.
Answers:
• None of these, the python standard does not allow reference cycles
• Determining all reachable objects, and deleting all other unreachable objects from the stack
• Keeping track of all container objects and comparing the number of references to a container to its total reference count
• Selecting an object at random and checking if it is in a reference cycle
• Traversing all references using an adapted breadth first search. If the process visits a node it has already seen, there is a reference cycle containing that node
350. Which of the following is equivalent to "x = a + b"?
Answers:
• x = a.__add__(b)
• from operator import add; x = add(a, b)
• x = sum({a, b})
• x = a.plus(b)
• from math import fsum; x = fsum([a, b])
351. Is it possible to use Java classes in Jython?
Answers:
• Yes, they must be treated like Python classes
• No
• Yes, they must be treated like Java classes
• Yes, but the programmer must use a special Jython syntax for calling Java classes
352. Python has which 3 different profilers in the standard library?
Answers:
• hotshot, nose, profile
• cProfile, profile, hotshot
• nose, timeit, profile
• profile, trace, pdb
353. If you wanted to determine the type of an image with the stdlib, you would use functions from which module?
Answers:
• types
• pimg
• Image
• imghdr
354. The built in method reversed() returns:
Answers:
• The original sequence, backwards
• An iterator that traverses the original sequence backwards
• The same thing as original_sequence[::-1]
355. What does the code 'import sndhdr; sndhdr.what(filename)' Do?
Answers:
• Determines the location of the sound file on disk
• Determines what Bitrate the sound file is
• Determines the type of sound file it is by inspecting the file headers
• Determines the type of sound file it is by inspecting the filename
356. Given an open file object f, what does f.read() result in when the end of the file has been reached?
Answers:
• It returns None
• It returns False
• It returns -1
• It returns '' (an empty string)
• It raises EOFError
357. What expression evaluates to 'python 2.7'?
Answers:
• all answers are correct
• "%s %d" % ('python', 2.7)
• "%s %r" % ('python', '2.7')
• "%s %f" % ('python', 2.7)
• "%s %s" % ('python', 2.7)
358. The function apply has the same functionality as:
Answers:
• functools.wraps
• *args, **kwargs
• list comprehensions
• map
359. What will be the result of the following expression 7 // 3 + 7 // -3?
Answers:
• 0
• 1
• -1
• There is no // operator in Python.
360. In a Python 3 class declared as "Child(Base)", what is the correct way for a method "foo()" to call its base implementation?
Answers:
• super(Child).foo()
• super(Base, self).foo()
• Child.foo(self)
• super().foo()
• Base.foo(self)
361. What would be output of following?  import sys d = {} for x in range(4):     d[x] = lambda : sys.stdout.write(x)  d[1]() d[2]() d[3]()
Answers:
• KeyError
• 012
• 333
• 123
362. Which of the following is a module in the Python Standard Library?
Answers:
• macpath
• linuxpath
• unixpath
• winpath
• solarispath
363. In Python 3.x, what must also happen if a class defines __eq__() ?
Answers:
• It must also define __ne__().
• It must also define __cmp__() if its instances need to be sortable.
• It must also define __ne__(), __gt__() and __lt__() if its instances need to be sortable.
• It must also define __hash__() if its instances are immutable and need to be hashable.
• It must also define __hash__() if its instances are mutable and need to be hashable.
364. All Warnings in Python are subclassed from:
Answers:
• Warning
• AbstractWarning
• BaseWarning
365. There are two strings, "a" and "b" with same values ,a="harmeet" and b="harmeet". Which one of the following case is true?
Answers:
• Both strings a and b refer to different strings having same value.
• Both strings "a" and "b" refer to one single string with value "harmeet"


{ 0 comments... read them below or add one }

Post a Comment