JavaScript is required
- What does _ do at the interactive prompt?
- Counter for how many times you've hit enter
- Refers to the last non-None expression result
-
def division1(): """Assume Python 2.7""" return 5 / 2
- 2
-
def division2(): return 5 // 2
- 2
-
def division3(): return divmod(5, 2)
- (2, 1)
- Which of these will exit a Python program without printing a stack trace?
-
Yes
No
exit()
-
Yes
No
os._exit(0)
-
Yes
No
quit()
-
Yes
No
raise BaseException()
-
Yes
No
raise SystemExit()
-
Yes
No
sys.exit()
-
Yes
No
- Which of these will exit a Python program, even if other non-daemon threads are running, and will skip running `finally` clauses?
-
Yes
No
exit()
-
Yes
No
os._exit(0)
-
Yes
No
quit()
-
Yes
No
raise BaseException()
-
Yes
No
raise SystemExit()
-
Yes
No
sys.exit()
-
Yes
No
- Which of these is a syntactically valid way to put multiple statements on one line?
-
Yes
No
(a = 1, foo(2), return 1)
-
Yes
No
[locals().__setitem__('a', 1), foo(2), __return__(1)]
-
Yes
No
a = 1; foo(2); return 1
-
Yes
No
a, _, _ = 1, foo(2), return 1
-
Yes
No
-
def indentation1(): """Is this function valid Python?""" if True: a = 1 else: a = 10 return a
- no
- yes
-
def indentation2(): """Is this function valid Python?""" if True: a = 1 else: a = 10 return a
- no
- yes
-
def indentation3(): """Is this function valid Python?""" if True: a = 1 else: a = 10 return a
- no
- yes
-
def indentation4(): """Is this function valid Python?""" if True: a = 1 else: a = 10 return a
- no
- yes
-
def format1(): return format(14,"3d") + ' ' + format(123.456,"0.2f")
-
' 14 0.456'
-
' 14 123.46'
-
'014 123.45'
-
'14 0123.456'
-
-
def printing(): """What does this function display?""" print 1, 'hi', [3, 4]
-
1 'hi' [3, 4]
-
1 hi [3, 4]
-
1, 'hi', <list instance at 0x10401ca70>
-
1, 'hi', [3, 4]
- syntax error
-
-
def reassign_variables(): """What's the value of a by the end of the function?""" a = 10 a = "asdf" return type(a)
-
<type 'int'>
-
<type 'str'>
-
-
def format2(): return "{0:3d} {1:0.2f}".format(14,123.456)
-
' 14 0.456'
-
' 14 123.46'
-
'014 123.45'
-
'14 0123.456'
-
- Which of these are methods of file objects
-
Yes
No
.close()
-
Yes
No
.count()
-
Yes
No
.encode()
-
Yes
No
.format()
-
Yes
No
.next()
-
Yes
No
.read()
-
Yes
No
.readlines()
-
Yes
No
.seek()
-
Yes
No
.write()
-
Yes
No
- Which of these objects share many methods with file objects?
-
Yes
No
1
-
Yes
No
StringIO.StringIO
-
Yes
No
socket.socket()
-
Yes
No
sys.stderr
-
Yes
No
sys.stdin
-
Yes
No
sys.stdout
-
Yes
No
- Which of these expressions evaluates to a reversed string? (where the initial string is s)
-
Yes
No
''.join(reversed(s))
-
Yes
No
reversed(s)
-
Yes
No
s.reverse()
-
Yes
No
s[-1:0:-1]
-
Yes
No
s[-1]
-
Yes
No
s[0:len(s):-1]
-
Yes
No
s[::-1]
-
Yes
No
s[len(s):0:-1]
-
Yes
No
str(reversed(s))
-
Yes
No
-
def repr1(): return repr(1)
-
'"1"'
-
'1'
-
<int 1>
-
-
def repr2(): return len(repr('abc'))
-
3
-
5
-
7
-
-
def repr3(): return len(str('abc'))
-
3
-
5
-
7
-
- Which of these comprehensions will run without errors in a fresh Python interpreter session?
-
Yes
No
(x for x in 'ab')
-
Yes
No
(x for x in range(10), range(10)
-
Yes
No
(x:y for x, y in [[1,2], [3, 4], [5, 6]])
-
Yes
No
[1 if x for x in [True, False, True]]
-
Yes
No
[ord(c) for c in word for word in ['abc', 'def', 'ghi']]
-
Yes
No
[x+y for x, y in zip('adsf', 'zvxc')]
-
Yes
No
{x for x in range(10) if x%2 == 0}
-
Yes
No
{x:y for x, y in zip(range(10), 'abc')}
-
Yes
No
- Which are valid tuples in Python?
-
Yes
No
()
-
Yes
No
(,)
-
Yes
No
(1)
-
Yes
No
(1,2)
-
Yes
No
1 + 1
-
Yes
No
1,
-
Yes
No
1, 2
-
Yes
No
tuple()
-
Yes
No
tuple(1)
-
Yes
No
tuple(1,2)
-
Yes
No
tuple([1,2,3])
-
Yes
No
-
def memory1(): return [].__sizeof__() > ().__sizeof__()
- False
- True
-
def memory2(): l = [] l.append(1) return l.__sizeof__() == [1,2,3,4].__sizeof__()
- False
- True
-
def memory3(): l = [] l.append(1) return l.__sizeof__() == [1,2,3,4,5].__sizeof__()
- False
- True
-
def memory4(): l1 = ['asdfasdlfk jas;ldfsd;lkfj as;ldkfj asl;dkfj asl;kfj '] l2 = [''] return l1.__sizeof__() == l2.__sizeof__()
- False
- True
-
def sets1(): return set([1,2,3]) | {2,3,4}
-
set([1, 2, 3, 4])
-
set([2, 3])
-
-
def sets2(): return {1,2,3} & {2,3,4}
-
set([1, 2, 3, 4])
-
set([2, 3])
-
-
def sets3(): return {1,2,3} - {2,3,4}
-
set([-1])
-
set([1])
-
-
def sets4(): return {1,2,3} ^ {2,3,4}
-
set([1, 2, 3, 4])
-
set([1, 4])
-
set([2, 4, 6])
-
-
def dicts1(): return dict({'a':1}, b=2, c=3)
-
{'a': 1, 'c': 3, 'b': 2}
-
-
def dicts2(): """What does the dicts2 return?""" d = {1:'a', 'b':2, (4, 5):[6, 7]} d.get(4, 'something')
-
'something'
-
6
-
None
-
[6, 7]
-
-
def dicts3(): for k in {1:2, 3:4}: return k
-
1
-
2
-
3
-
4
-
-
def dicts4(): return list({1:2, 3:4})
-
[(1, 2), (3, 4)]
-
[1, 3]
-
[2, 4]
-
-
def dicts(): return 1 in {1:2, 3:4}
- False
- True
- Which of the following can be used as iterators in a for loop?
-
Yes
No
'the quick brown fox'
-
Yes
No
(1,2)
-
Yes
No
(x*x for x in range(10) if x%3 == 1)
-
Yes
No
1 + 1 + 2 + 3
-
Yes
No
1,2,3
-
Yes
No
None
-
Yes
No
open('filename', 'r')
-
Yes
No
open('filename', 'w')
-
Yes
No
os.walk(os.path(os.path.expanduser('~')))
-
Yes
No
xrange(10000000000)
-
Yes
No
{1,2,3}
-
Yes
No
-
def iteration2(): l = [0,1,2,3,4] for i in iter(l.pop, 0): l.insert(0, 0) return l
- [0, 0, 0, 0]
-
def iteration3(): return hasattr([1,2], 'next')
- False
- True
-
def iteration4(): return hasattr(iter([1,2]), 'next')
- False
- True
-
def iteration5(): return hasattr('abc', 'next')
- False
- True
-
def iteration6(): return hasattr((x for x in 'abc'), 'next')
- False
- True
-
def generators1(): "placeholder for more generator quesitons to come" def countdown(n): while n > 0: yield n n -= 1 yield 'blast off' c = countdown(4) c.next() c.next() return c.next()
-
'blast off'
-
1
-
2
-
3
-
4
-
-
def generators2(): def odd(iterable): for x in iterable: if x % 2 == 1: yield x def elevens(): for i in xrange(1000): yield i * 11 return sum(x for i, x in zip(range(3), odd(elevens())))
-
165
-
44
-
66
-
99
-
-
def generators3(): return range(20).__sizeof__() > xrange(1000).__sizeof__()
- False
- True
-
def coroutines1(): def counter(n): while True: passed_in = yield n if passed_in is None: n += 1 else: n = passed_in c = counter(1) return [c.next(), c.send(5), c.next(), c.next()]
-
[1, 2, 3, 4]
-
[1, 2, 5, 6]
-
[1, 2, 6, 7]
-
[1, 2, 6, 7]
-
[1, 5, 2, 3]
-
[1, 5, 6, 7]
-
[1, 6, 7, 8]
-
-
def type1(): return type(1), type('a'), type(lambda: None), type([])
-
(<type 'int'>, <type 'char'>, <type 'function'>, <type 'tuple'>)
-
(<type 'int'>, <type 'str'>, <type 'NoneType'>, <type 'list'>)
-
(<type 'int'>, <type 'str'>, <type 'NoneType'>, <type 'tuple'>)
-
(<type 'int'>, <type 'str'>, <type 'function'>, <type 'list'>)
-
- Which are true of objects in Python?
- Yes No All values in Python are objects
- Yes No Custom types of objects have inherit behavior from only one parent type
- Yes No Internal data
- Yes No Methods that perform operations involving that data
- Yes No Python objects make hiding data from the programmer easy
- Yes No Strings and lists are types of built-in objects
- Yes No The class statement is used to define new types of objects
-
def classes2(): l = [] return dir(l)
-
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
-
- Method names that start and end with double underscores
- Are a great idea, this style should be used for naming new methods
- Are always implemented in the host language (c for cpython)
- Cannot be overridden by custom methods
- Implement various language operations like +
- Use the same implementation for all types of objects
-
def classes4(): """In this code...""" class Stack(object): def __init__(self): self.stack = [] def push(self, thing): self.stack.append(thing) def pop(self): return self.stack.pop() def length(self): return len(self.stack) s = Stack() t = s s.push("Dave") s.push(42) s.push([3,4,5]) x = s.pop() y = s.pop() del s return
- Yes No All operations involving attributes of the object must explicitly refer to the self variable
- Yes No Even though this class definition occurs in a function, the class will be globally accessible
- Yes No Inside the class definition, the def keyword is used to create methods
- Yes No The Stack object to which s referred no longer exists after `del s`
- Yes No The __init__ method is automatically run to when an object of the type Stack is created
- Yes No The first argument passed in to each method will always be the object itself
- Yes No The first parameter of each method is called self, a keyword in python with special rules
- Yes No The variable x refers to [3, 4, 5] by the end of the function
- Yes No `class Stack(object)` means that Stack takes one argument at instantiation
- Yes No `class Stack(object)` means the Stack type of object inherits fron `object`
-
def classes5(): class Stack(list): def push(self, thing): self.append(thing) s = Stack() s.append(1) s.push('a') print s
-
<Stack object>
-
['a', 1]
-
['a']
-
[1, 'a']
-
[1]
-
-
def classes6(): class Foo(object): def __repr__(self): return "<Foo object>" def bar(*args): return args @staticmethod def baz(*args): return args return [Foo.bar(Foo(), 1, 2), Foo().bar(1, 2), Foo.baz(1, 2), Foo().baz(1, 2)]
-
[(1, 2), (1, 2), (1, 2), (1, 2)]
-
[(1, 2), (<Foo object>, 1, 2), (1, 2), (<Foo object>, 1, 2)]
-
[(<Foo object>, 1, 2), (1, 2), (1, 2), (1, 2)]
-
[(<Foo object>, 1, 2), (1, 2), (1, 2), (<Foo object>, 1, 2)]
-
[(<Foo object>, 1, 2), (<Foo object>, 1, 2), (1, 2), (1, 2)]
-
[(<Foo object>, 1, 2), (<Foo object>, 1, 2), (1, 2), (<Foo object>, 1, 2)]
-
-
def exceptions1(): try: undefined_variable except NameError as e: return e
-
NameError("global name 'undefined_variable' is not defined",)
-
- Which of these is a good fit for a context manager?
- Yes No adding 1 to a variable
- Yes No cleanup that ought to happen regardless of whether a section of code is completed normally, or an exception is raised, jumping out of the code.
- Yes No obtaining a lock on a shared resource in a mutlithreading environment, and releasing it afterwards
- Yes No opening a file before working with is, and closing it afterwards
- Yes No recursively traversing a binary search tree
- Yes No temporarily setting a global variable to a value, and restoring its original value afterwards
- Modules...
- Yes No are always written in the host language (for cpython, c)
- Yes No are made accessible via the import statement
- Yes No have the same name as the filename in which their associated code is written
- Yes No written in Python must have a .py suffix
-
from mymodule import MyClass
- Yes No creates a variable called MyClass in the current namespace and binds the class to it
- Yes No creates a variable called mymodule and binds the module object to it
- Yes No executes mymodule
-
from mymodule import MyClass as mc
- Yes No creates a variable called mc in the current namespace and binds the class to it
- Yes No creates a variable called mymodule and binds the module object to it
- Yes No executes mymodule
- The following are real ways to get help in Python:
-
Yes
No
$ pydoc reduce
-
Yes
No
>>> dir(reduce)
-
Yes
No
>>> doc(reduce)
-
Yes
No
>>> help reduce
-
Yes
No
>>> help(reduce)
-
Yes
No
>>> reduce.__doc__
-
Yes
No
>>> reduce.__help__
-
Yes
No
- In a unix-y environment, which of these are required to make a Python script executable from any directory?
- Yes No Add `#!/usr/bin/env python' or similar to the top of the script
- Yes No Add the file to the PATH environmental variable
- Yes No Add the file to the PYTHONPATH environmental variable
- Yes No Put the script in a folder listed in the PATH environmental variable
- Yes No Put the script in a folder listed in the PYTHONPATH environmental variable
- Yes No Set the unix permissions of the file to executable with `chmod u+x`