NEW
Font size
WorksheetsPY4E Finals
Total questions: 49
Worksheet time: 25mins
What does the following Python program print out?
str1 = "Hello"
str2 = 'there'
bob = str1 + str2
print(bob)
Hello there
Hello
0
Hellothere
What does the following Python program print out?
x = '40'
y = int(x) + 2
print(y)
42
402
x2
int402
How would you use the index operator [ ] to print out the letter q from the string?
x = 'From marquard@uct.ac.za'
print x[-1]
print(x[8])
print(x[7])
print(x[9])
How would you use string slicing [ : ] to print out 'uct' from the string?
x = 'From marquard@uct.ac.za'
print(x[15:3])
print(x[14:3])
print(x[14/17])
print(x[15:18])
print(x[14:17])
What is the iteration variable in the following Python code?
for letter in 'banana':
print(letter)
'banana'
for
in
letter
What does the following Python code print out?
print(len('banana') * 7)
banana7
bananabananabananabananabananabananabanana
0
42
How would you print out the following variable in all uppercase in Python?
greet = 'Hello Bob'
console.log(greet.toUpperCase());
puts(greet.ucase);
print(uc($greet));
print(greet.upper())
Which of the following is not a valid string method in Python?
shout()
split()
startswith()
join()
What will the following Python code print out?
data = 'From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008'
pos = data.find('.')
print(data[pos:pos+3])
mar
.ma
Sat
uct
Which of the following string methods removes whitespace from both the beginning and end of a string?
strtrunc()
rltrim()
strip()
wsrem()
Where are files stored?
Main Memory
Motherboard
Machine Language
Secondary Memory
What is stored in a "file handle" that is returned from a successful open() call?
The handle has a list of all the files in a particular folder on the hard drive
The handle is a connection to the file's data
The handle contains the first 10 lines of a file
All the data from the file is read into memory and stored in the handle
What do we use the second parameter of the open() call to indicate?
What disk drive the file is stored on
Whether we want to read data from the file or write data to the file
How large we expect the file to be
The list of folders to be searched to find the file we want to open
What Python function would you use if you wanted to prompt the user for a file name to open?
file_input()
alert()
gets()
input()
What is the purpose of the newline character in text files?
It allows us to open more than one file and read them in a synchronized manner
It indicates the end of one line of text and the beginning of another line of text
It adds a new network connection to retrieve files from the network
It enables random movement throughout the file
If we open a file as follows:
xfile = open('mbox.txt')
while ((line = xfile.readLine()) != null) {
for line in xfile:
while (<xfile>) {
while line = xfile.gets
What is the purpose of the following Python code?
fhand = open('mbox.txt')
x = 0
for line in fhand:
x = x + 1
print(x)
Convert the lines in mbox.txt to lower case
Count the lines in the file 'mbox.txt'
Remove the leading and trailing spaces from each line in mbox.txt
Reverse the order of the lines in mbox.txt
If you see extra blank lines in the output of a file read, what Python string function will likely solve the problem?
trim()
startswith()
rstrip()
ljust()
How would you avoid a traceback and print your own error message for a bad file name?
fname = input('Enter the file name: ')
fhand = open(fname)
setjmp / longjmp
try / except
signal handlers
try / catch / finally
Reads the entire file into the variable inp as a string
Prompts the user for a file name
Checks to see if the file exists and can be written
Turns the text in the file into a graphic image like a PNG or JPG
How are "collection" variables different from normal variables?
Collection variables pull multiple network documents together
Collection variables merge streams of output into a single stream
Collection variables can only store a single value
Collection variables can store multiple values in a single variable
What are the Python keywords used to construct a loop to iterate through a list?
foreach / in
for / in
def / return
try / except
For the following list, how would you print out 'Sally'?
friends = ['Joseph', 'Glenn', 'Sally']
print friends[3]
print(friends['Sally'])
print(friends[2])
print(friends[2:1])
What would the following Python code print out?
fruit = 'Banana'
fruit[0] = 'b'
print(fruit)
[0]
b
B
Nothing would print - the program fails with a traceback error
Banana
Which of the following Python statements would print out the length of a list stored in the variable data?
print(data.length())
print(data.Len)
print(data.length)
print(len(data))
What type of data is produced when you call the range() function?
x = list(range(5))
A list of words
A string
A list of integers
A boolean (true/false) value
What does the following Python code print out?
a = [1, 2, 3]
b = [4, 5, 6]
c = a + b
print(len(c))
15
[1, 2, 3, 4, 5, 6]
6
[1, 2, 3]
21
Which of the following slicing operations will produce the list [12, 3]?
t = [9, 41, 12, 3, 74, 15]
t[12:3]
t[2:4]
t[1:3]
t[2:2]
What list method adds a new item to the end of an existing list?
index()
append()
forward()
add()
What will the following Python code print out?
friends = ['Joseph', 'Glenn', 'Sally']
friends.sort()
print(friends[0])
Glenn
Joseph
Sally
friends
How are Python dictionaries different from Python lists?
Python lists store multiple values and dictionaries store a single value
Python dictionaries are a collection and lists are not a collection
Python lists are indexed using integers and dictionaries can use strings as indexes
Python lists can store strings and dictionaries can only store words
What is a term commonly used to describe the Python dictionary feature in other programming languages?
Sequences
Lambdas
Associative arrays
Closures
What would the following Python code print out?
stuff = dict()
print(stuff['candy'])
candy
0
-1
The program would fail with a traceback.
What would the following Python code print out?
stuff = dict()
print(stuff.get('candy', -1))
0
-1
The program would fail with a traceback
candy
What is a common use of Python dictionaries in a program?
Splitting a line of input into words using a space as a delimiter
Building a histogram counting the occurrences of various strings in a file
Computing an average of a set of numbers
Sorting a list of names into alphabetical order
Which of the following lines of Python is equivalent to the following sequence of statements assuming that counts is a dictionary?
if key in counts:
counts[key] = counts[key] + 1
else:
counts[key] = 1
counts[key] = (key in counts) + 1
counts[key] = (counts[key] * 1) + 1
counts[key] = counts.get(key, 0) + 1
counts[key] = counts.get(key, -1) + 1
In the following Python code, what does the for loop iterate through?
x = dict()
...
for y in x:
...
It loops through the keys in the dictionary
It loops through the integers in the range from zero through the length of the dictionary
It loops through the values in the dictionary
It loops through all of the dictionaries in the program
Which method in a dictionary object gives you a list of the values in the dictionary?
values()
items()
keys()
all()
What is the purpose of the second parameter of the get() method for Python dictionaries?
The key to retrieve
To provide a default value if the key is not found
The value to retrieve
An alternate key to use if the first key cannot be found
What is the difference between a Python tuple and Python list?
Lists maintain the order of the items and tuples do not maintain order
Lists are indexed by integers and tuples are indexed by strings
Tuples can be expanded after they are created and lists cannot
Lists are mutable and tuples are not mutable
Which of the following methods are available for both Python lists and Python tuples?
append()
reverse()
index()
sort()
What will end up in the variable y after this code is executed?
x, y = 3, 4
A two-item list
3
4
A two-item tuple
In the following Python code, what will end up in the variable y?
x = { 'chuck' : 1 , 'fred' : 42, 'jan': 100 }
y = x.items()
A list of strings
A list of integers
A list of tuples
A tuple with three integers
Which of the following tuples is greater than x in the following Python sequence?
x = (5, 1, 3)
if ??? > x :
...
(0, 1000, 2000)
(4, 100, 200)
(5, 0, 300)
(6, 0, 0)
What does the following Python code accomplish, assuming c is a non-empty dictionary?
tmp = list()
for k, v in c.items():
tmp.append((v, k))
It computes the largest of all the values in the dictionary
It sorts the dictionary based on its key values
It creates a list of tuples where each tuple is a value, key pair
It computes the average of all the values in the dictionary
If the variable data is a Python list, how do we sort it in reverse order?
data.sort.reverse()
data.sort(reverse=True)
data = data.sort(-1)
data = sortrev(data)
Using the following tuple, how would you print 'Wed'?
days = ('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun')
print[days(2)]
print(days[1])
print(days{2})
print(days[2])
In the following Python loop, why are there two iteration variables (k and v)?
c = {'a': 10, 'b': 1, 'c': 22}
for k, v in c.items():
...
Because the keys for the dictionary are strings
Because for each item we want the previous and current key
Because the .items() method in dictionaries returns a list of tuples
Because there are two items in the dictionary
Given that Python lists and Python tuples are quite similar, when might you prefer to use a tuple over a list?
For a list of items that will be extended as new items are found
For a temporary variable that you will use and discard without modifying
For a list of items you intend to sort in place
For a list of items that want to use strings as key values instead of integers
