Elance Python Test Answers



What is a correct term for the following piece of Python syntax: 3 + 4

An expression.
A suite.
A statement.
A lambda.
A closure.

 

 

What will an octal number and hexadecimal number start with?

There are no octal numbers in Python.
sign (plus or minus)
Any digit
0 (zero)

 

 

What does the following code do sys.path.append('/usr/local') ?

Changes the current working directory.
Changes the location where subprocesses are searched for after they are launched.
Adds a new directory to search for imported Python modules
Changes the location where Python binaries are stored.
Changes the location from which the Python executable is run.

 

 

Which method is used to get to the beginning of a file?

f.seek(0)
f.seek(1)
f.seek()
f.rewind()

 

 

Is it possible to swap values of variables a and b by using the expression 'a, b = b, a' ?

Yes, but only for numeric variables
Yes, but only for string variables
No.
It is always possible.

 

 

Which of these lines properly checks the length of a variable named "l"?

l.len()
len(l)
length(l)
l.length()

 

 

What is the type of the expression (' ', )?

integer
tuple
string
This expression will result in a syntax error.

 

 

What is the difference between an index in dictionaries and in tuples and lists?

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
There is no difference
Tuples and lists are indexed by ordered numbers, while dictionaries are indexed by keys

 

 

What operator checks the inequality of two values?

=/=
>=
isn't
!=
>< 

 

 

What does the expression string1 + string2 do?

It's a syntax error.
Adds string1 to string2 (both must be in numeric format).
Concatenates string1 and string2.
Repeats string1 string2 times (string2 must be in numeric format).

 

 

Is it possible to call a function from within another function?

Yes, but only when the program runs on a remote server.
Yes, but only in the interactive shell.
Yes.
No.

 

 

When opening the Python shell, the prompt you see is

$
#
>>> 

 

 

Which of these values equates to True?

None of these
""
{}
()

 

 

What is the purpose of an 'if' statement?

Repeatedly execute a block of code
Execute code from more than one place in a program
Conditionally execute a block of code

 

 

What keyword is used to define a function?

proc
func
def
sub

 

 

Python files typically have which extension?

pl
pie
py
pil
pt

 

 

Functions are first-class objects in Python.

Always
Never

 

 

It is possible to create a while loop that will never stop?

No
Yes

 

 

What is the index of the first item in a tuple or list?

0
-2,147,483,648
1
-1

 

 

What will be printed as the result of: animals = ['bear', 'tiger', 'penguin', 'zebra'] print animals[2] ?

tiger
zebra
bear
penguin

 

 

Which Python implementation is best for testing Java code?

CPython
IronPython
Jython
PyPy

 

 

Python variables are references to objects.

Always
Never

 

 

What keyword is used to define a function?

function
def
sub
None of these
define

 

 

What kind of type system does Python have?

Loading.
Dynamic.
Inverse.
Static.
Proportional.

 

 

What will be the value of a variable x after executing the expression x = y = 1?

This expression will result in a syntax error.
1
Undefined
0

 

 

If you want a function you define to return "a", what should be put on the last line of the function (correctly indented)?

ret("a")
"a"
return "a"
a

 

 

What character is used to denote the beginning of a comment?

{
/*
#
//

 

 

How does one print the string "fred" on a line by itself in Python 2.x?

print 'fred'
cout << "fred" << endl;
println('fred')
write('fred')

 

 

What will typing the following at the Python interpreter produce? [3]*3

'9'
[9]
'333'
[3, 3, 3]

 

 

What keyword is needed to use an external module?

package
external
use
import

 

 

What does the sys module include?

The name of the operating system where your Python code is run.
The largest integer the machine's architecture supports.
The Python interpreter's version number.
All are correct.

 

 

True or False: Python holds the current working directory in memory.

False
True

 

 

What does the print statement do?

Returns the status of all printers installed on the network.
Evaluates its parameters and writes the resulting objects to standard output.
Prints the source code on the default printer.
Allows users to input data.

 

 

What data type is the following: [1, 2, 3] ?

Set.
List.
Dictionary.
Counter.
Tuple.

 

 

True or False. in python you can run linux command

False
True

 

 

Which of the following data structures supports the 'in' operator: list, dictionary, set ?

All three.
list
dictionary
None.
set

 

 

What is a variable?

An object containing data whose value cannot be altered by the program
A statement which allows you to choose one variant from a given set
An object which may contain some data
A collection of elements, each identified by an index

 

 

What is the maximum recursion limit in Python?

100000
It's configurable.
1000000
10000
100

 

 

What function do you use to determine the size of a tuple, a list, or a string?

Tuplen for tuples, listlen for lists, strlen for strings
len
size
length

 

 

How are comments denoted in Python?

// text
^^ text ^^
/* text */
# text
<!-- text -->

 

 

When defining a class, what controls which parameters that may be passed when the class is instantiated?

Specifying those parameters after the class name.
Specifying those parameters in the definition of an __init__ method of the class.
Writing the desired values after the class name when the class instance is created.
There is no way to pass parameters to a class instance.

 

 

What is a string delimited by?

'
"
All of these are correct,
'''
"""

 

 

How are non-anonymous Python functions declared?

With "do function ... done".
With the "function" keyword.
With function prototypes declared in header files.
With the "def" keyword.

 

 

What is the del statement used for?

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.

 

 

Which one of following Internet protocols is supported by Python libraries: HTTP, FTP, SMTP, POP3, IMAP4, NNTP, Telnet?

All of them
Only HTTP
None of them
Only HTTP, FTP, POP3, IMAP4

 

 

Which of these will result in an error?

"hello" ** 2
"hello" + "hello"
len ( "hello" )
"hello" * 2

 

 

What is the difference between using single quotes and double quotes in Python strings?

Single quotes are for short strings. Double quotes are for long strings.
Double quotes are for constants. Single quotes are for variables.
In Python you can use only single quotes.
There is no difference.

 

 

What file must a directory have in order to be an importable Python package?

__vars__.py
__class__.py
__init__.py
init

 

 

How would you declare a list x in Python with predefined values of 1, 2 and 3 ?

x = {'1', '2', '3'}
x = list{'1', '2', '3'}
x = list(1, 2, 3)
x = [1, 2, 3]
x = new list (1, 2, 3)

 

 

Which of the following is NOT a valid part of an "if" block?

if:
elif:
else:
elseif:

 

 

Which method of file objects will return the next line?

read
get
echo
readline

 

 

How are the results of '12 ** 3' and 'pow(12,3)' related?

The first expression will produce a SyntaxError exception.
The second expression will produce a NameError exception.
They are different.
They are equivalent.

 

 

What will be returned when the following command is run: print 5 <= -2 ?

'5 <= -2'
True
False
3

 

 

Is it possible to work with databases in Jython?

Yes, using Python DB API only
No
Yes, using both JDBC and Python DB API
Yes, using JDBC only

What keywords are used in Python's assignment statements?


assign

assume
There are no keywords in assignment statements.
let

 

 

How add comentaries in Python ?

<!-- text -->
^^ text ^^
// text
# text or ' ' ' text' ' '
/* text */

 

 

How does one pause the execution of a program for 5 seconds?

import date date.pause(5)
import date date.pause(5.0)
import time time.sleep(5)

 

 

What is a socket in Python?

An area on the computer where a certain GUI widget is located
An object that hides network connections under a single interface
A block of data which is retrieved from a database via an SQL query
A signal sent from one GUI widget to another

 

 

What are wxPython, pyQT, and pyGTK?

Test suites for Python
System administrators' toolkits for Python
GUI programming toolkits for Python
Names of popular Python repositories

 

 

When is the function __init__ called?

When an instance of a class is created.
At a program's start.
At a program's end.
When an instance of a class is destroyed.

 

 

What does the break keyword do?

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.

 

 

The statement 'a,b = b,a' is a valid way to successfuly switch the values of the variables a and b in Python.

True
False

 

 

What is the result of "z1" + str(2) ?

'z12'
the exception NameError: name '2' is not defined
the exception SyntaxError: invalid syntax
'z12.00'

 

 

Which of the following will open a file for editing?

open("file.txt","w")
open("file.txt","r")
open("file.txt")
open("file.txt","e")

 

 

If N==100, what is used to read the next N bytes into a string?

open('file').read(N)
open('file').readline()
open('file').readlines()
open('file').read()

 

 

Are there tools available to help find bugs, or perform static analysis?

Yes, PyErrs.
Yes, PyStats.
No, you must find the bugs on your own.
Yes, PyChecker and Pylint.

 

 

What keyword do you use to define a class?

object
class
block
def

 

 

What is the result of string.split('111+bb+c', '+') ?

['111+bb+c']
none are correct
['111', 'bb', 'c']
['c', 'bb', '111']

 

 

After executing the following statements, what is the value of x? x = [x for x in range(1,100,7)] x = x x = "0"

x
Syntax Error
[x for x in range(1,100,7)]
"0"

 

 

A for loop is executed over the values of a

none of these
any iterable
tuple only
list only
set only

 

 

Which of the following is not a supported compression format provided by the standard library?

bzip
zip
gzip
lzma

 

 

What does Python use type declarations for?

structures
strings
Python does not have type declarations
numbers

 

 

What is a regular expression?

Any correct expression that is possible in Python.
An algorithm for quick retrieval of data from Python dictionaries.
A tool for matching strings of text, such as particular characters, words, or patterns of characters.
A set of programming language expressions that are used by a programmer on a regular basis.

 

 

How can you open text file "wilma" for reading in Python 2.x?

open('wilma', 'r')
open 'wilma', 'rb'
fopen("wilma", "rb");
fopen 'wilma', 'r'

 

 

What are assertions?

Comments that are written at the beginning of each class and functions to declare the intentions of their developers.
Statements that can result in a syntax error.
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.

 

 

PEP8 provides:

A style guide for writing Python Programs
Instructions on how to Introduce New PEP's
The deprecation of Python modules

 

 

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)

[1,2,3,'a','b','c']
[1,2,3]
['a','b','c']
['a','b','c',1,2,3]
Error message. Invalid List method

 

 

In Python (v2.6 and later), the 'json' module is a part of the standard library.

False
True

 

 

a = [] How will you add an element to the list a?

a.append(0)
a(0) = 1
a[0] = 1
a = 1

 

 

Which of the following will start a multi-line string in python?

#
//
/*
<<EOF
"""

 

 

In an if-statement, which of the following is a valid start to a line that ends with a ':' (colon) ?

elseif
eliff
elsif
elif

 

 

In Python 2, What does the following statement return? map(lambda x : x*2, [1, 2, 3])

[3, 2, 1]
[6, 4, 2]
None. It modifies the list in place.
[1, 2, 3]
[2, 4, 6]

 

 

How is Python's code is organized?

Logical blocks are separated by keywords.
Logical blocks share the same indentation.
Logical blocks are indented and enclosed in parentheses ().
Logical blocks are enclosed in brackets { }.

 

 

How are tuples enclosed?

Square brackets []
Curly braces {}
Parentheses ()
Backquotes ``

 

 

What is PyXML?

A Python package that allows processing XML documents.
A tool for generating documentation in XML format from Python source code.
A tool for displaying the structure of a Python program in a form of an XML document.
A tool for automatic programs testing.

 

 

In Python the MRO is:

A mail library that makes it easy to parse email headers.
The order of classes that Python searches when looking for an attribute or method of a class.
A member of the math library.

 

 

Which will find how many elements are in a dictionary?

count = 1 for key in dict_.keys(): count += 1
|dict_|
dict_.entries()
len(dict_)

 

 

In a class, which of the following is preferable because it follows conventions?

def __init__(myarg):
def __init__(arg):
def __init__(self):
def __init__():

 

 

Python has both == and is, what is the difference?

== checks for identity, is checks for equality
They are the same
== checks for equality, is checks for identity

 

 

In a Python project, what is the setup.py file is used for?

Project installation.
Document the project.
Create classes and functions.
Set up of class variables.

 

 

What will typing the following at the Python interpreter produce? sequence = ['A','B','C','D','E','F'] ; "D" in sequence

True
False
NameError exception
['A','B','C',True,'E','F']

 

 

There is only one Python interpreter.

False
True

 

 

What data type is the following: (1, 2, 3) ?

Tuple.
Map.
Set.
List.
Counter.

 

 

What is the name of a feature invoked by the following: "This is a string"[3:9]

Pieces
Multi-indexing
Pathfinding
Slices

 

 

What does a function definition header end with?

nothing
;
end of line
:

 

 

What is the name of the standard Python GUI interpreter?

PyTerpret
IDLE
PyDE
Guithon

 

 

Which of the following commands declares a dictionary literal?

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"}
my_dictionary = ["a": 123, "b": "value", "c":"test"]

 

 

Given a X = 'a b c', what does X.split() return?

''a', 'b', 'c''
('a', 'b', 'c')
['a b c']
['a', 'b', 'c']

 

 

Is it possible to send MIME multipart messages from within a Python program?

Yes
Yes, but the size of the message may not exceed 640 KB
Yes, but with no more than 16 parts
No

 

 

What is the value of the variable a after the following statement: a=(1,2,3); a=a[2];

None and the system generates an error (exception)
3
None
1
2

 

 

What is the exponentiation (power) operator?

Both are correct.
**
^
None are correct.

 

 

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

True
['Sir Robin', 'Sir Gawaine', 'Sir Not Appearing in this film']
['Sir Robin', 'Sir Gawaine', 'Sir Not Appearing in this film', 'rabbits']
4
['Sir Robin', 'Sir Gawaine', 'Sir Not Appearing in this film', 'cb', 'rabbits']

 

 

Everything in Python is an object.

True.
Everything but base numeric types like Int and Float.
False.
Everything but modules.

 

 

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")?

444444
24
"a*b"
This statement will result in a syntax error.

 

 

PEP8 style guidelines include:

Limit all lines to a maximum of 79 characters
Use 4 spaces per indentation level
Don't use spaces around the '=' sign when used to indicate a keyword argument or a default parameter value
All of these
CapWords for class names, lowercase for function names

 

 

After executing the following statement, what is the value of x? x = "9" * 3

27
333
"999"
Syntax Error
 

there is a code example: x = {"quizful": []} How can you add an element "python test" in list "quizful"?

x["quizful"].add("python test")
x["quizful"][] = "python test"
x["quizful"].append("python test")
x["quizful"] += "python test"

 

 

How can the elements in a list be reversed?

list_[-1:-len(a)]
list_.flip()
list_ = list_[-1::]
list_.reverse()

 

 

What character marks a decorator?

@
.
!
()
$

 

 

What will be the last value printed for i in range(1, 10): print i

10
1
11
9
8

 

 

If i and j are numbers, which statement evaluates to the remainder of i divided by j?

i // j
i mod j
i % j
i / j

 

 

What function is used to convert integer numbers to floats?

int_to_float
floatize
int2float
float

 

 

According to PEP8 python programs should generally be indented with:

2 spaces
4 spaces
8 spaces
1 tab

 

 

Does the elif statement require a logical expression?

No, there is no elif statement in Python
No
Yes, unless it is used in place of an else statement
Yes

 

 

How do you print from 0 to 10 in python?

for i in range(11): print i
while x < 10: print x
for( x = 0; x < 11; x++) printf("%s",x);
for i in range(10): print i

 

 

What is a string in Python?

Any text put in double-quotes
A line of source code
An object which is a sequence of characters
The same thing as a statement, just an argument

 

 

What will typing the following at the Python interpreter will produce? lang = "Python" ; lang[3]

't'
'Pyth'
'h'
'Pyt'

 

 

What is the statement that can be used in Python if a statement is required syntactically but the program requires no action?

return
pass
break
continue
yield

 

 

What will typing the following at the Python interpreter produce? >>> url = 'http://docs.python.org' >>> url[-4:]

'python.org'
'http'
'.org'
'docs'
IndexError: string index out of range

 

 

Is it possible to catch AssertionError exceptions?

Yes, but only in Python's interactive shell
No
Yes
Yes, but only when not in Python's interactive shell

 

 

What is used to read the next line in a file up to the '\n'?

open('file').read('\n')
open('file').readlines()
open('file').read()
open('file').readline()

 

 

The range(n) function returns values from...

0 to n
0 to n-1
Syntax error: missing arguments
n-1 to n

 

 

What is a fundamental difference between a list and a tuple?

Lists have no length limit.
Lists can be nested, tuples not.
Lists cannot be mutated, while tuples can.
Only list can be subclassed.
Lists can be mutated, while tuples cannot.

 

 

What will typing the following at the Python interpreter produce? sequence = ['A','B','C','D','E','F'] ; sequence[:]

('A', 'B', 'C', 'D', 'E', 'F')
['A', 'B', 'C', 'D', 'E']
['A', 'B', 'C', 'D', 'E', 'F']
SyntaxError exception

 

 

What is the main difference between a tuple and a list?

Tuples are created with parentheses and lists are create with square brackets.
Tuples can contain no more than 16 elements, lists can contain more than that.
Lists are changeable sequences of data, while tuples are not changeable.
Tuples are created with square brackets and lists are create with square with parentheses.

 

 

How can each line of an already-opened text file be printed?

cat file_
for line in file_: print line
print file_
while True: if not line: break line = file_.readline()

 

 

What is the type of the expression [" "]?

string
array
tuple
list

 

 

True or False; you can't create async program in python

False
True

 

 

What is the result of string.lower('RR')?

RR'
an AttributeError exception
'lower'
rr
'rr'

 

 

Which keywords can be used to define a function?

def, import
def, letrec
def, proc
def, defun
def, lambda

 

 

Assume dictionary mydict = {'foo': 'Hello', 'bar': 'World!'} Which of the below would change the value of foo to 'Goodbye' ?

mydict.foo = 'Goodbye'
mydict[foo] = 'Goodbye'
mydict.update('foo', 'Goodbye')
mydict['foo'] = 'Goodbye'
mydict.foo.update('Goodbye')

 

 

Which of these lines will return 125?

Math.pow( 5, 3)
5 ** 3
pow( "5 ^ 3")
5 ^ 3

 

 

What will typing the following at the Python interpreter produce? sequence = ['A','B','C','D','E','F'] ; sequence[-6]

'F'
'B'
IndexError exception
'A'

 

 

What will be result of 3/2 in Python 2.x?

1.5
2
1

 

 

What will happen if you try to add an integer to a long number?

The result will be a long number.
The result will be an integer.
This operation will result in an overflow error.
The result of this operation is undefined.
Python will warn you about a type mismatch and ask if you want to convert an integer to a long.

 

 

Which of the following is not a valid data type in Python?

double
bool
float
str
int

 

 

What does the pass statement do?

It passes control flow of the program to the debugger.
It is a function which asks the user to enter a password.
There is no such statement in Python.
Jumps to the top of the closest enclosing loop.
Nothing. It can be used when a statement is needed syntactically.

 

 

By convention, where are internal variables set in a Python class?

the __class__ function
global variables
the __init__ function
the init function

 

 

Where does 'pip install' retrieve modules from?

$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
'pip' does not have an 'install' subcommand
packages.debian.org - the Debian package archive
the lowest-latency Sourceforge download mirror

 

 

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

This expression will result in a syntax error.
('x.x')
('xxx', 'abcxxxabc', 'axxxxa')
('xxx')

 

 

How would you assign the last element of a list to the variable 'x' without modifying the list?

x = aList.pop()
x = aList.last()
x = aList[-1]
x = last(aList)

How is a default value to a function's parameter provided?


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.
By writing the desired value in curly brackets after the parameter's name.

 

 

What is the purpose of the map function?

To integrate geographical data (such as Google Maps) in Python programs.
To take a list and remove elements based on some criteria.
To perform a specific action on each element of a list without writing a loop.
To construct a directory of a Python package.

 

 

What does the expression "(lambda x: x + 3)(1)" return?

An anonymous function.
13
A syntax error.
'lambda lambda lambda'
4

 

 

How would you check if the file 'myFile.txt' exists?

os.path.exists("myFile.txt")
file_exists("myFile.txt")
os.exists("myFile.txt")
path_exists("myFile.txt")

 

 

Assume myList = [1, 2, 3, 4, 5] and myVar = 3 How would you check if myVar is contained in myList?

myVar in myList
myVar.in(myList)
myList.has_item(myVar)
myVar.exists(myList)
myList.contains(myVar)

 

 

How are the following strings related? '123', "123", and """123"""

They are different.
The third is not a string.
They are equivalent.
They are integers and not strings.

 

 

A decorator in python ________

dynamically alters the functionality of a function, method, or class.
reformats a source code according to python formatting rules
is a sub-class on object in an inherited class
Provides static documentation about an object.

 

 

How can you open a binary file named dino?

open 'dino', 'r'
open('dino', 'r')
fopen 'dino', 'r'
open('dino', 'rb')

 

 

What kind of functions are created with a lambda expression?

Boolean
Anonymous
There is no lambda expression in Python.
Precompiled

 

 

Which of these two operations can be applied to a string: +, * ?

Only +
Neither.
Only *
Both of them.

 

 

What is the correct form for the first line of the switch operator?

There is no switch operator in Python
switch:
switch?
switch

 

 

Which example would return "Python Supremacy"?

"Python _".find("_", "Supremacy")
"Python _".substitute("_", "Supremacy")
"Python _".replace("_", "Supremacy")

 

 

Why might a Python module have the following code at the end: if __name__ == '__main__'?

Code that is written after this statement is ignored by the interpreter, so comments are usually added after it.
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 executed only when the module is used directly.

 

 

What is a package?

All Python programs that are available on the computer.
Any Python program which imports external modules.
A folder with module files that can be imported together.
Any folder with Python source code files in it.

 

 

If you want to enter accented characters, what is put in front of the string the character?

d
g
G
u

 

 

Which of these structures cannot contain duplicates?

A Tuple
A Set
A Sequence
A List

 

 

If the body of a function func consists of only one statement pass, what will be the output of the expression print func()?

None
This expression will result in a syntax error
Empty string
0

 

 

The built in Python mapping type is called

list
dict
hash
set

 

 

What would be the result of: print not (True or False) ?

False
1
TRUE
0

 

 

What is the syntax of assertions in Python?

assert Expression[, Arguments]
check Expression[, Arguments]
Any statement in which only boolean operations are used.
test Expression[, Arguments]

 

 

What syntax do you use when you create a subclass of an existing class?

You cannot extend classes in Python
class SubclassName(BasicClassName):
class BasicClassName(SubclassName):
SubclassName is subclass of BasicClassName

 

 

The 'distutils' module provides

the packaging tools for Python
utility functions for higher order math functions.
utility functions for calculating distance

 

 

True or False? you can create Android programs with Python.

True
False

 

 

What does the spawn family of functions do?

These functions allow a Python program to start another process.
There are no such functions in Python.
These functions allow a Python program to stop the current process.
These functions allow a Python program to stop another process.

 

 

When do you use strings in triple quotes?

They are used for strings containing Unicode symbols.
Strings in triple quotes can span multiple lines without escaping newlines.
(all of these)
They are used for strings containing regular expressions.

 

 

From which module can a user import classes and methods to work with regular expressions?

regularexpressions
sys
regexp
re

 

 

What are decorators?

A way of applying transformations to a function or method definition using higher-order functions.
Detailed comments written in the lines directly preceding definitions.
Certain classes of identifiers (besides keywords) that have special meanings.
Strings printed to standard out in the intermediate stages of processing.

 

 

What is a 'docstring'?

Documentation found on python's official websites and tutorials describing parts of the standard library.
A library that's used to automatically generate documentation from function definitions.
Any string literal in python code is often referred to as a 'docstring'.
A string literal that occurs as the first statement in a module, function, class, or method definition that serves to describe it's function.

 

 

What is delegation?

Applying a function to a list of lists.
Chaining together several function outputs.
An object oriented technique to implement a method by calling another method instead.
Passing the output of one function to another function

 

 

What kinds of variables can be used in Python programs?

Integers only.
Integers, longs, floats and imaginary numbers.
Integers and floats.
Floats only.

 

 

The md5 and sha modules have been deprecated in favor of which module?

hash
hasher
hmac
libhash
hashlib

 

 

What standard library module is used for manipulating path names?

os.path
pathname
stdpath
sys.path
paths

 

 

How can one convert [1,2,3] to '1 - 2 - 3' ?

[1, 2, 3].merge()
[1, 2, 3].merge(' - ')
merge([1,2,3], ' - ')
' - '.join([1,2,3])
' - '.merge([1,2,3])

 

 

True or False: Python has private instance variables.

True. All variables are private instance variables.
Only in "private" mode.
False, but convention states that variable names starting with underscores should be treated as non-public.
True when prefixed with the private keyword.

 

 

Which of the following is true about (1,2,3,)

It is an invalid expression
It represents an immutable object
It is equivalent to 1,2,3
It is equivalent to [1,2,3,]

 

 

what would be an answer of the code below: a = len('aa') switch a: case 1: print 2 break case 2: print 1 break default: print 0

case 2 - 1
no switch in python
case 2 and default - 1 and 0
nothing

 

 

What is returned by the following expression: ("123",)[0]

'123'
None
None and the system generates an error (exception)
('123')
'1'

 

 

What is a DBM in Python?

Database manager
Distributed buffer manager
Database mirroring
Database machine

 

 

You need to run two applications which have conflicting dependencies. What Python tool would you use to solve this problem?

virtualenv
celery
appengine
there is no simple way to solve this problem using Python
aptitude

 

 

Python standard library comes with which RDMS library?

oracle
postgresql
sqlite
mysql

 

 

If somewhere in a script is the statement f.close(), which of the following may have come before it?

open("tmp.tmp")
none are correct
f.open("tmp.tmp")
f=open("tmp.tmp")

 

 

Given str="hello" , what will be the result of an expression str[4:100]?

It results in a syntax error.
"o"
"hello"
"hell"

 

 

Suppose a= [1,2,3]. What will be the value of 'a' after executing this command, a=a*3 ?

[3,6,9]
Lists are Immutable. So, this will result in an error message.
None
[1,2,3,1,2,3,1,2,3]

 

 

What does mro stand for in Python?

Mercurial Research Orientation
Modular Rapid Object
Massive Rounded Object
Method Resolution Order

 

 

How can you define a tuple having one element?

1
(1)
(1,)

 

 

What is the basic difference between theses two operations in 're' module: match() and search()?

The only difference is that re.match() has much more parameters than re.search()
The only difference is that re.search() has much more parameters than re.match()
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.
There is no difference between the two operations.
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.

 

 

Which of these expressions produce the same results in Python 2.x? 5/3 5.0/3.0 5.0/3

5 / 3 and 5.0 / 3
All results are the same.
5.0 / 3.0 and 5.0 / 3
5.0 / 3.0 and 5 / 3
All results are different.

 

 

'chr' is the inverse of:

'ord'
'int'
'bin'
'id'

 

 

After executing the following statements, what is the value of var? var = "dlrow olleh" var = var[::-1]

"dlrow olle"
Syntax Error
The interpreter will crash
'hello world'

 

 

Which of these list declarations will result in error?

l = [1, 2, "four"]
l = [1, 2, 4, ]
None of these
l = [1, 2, 4]

 

 

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

1
11

 

 

Given the expression monty = ('cave', 'of', 'arghhh'). Which of the following statments about this expression is true?

'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.
You can add "wizard tim" to monty using monty.extend("wizard tim").

 

 

What will the following code print? my_list = ["A", "B", "A", "C", "D", "1"] try: print " ".join(my_list[:-2]) except: print "Error, could not print"

"Error, could not print"
"D 1 A B"
It does not print anything
"ACD1"
"A B A C"

 

 

What part of an if, elif, else statement is optional?

All parts are mandatory.
elif, else
elif
else

 

 

What is htmllib?

A tool which is used to link web pages to relational databases.
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.
An HTML parser based on the sgmllib SGML parser.

 

 

In which of the following may a continue statement occur?

Functions definitions and for and while loops.
Function definitions, for and while loops, and finally clauses.
For and while loops.
For and while loops and finally clauses.
Class definitions, function definitions, and for and while loops.

 

 

Which of the following is a valid class declaration?

class NameClass(object): def __init__(var1, var2): this.var1 = var1 this.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): self.var1 = var1 self.var2 = var2

 

 

Which of these will obtain a list of the distinct values in a list?

uniques = list(set(list_))
uniques = list(list_)
uniques = list(x | x not in list_[_:])
uniques = list_.distinct()

 

 

If d = set( [ 0, 0, 1, 2, 2, 3, 4] ), what is the value of len(d) ?

5
4
8
6
7

 

 

The with keyword allows you to:

Invoke a Context Manager
Assign a Value to a Variable
Create a Pointer

Given a dictionary 'unordered', which of these will sort the dictionary in descending order?

unordered.sort()
unordered.sort("descending")
Dictionaries cannot be ordered.
unordered.sort(descending)

 

 

What is returned by: ("123")[0]

'123'
'1'
None
("123")
None and the system generates an error (exception)

 

 

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

[0,2,3]
[1,2,0]
[1,2,3]
[1,0,3]

 

 

Which of the following is not an interface for a web server to communicate with a Python program?

wsgi
fcgi
webcat
cgi

 

 

The Python 'pickle' module is always safe to use.

True
False

 

 

Assume myDict = {'name': 'Foo', 'surname': 'Bar'} How would you check for the presence of the 'name' key in myDict ?

has_attribute(myDict, 'name')
hasattr(myDict, 'name')
has_attribute('name', myDict)
has_attribute(name, myDict)
'name' in myDict

 

 

What function is used to list the contents of a directory or a folder?

On Windows computers win.listdir, on Unix computers unix.listdir, on Macs mac.listdir
os.listdir
os.foldercontents
os.dir

 

 

What value will be stored in a variable arr after the expression arr = range(0, 6, 2) is executed?

[0, 1, 2, 3, 4, 5, 6]
[0, 2, 4]
[2, 3, 4, 5]
[0, 2, 4, 6]

 

 

What kind of language is Python?

Logical
Multiparadigm
Functional
Procedural

 

 

What is a pickle?

A Python package precompiled for faster loading.
A representation of a Python object as a string of bytes.
A name of a central Python repository.
A Python interpreter which can be embedded into a C program.

 

 

What does PEP stand for?

Python Enhancement Proposal
Python Engagement Pattern
Particularly Egregious Practices
Python Echoes Python

 

 

What is the difference between the regular expression functions match and search?

match looks for matches only at the start of its input, search finds strings anywhere in the input.
search looks for matches only at the start of its input, match finds strings anywhere in the input.
There is no function search in a regular expression module.
These functions are the same.

 

 

Python comes with a UI Toolkit in its standard library. This toolkit is:

QT
GTK
Winforms
Tkinter

 

 

What would be printed? x = [[1, 2], [3, 4], [5, 6]] x = [x for x in x for x in x] print x

[6, 6, 6, 6, 6, 6]
[[1, 2], [3, 4], [5, 6]]
Compilation error
[[1, 2], [1, 2], [1, 2]]
[1, 2, 3, 4, 5, 6]

 

 

What will typing the following at the Python interpreter produce? s1 = "Good" ; s2 = "Morning" ; s1 s2

GoodMorning
'GoodMorning'
'Good Morning'
SyntaxError exception

 

 

Which of these should you include in order to pass variables to a script?

from sys import getarg
from sys import args
from system import argv
from sys import argv

 

 

Which of these is not a common Python web framework?

PyScripts
Pylons
Django
web.py

 

 

Distutils uses a file called ____ to act as the entry point to managing a package.

distutils.py
install.py
package.py
run.py
setup.py

 

 

What is the difference between using list comprehensions and generator expressions?

List comprehensions produce the result as a mutable list. Generator expressions produce the result as an immutable tuple.
List comprehensions produce the result as a list all at once in memory. Generator expressions do not produce the result all at once.
List comprehension produce the result as a list. Generator expressions produce a single value that is not a sequence.
There is no difference between list comprehensions and generator expressions.

 

 

What gets printed: a = b = [1, 2, 3] b[2] = 4 print(a)

[1, 4, 3]
[1, 2, 4]
A syntax error.
[1, 2, 3, 4]
[1, 2, 3]

 

 

When running a python script what is sys.argv[0] equal to?

The last argument passed to the script
The first argument passed to the script
The name of the script that was executed

 

 

What is the result of the following expression: print((1, 2, 3) < (1, 2, 4))?

True.
None.
This expression will result in a syntax error.
False.

 

 

Which of the following statements will output the following line, exactly as shown: 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'
print r"python is fun\n"

 

 

How would you convert the string below to title case and remove all heading/trailing spaces ? myStr = ' ThIs iS a samPle String. '

title.strip(myStr)
myStr.to_title().strip()
title(myStr).strip()
myStr.striptitle()
myStr.title().strip()

 

 

In order to create a string representation of a datetime object, you would use:

The datetime's strptime
The datetime's strftime

 

 

In what way can Python interoperate with C code?

Python C/API
All of these
ctypes
Cython

 

 

Which of the following is the correct import statement for the "exists" function?

from dir import exists
from os.path import exists
from sys import exists
from os import exists

 

 

Which is NOT an implementation of the Python Language?

PyPi
Jython
CPython
IronPython
PyPy

 

 

Which of these are built-in test modules of Python?

unittest, doctest, testclient
unittest, doctest, __test__
unittest, doctest, django.test
unittest, doctest

 

 

When looping over a dictionary, entries are found in which order? for k,v in mydict.items(): print k,v

sorted in order of the key
in the order they were added to the dictionary
Last In, First Out
unsorted
sorted in order of the value

 

 

Python's implementation for .NET is:

VisualPython
IronPython
Python.NET
P#.NET
there isn't one

 

 

What does the following do: a=1,2,3

Creates or updates the variable "a" with the sequence (1,2,3)
Creates or updates the variable "a" with the list [1,2,3]
Creates or updates the variable "a" with the number 3
Generates a compilation error
Generates an execution error

 

 

Which Python string formatting example is correct?

"%s" & "Python!"
print("%s", "Python!")
"{0}".format("Python!")

 

 

How many lists are created from the following? a = [] b = a c = a[:]

3
None.
2
1

 

 

Assume s = ' Hello World ' Which of the following would remove only trailing whitespace?

' '.join(s.rsplit())
s.replace(" ", "")
s.removeright(' ')
s.strip()
s.rstrip()

 

 

If a file is opened by calling "input = open('data')", what does the line "aString = input.read()" do?

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

 

 

What is the result of eval("7"), string.atoi("4"), int("7") ?

("7", 4, 7)
("7", 4, 7.0)
(7, 4, 7.0)
(7, 4, 7)

 

 

What will typing the following at the Python interpreter produce? ['A','B','C','D','E','F'] + 'G'

['A','B','C','D','E','F','G']
TypeError exception
['G','A','B','C','D','E','F']
'ABCDEFG'

 

 

Which will return the 10th element of a list, or None if no such element exists?

try: return list_[9] except IndexError: return None
All of the above.
return list_[10:]
if 10 in list_: return list_[10] else: return None

 

 

What will typing r"Python's great" at the Python interpreter produce?

Python is great
Python's great
Python\\'s great
Python\'s great

 

 

Given dictionary: a = {'foo': 1, 'bar': 10} Which of the following removes the last key pair value ?

a.remove('bar')
a.remove(bar)
del a['bar']
a.remove(2)
del a[2]

 

 

How can one serve current directory in http?

python HTTPServer
python -m HTTPServer
python SimpleHTTPServer
python -m SimpleHTTPServer

 

 

What does range(6)[::2] return?

[0,2,4]
SyntaxError
[2,4,6]
[0,1]
[5,6]

 

 

Which of these functions is a generator that will produce an endless sequence of odd numbers?

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

 

 

Which is the correct code for obtaining a random whole number from 1 to 1,000,000 in Python 2.x?

import random; x = random.rand(1,1000000)
import random; x = random.choice(range(1000000))
import random; x = random.randint(1,1000000)
import random; x = random.random(1000000)

 

 

True or False: Python packages can be imported from inside a Zip file.

False
True

 

 

What is the default SimpleHTTPServer port?

3000
8000
9090
9000
80

 

 

What is printed by the following: print type(lambda:None) ?

<type 'object'>
<type 'NoneType'>
<type 'type'>
<type 'function'>
<type 'bool'>

 

 

In Python 3.x, does 3/2 == 3.0/2.0?

Never.
Always.

 

 

In Python, what does the 'dir' builtin do?

Looks up the current user's directory record.
Returns the name of the current working directory.
Changes the current working directory.
Lists the attribute names of an object.
Lists the contents of a directory.

 

 

Which is the reference implementation of Python?

IronPython
Jython
CPython
PyPy

 

 

What is the result of ("%g" % 74), '7' ?

('74', '7')
(74, 7)
('74', '7.00')
('74', '7.0')

 

 

What is 3/2?

It depends on the Python version
1
1.5

What is a list comprehension?

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 tool to concisely create lists without using common constructs, like map or filter.
A name of a paradigm of a list usage in Python.

 

 

After executing the following code, what is the value of d? d = [0] l = lambda x: d.append(x) d.pop() l(1)

[2]
None.
This expression will produce an exception.
[1]

 

 

What gets printed: a = [0] b = [a] *4 a[0] = 2 print(b)

[0]
[[2], [2], [2], [2]]
[2]
[[2], [0], [0], [0]]
[[0], [0], [0], [0]]

 

 

What does a function glob.glob do?

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.
There is no such function in Python.
This function search for parameters on the Internet.

 

 

Assume myList = [1, 2, 3, 4] What line of code will print myList in reverse?

print myList.sort(reverse=True)
print myList[::-1]
print myList.tail()
print myList[-1]

 

 

When opening a file, what is the difference between text mode and binary mode?

There is no difference.
In text mode, carriage returns are always converted to linefeed characters.
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.

 

 

After you enter the following in a Python script and run the script, what would get printed? formatter = "%s" print formatter % (formatter)

none are correct
%%s
%s
s

 

 

Which of these is a valid way to implement switch-case in Python?

Python already has the "switch" keyword.
Use a list comprehension like [x for x in {1,2,3}]
Define functions and then refer to them by key with a dict.
All of the provided answers are technically correct.

 

 

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?

Y = [8, 10, 12]
Y = [[4, 0, 6], [4, 0, 6]]
Y = [[4, 5, 6], [4, 5, 6]]
Y = [4, 0, 6, 4, 5, 6]

 

 

What is a persistent dictionary?

A dictionary in which data are stored in a sorted order.
A dictionary of a rather small size which is loaded to a cache memory for a faster performance.
A dictionary which is loaded automatically when Python's interpreter is started.
A sequence of name and value pairs which is saved to a disk, that will endure between multiple program runs.

 

 

Which datatypes are immutable in Python

Dict, Tuple, String, Set
Set, Tuple, Float, List
Dict, List, Set, Int
Float, Tuple, List, String
Tuple, Int, Float, String

 

 

Which is _not_ a way to control how Python finds the implementation of modules for import?

Change the contents of sys.path_hooks
Change the PYTHONPATH environment variable
Change the contents of sys.path
Change the contents of sys.api_version
Change the contents of sys.meta_path

 

 

Is it possible to check for more than one error in one except line?

No, it is not possible.
Yes, if the exception types are enclosed in parentheses.
Yes, if the exception types are enclosed in curly braces.
Yes, if the exception types are enclosed in square brackets.

 

 

What does the following code do: @something def some_function(): pass

Calls `something`, passing in `some_function` (`some_function` remains unchanged).
Adds `something` to `some_function`'s `__annotations__` field
Calls `something`, passing in `some_function` and rebinds the name `some_function` to the return value of `something`.
It raises a `SyntaxError`
Silences all errors raised by `something` while it is called.

 

 

What will typing the following at the Python interpreter produce? lang = list('Python') ; lang[:-4]

['P', 'y', 't', 'h']
['o', 'n']
['P', 'y']
['t', 'h', 'o', 'n']

 

 

filter(function, iterable) is equivalent to:

[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

 

 

What method is usually used to return unicode representation of an object?

unicode
utf-8
str
__unicode__
__str__

 

 

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

[1] [1, 2] [1, 2, 3]
AttributeError
[1] [2] [3]
None

 

 

In order to display a value in the interactive interpreter, Python uses what method of a class?

__repr__
__hash__
__str__
__unicode__

 

 

Which of these will allow you to put more than one statement in one line of text?

None of these
A semicolon
An extra indent
A colon
A triple-quoted string

 

 

Given str="code", what will be the result of the expression str[0] = 'm'?

"code"
"mode"
A TypeError. Strings in Python are immutable.
"mcode"

 

 

How is the ternary operator written in Python 2.5+?

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

 

 

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?

super(Child, self).foo()
super(Child).frob()
super(Base, self).foo()
Child.frob(super)
Child.frob(self)

 

 

What type of error does "type('1') is int" return?

NameError
TypeError
None; it returns True
None; it returns False
SyntaxError

 

 

def fn(a, *b, **c): print(c) fn(5) What will be the output?

25
{}
Error
5
255

 

 

What does the function sys.modules.keys() do?

Returns a list of all loaded modules.
Reloads a module and passed a parameter to a function.
Loads a list of all modules in central repository.
Returns a list of all available modules.

 

 

The following lines do the same work. What is the difference between them? lines = string.split(text, '\n') and lines = text.split('\n')

An import is required by the second line.
No import is required by the second line.
No import is required by the first line.
There is no difference.

 

 

Is it possible to link a Python program to code written in C?

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.
Yes; the C code can be in a form of a dynamically or a statically linked library.

 

 

What is the correct way to get the exception as variable in except statement?

B) except (Exception, e):
A) except Exception<e>:
C) except Exception, e:
D) except Exception as e:
C is correct in Python 2, D is correct in Python 3, and Python 2.6 and 2.7 accepts both.

 

 

What will be returned by the statement "12345"[1:-1] ?

1234
'1234'
'234'
234
12345

 

 

How can one merge two dicts? >>> x = {'a':1, 'b': 2} >>> y = {'b':10, 'c': 11} result: {'a': 1, 'b': 10, 'c': 11}

z = dict(x, **y)
All of these.
z = dict(list(x.items()) + list(y.items()))
z = x.copy() z.update(y)

 

 

Which will raise 2 to the 24th power?

x = 1 << 24
import math; x = math.pow(2, 24)
(Any Of These)
x = 2 ** 24

If you wanted to copy a tree of files with the Python standard library, you would look at which module?

shlex
sys
cmd
shutil

 

 

Python is a garbage collected language. The CPython implementation primarily accomplishes this memory management via _____.

overridable __del__ methods called finalizers
the gc garbage collection interface
reference counting
the mark and sweep algorithm

 

 

How do you increase a datetime variable called "dt" with three days?

dt = datetime.datetime(dt.year, dt.month, dt.day + 3, dt.hour, dt.minute, dt.second)
dt = dt.future(days=3)
dt += datetime.timedelta(3)
dt += 3
dt += (0, 0, 3, 0, 0, 0)

 

 

Given the list called my_list, what would the following slice notation give you: my_list[-1:-5:-1]

An IndexError exception. Negative numbers in slice notation have no meaning.
2 items, starting from the 5th index from the end of the list
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.
No items, since the beginning and ending indices are the same

 

 

How can the whole numbers from 1 to 10 be totaled?

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

 

 

What will typing the following at the Python interpreter produce? sequence = ['A','B','C','D','E','F'] ; sequence[1:2:3]

['B', 'C']
['B']
'B'
[]

 

 

Which of the following can be used as a dictionary key?

list
tuple
dictionary
None of Above
set

 

 

Given array = [1, 2, 3, 4, 5, 6] what is the value of array after the following statement? del array[1:3]

[4, 5, 6]
[3, 4, 5, 6]
[1, 4, 5, 6]
[1, 5, 6]

 

 

What will typing the following at the Python interpreter produce? >>> num = [2,3,5,7,11] >>> len(num) // min(num)

2
SyntaxError exception
2.0
10.0
2.5

 

 

In Python, 'round(1)' and 'abs(-1)' will produce identical results.

The first expression will produce a NameError exception.
The second expression will produce a SyntaxError exception.
True, both quantities are identical.
False, the round() produces a float while the abs() produces an integer.

 

 

What will be the value of a in: a = set(); a.add(['b'])?

set(['b'])
('b')
['b']
TypeError: unhashable type: 'list'

 

 

What is " __doc__" for in Python?

return class information or none
return documentation string of class or none
return object document or none
return documentation string of object or none

 

 

Which of the following is NOT python ORM?

SQLAlchemy
peewee
Storm
Doctrine

 

 

True or False; you can sort dict by key

True
False

 

 

Which of these lines will reverse a list named "foo"?

All of these
foo = foo ** -1
foo = foo[::-1]
foo = reverse(foo)

 

 

Which of the following words are standard library functions? apply, complex, has, min, setaddr

All of them.
apply, complex, min
apply, has, setaddr

 

 

If a="holy", b="grail", and c=None, what does the following expression return? a or b or c

True
None
'grail'
'holy'
False

 

 

What will the output of the following statement be? print "%s is awesome !" % python

pythons is awesome !
%s is awesome !
NameError
None
python is awesome !

 

 

What is the result of print(2 <> 3) in Python 3?

SyntaxError
-1
False
1
True

 

 

The code 'lambda x: return x' will do what?

Raise a ValueError Exception
Raise a SyntaxError Exception
Return x
Raise a TypeError Exception
Raise a NameError Exception

 

 

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)

x = [i for i in range(5) for j in range(10)]
x = [[i for i in range(5)] for j in range(10)]
x = [[i for i in range(10)] for j in range(5)]
x = [i for i in range(10) for j in range(5)]

 

 

What is a future statement?

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 reference to a variable that has not yet been instantiated.
A declaration of a method that has not yet been implemented.
A variable assignment for an instance of a class that has not yet been created.
A proposal for a feature that should be implemented in the Python Standard Library in future releases.

 

 

Which of these can sort the following by value? sample_dict

sorted(sample_dict.items(), key=lambda d:d[0])
sorted(sample_dict.items(), value=lambda d:d[1] )
sorted(sample_dict.items(), value=lambda d:d[0] )
sorted(sample_dict.items(), key=lambda d:d[1])

 

 

Assume: a = 1 b = 4 c = (a == 'text') and a or b. What is the value of c?

'text1'
'text'
1
4
None

 

 

What do you do to implicitly concatenate two literal strings?

Write them one after another
Put the whole expression in triple-quotes """
Separate them with commas
Separate them with '*' characters

 

 

Using the python string module, what would the following return: string.join(['Python', 'is', 'great']) ?

''Python''is''great'
Python is great
A 'SyntaxError: invalid syntax' exception
'Python is great'

 

 

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

1 2 3 4 1 2 3 1 2 1
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

 

 

What does a method name that starts with two underscores but does not end with two underscores signify?

It is an internal method of a class. It can be called directly and indirectly.
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.
There is no reason to do that.

 

 

The super() function works for:

Both new and old style classes
old style classes
new style classes

 

 

x = reduce(lambda x,y:x+y,[int(x) for x in "1"*10]) What is the value of x?

10
Syntax Error
"1111111111"
2568988

 

 

Which of the following if statements will result in an error?

if ( 0 and 1/0 ):
if ( None and 1/0 ):
if ( 1 ): ... elif ( 1/0 ):
if ( 0 & 1/0 ):

 

 

Given the following code, what will be printed to the standard output? x = 5 def some_function(): print(x) x = 6 some_function() print(x)

6, then 6
5, then 6
5, then 5
UnboundLocalError (and traceback)

 

 

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?

No difference: the declarations have the same effect.
The first (def) defines "double" in the global or class namespace, while the second (lambda) only sets a local variable.
The second (lambda) can be used as a function argument, as in "map(double, l)", but the first (def) cannot.
The first (def) has its "__name__" attribute initialized to "double", but the second (lambda) does not.
CPython can optimize and execute the first (def) more efficiently than the second (lambda).

 

 

print max([3,4,-5,0],key=abs) returns?

-5
Syntax error
4
5
0

 

 

How are imaginary numbers denoted in Python?

Using escape sequence \j
Using escape sequence \n
Using suffix i
Using suffix j

 

 

When resolving a name to an object in a function, which of these is not a scope considered?

Builtin
Closed over
Global
Local
Class

 

 

What standard library module would you use to find the names and default values of a function’s arguments?

signature
inspect
argsig
functools
sys.argv

 

 

If you use UTF-8 characters in your source file, what should you do to make it work under Python 2?

# coding:utf-8
# vim: set fileencoding=utf-8 :
# -*- coding: utf-8 -*-
Any of these

 

 

What's the difference between input() and raw_input() in Python 2.x?

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() doesn't cook input, while input() sears it to a nice medium-rare.
raw_input() reads input as a string, while input() evaluates input as Python code.
raw_input() reads input as a string, while input() reads it as unicode.

 

 

What common convention do Python programs use to indicate internal-only APIs?

A single underscore prefix
A prefix of "private_"
A double underscore prefix
Two leading and two trailing underscores
A suffix of "_private"

 

 

This decorated function in python: @foo def bar(): ... is equal to:

def bar(): ... foo()(bar)
def bar(): ... bar = foo()(bar)
def bar(): ... bar = foo(bar)
def bar(): ... foo(bar)

 

 

Given mydict = {'foo': 'hello', 'bar': 'world'} Which of the below would evaluate to True ?

import types type(mydict) = types.DictionaryType
mydict.type == {}
import types type(mydict) == types.DictionaryType
type(mydict) == {}
type(mydict) = {}

 

 

In Python 2.7 the Counter object acts most like a:

dictionary
list
set

 

 

Which of the following built-in identifiers may not be assigned to (as of Python 2.4)?

NotImplemented
None
__builtins__
object
type

 

 

How often is the value of y initialized in the following class? >>> class X(): >>> def x(self,y = []): >>> return y

Once per class instance.
Once per function call.
Twice.
Once.

 

 

Which of these arguments is not passed to a metaclass when it is instantiated?

Class name
Class module
Class bases
Class dictionary

 

 

What is printed by print( r"\nthing" )?

"\nthing"
\nthing
r"\nthing"
A new line and then the string: thing
r\nthing

 

 

Which of the following will produce the same output?

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

 

 

What is the result of the expression: print [k(1) for k in [lambda x: x + p for p in range(3)]]?

This expression will produce a syntax error.
[3, 3, 3]
[1, 2, 3]
[4, 4, 4]

 

 

At minimum, what must a metaclass be?

A callable object.
An instance of itself.
A class with a 'meta' attribute.
A class defined within a class.

 

 

Python has both a math library and a cmath library. How are they related?

cmath is the math library written in C for speed
cmath is for complex numbers while math is for rational numbers

 

 

Which of the following is not a Python standard library module for processing arguments to a program?

getopt
getargs
argparse
optparse

 

 

Which option creates a list of key value tuples from a dictionary sorted by value? d = {'a':1, 'b':2, 'c':3}

sorted(d.items(), value=operator.itemgetter(0))
sorted(d.items(), value=operator.itemgetter(1))
sorted(d.items(), key=operator.itemgetter(1))
sorted(d.items(), key=lambda x[1])

 

 

What is the Python 3 equivalent of the following Python 2 code: print >> f, "Smarterer", "Tests",

print("Smarterer", "Tests", file=f, end=" ")
print(("Smarterer", "Tests"), file=f, end="")
print("Smarterer", "Tests", file=f, end="\n")
print("Smarterer", "Tests", end="") >> f
fileprint(f, ("Smarterer", "Tests"))

 

 

For reading Comma Separated Value files you use the csv module. In which more must files be opened for use of the cvs module?

Binary mode in Python 2, text mode in Python 3
Text mode
Text mode in Python 2, binary mode in Python 3
Binary mode

 

 

If I do "x = X(); y = x[1, 2:3, 4:5:6]", what type is passed to x.__getitem__?

plain slice
tuple
dict of ints
extended slice
list of ints

 

 

All Exceptions in Python are subclassed from

AbstractException
Exception
BaseException

 

 

Given a list: lst = ['alpha', 'beta', '', 'gamma']. What will be returned by the function: filter(None, lst)?

['alpha', 'beta', '', 'gamma']
A NameError exception
['']
['alpha', 'beta', 'gamma']

 

 

When searching for imports Python searches what path?

os.import_path
sys.path
sys.PYTHONPATH
All of these

 

 

Which statement change the variable line from "<table><td>td main</td>" to "<table><tr>td main</tr>"

line = "tr>".join(line.split("td>")
line = line.replace("td","tr")
line.replace("td>","tr>")
line.replace("td","tr")

 

 

If a and b are strings, which of the following is equivalent to [a] + [b] ?

[a,b]
[a].extend([b])
[a + b]
[a].append(b)

 

 

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

123
012
333
KeyError

 

 

The distribute library is a fork of

distutils2
pip
setuptools
distutils

 

 

Suppose a= [1,2,3,4]. What will be the value of 'a' after we execute this statement a= a.append(5) ?

Error message
[1,2,3,4]
[1,2,3,4,5]
None

 

 

Python has which 3 different profilers in the standard library?

profile, trace, pdb
nose, timeit, profile
cProfile, profile, hotshot
hotshot, nose, profile

The CPython implementation garbage collector detects reference cycles by ___.

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
Keeping track of all container objects and comparing the number of references to a container to its total reference count
Determining all reachable objects, and deleting all other unreachable objects from the stack
None of these, the python standard does not allow reference cycles
Selecting an object at random and checking if it is in a reference cycle

 

 

If a = 1 and b = 2, what does the expression "a and b" return?

1
False.
2
3
True.

 

 

Which of these Python 2.7 APIs provides a high (for the platform) resolution wall-clock timer?

posix.clock_gettime()
All of these
ntmodule.QueryPerformanceCounter()
None of these
time.clock()

 

 

In Python 3.2's stand CPython implementation, all built-in types support weak-referencing.

False
True

 

 

Which of the following is equivalent to "x = a + b"?

x = a.__add__(b)
from operator import add; x = add(a, b)
x = sum({a, b})
from math import fsum; x = fsum([a, b])
x = a.plus(b)

 

 

What does the code 'import sndhdr; sndhdr.what(filename)' Do?

Determines the type of sound file it is by inspecting the filename
Determines the location of the sound file on disk
Determines the type of sound file it is by inspecting the file headers
Determines what Bitrate the sound file is

 

 

Is it possible to use Java classes in Jython?

Yes, but the programmer must use a special Jython syntax for calling Java classes
No
Yes, they must be treated like Java classes
Yes, they must be treated like Python classes

 

 

Consider a method x.foo decorated with @classmethod: What would x.foo.__class__ return?

<type 'object'>
<type 'dictionary'>
<type 'method'>
<type 'classmethod'>
<type 'instancemethod'>

 

 

In the Python 2.x interpreter, which piece of code will print "hello world" with only a space between the words?

print "hello",; print "world"
print "hello"; print "world"
print "hello" + "world"
None of these
print "hello\tworld"

 

 

Given an open file object f, what does f.read() result in when the end of the file has been reached?

It returns -1
It returns None
It returns '' (an empty string)
It returns False
It raises EOFError

 

 

If you wanted to determine the type of an image with the stdlib, you would use functions from which module?

types
Image
pimg
imghdr

 

 

The built in method reversed() returns:

The original sequence, backwards
An iterator that traverses the original sequence backwards
The same thing as original_sequence[::-1]

 

 

In a Python 3 class declared as "Child(Base)", what is the correct way for a method "foo()" to call its base implementation?

super().foo()
super(Base, self).foo()
super(Child).foo()
Base.foo(self)
Child.foo(self)

 

 

The function apply has the same functionality as:

list comprehensions
functools.wraps
*args, **kwargs
map

 

 

What will be the result of the following expression 7 // 3 + 7 // -3?

0
-1
There is no // operator in Python.
1

 

 

What expression evaluates to 'python 2.7'?

"%s %s" % ('python', 2.7)
"%s %r" % ('python', '2.7')
all answers are correct
"%s %f" % ('python', 2.7)
"%s %d" % ('python', 2.7)

 

 

In Python 3.x, what must also happen if a class defines __eq__() ?

It must also define __hash__() if its instances are mutable and need to be hashable.
It must also define __ne__().
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 __cmp__() if its instances need to be sortable.

 

 

Which of the following is a module in the Python Standard Library?

macpath
winpath
solarispath
unixpath
linuxpath

 

 

All Warnings in Python are subclassed from:

BaseWarning
Warning
AbstractWarning

 

 

There are two strings, "a" and "b" with same values ,a="harmeet" and b="harmeet". Which one of the following case is true?

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"
 

 

No comments:

Post a Comment