You are on page 1of 49

1.

When Python is running in the interactive mode and displaying the chevron prompt (>>>) - what
question is Python asking you?
What Python statement would you like me to run?
1. Когда Python работает в интерактивном режиме и отображает подсказку шеврона
(>>>) - какой вопрос вам задает Python?
Какой оператор Python вы хотите, чтобы я запустил?
2. What will the following program print out:
>>> x = 15
>>> x = x + 5
>>> print x
20
3. Python scripts (files) have names that end with:
.py
4. Which of these words is a reserved word in Python ?
For, break, if
4. Какое из этих слов является зарезервированным в Python?
For, break, if
5. What is the proper way to say "good-bye" to Python?
quit()
6. Which of the parts of a computer actually executes the program instructions?
Central Processing Unit (CPU)
6. Какая из частей компьютера действительно выполняет инструкции программы?
Центральный процессор (ЦП)
7. What is "code" in the context of this course?
A sequence of instructions in a programming language
7. Что такое «код» в контексте этого курса?
Последовательность инструкций на языке программирования
8. A USB memory stick is an example of which of the following components of computer
architecture?
Secondary Memory
8. Карта памяти USB является примером какого из следующих компонентов компьютерной
архитектуры?
Вторичная память
9. What is the best way to think about a "Syntax Error" while programming?
The computer did not understand the statement that you entered
10. Which of the following is not one of the programming patterns covered in Chapter 1?
Random steps
11. Which of the following is a comment in Python?
# This is a test
12. What does the following code print out?
print("123" + "abc")
123abc
13. Which of the following variables is the "most mnemonic"?
Hours, stop
14. Which of the following is a bad Python variable name?
#spam
15. Which of the following is not a Python reserved word?
speed, spam, iterate
16. What does the following statement do? x = x + 2
Retrieve the current value for x, add two to it and put the sum back into x
17. Which of the following elements of a mathematical expression in Python is evaluated first?
Parenthesis ()
18. What is the value of the following expression? 42 % 10
2
19. What is the value in x after the following statement executes: x = 1 + 2 * 3 - 8 / 4
5
20. What value be in the variable x when the following statement is executed?
x = int(98.6)
98
21. What does the Python raw_input() function do?
Pause the program and read data from the user
21. Что делает функция Python raw_input ()?
Приостановите программу и прочтите данные от пользователя
22. In the following code, print(98.6)
What is 98.6?
A constant
23. In the following code, x=42
What is x?
a variable
24. What do we do to a Python statement that is immediately after an if statement to indicate that
the statement is to be executed only when the if statement is true?
Indent the line below the if statement
25. Which of these operators is not a comparison / logical operator?
=
26. What is true about the following code segment:
if  x == 5 :
    print('Is 5')
    print('Is Still 5')
    print('Third 5')
Depending on the value of x, either all three of the print statements will execute or none of the
statements will execute
27. When you have multiple lines in an if block, how do you indicate the end of the if block?
You de-indent the next line past the if block to the same level of indent as the original if
statement
28. You look at the following text:
if x == 6 :
print 'Is 6'
print 'Is Still 6'
print 'Third 6'
It looks perfect but Python is giving you an 'Indentation Error' on the second print statement.
What is the most likely reason?
You have most likely mixed tabs and spaces in the file
29. What is the Python reserved word that we use in two-way if tests to indicate the block of code
that is to be executed if the logical test is false?
Except, else
30. What will the following code print out?

x=0
if x < 2 :
print 'Small'
elif x < 10 :
print 'Medium'
else :
print 'LARGE'
print 'All done'
Small
All done
31. For the following code,

if x < 2 :
print 'Below 2'
elif x >= 2 :
print 'Two or more'
else :
print 'Something else'
What value of 'x' will cause 'Something else' to print out?

This code will never print 'Something else' regardless of the value for 'x'
32. 'In the following code (numbers added) - which will be the last line to execute successfully?

(1) astr = 'Hello Bob'


(2) istr = int(astr)
(3) print 'First', istr
(4) astr = '123'
(5) istr = int(astr)
(6) print 'Second', istr

1
33. For the following code:

astr = 'Hello Bob'


istr = 0
try:
istr = int(astr)
except: istr = -1
What will the value for istr after this code executes?
-1
34. In Python what is the raw_input() feature best described as?
A built-in function
35. Which Python keyword indicates the start of a function definition?
Def
36. What will the following Python code print out?

def func(x) :

print x

func(10)

func(20)
10
20
37. In Python, how do you indicate the end of the block of code that makes up the function?
You de-indent a line of code to the same indent level as the def keyword
38. In Python what is the input() feature best described as?
a built in function
39. What does the following code print out?
def thing():
print('Hello')

print('There')
There
40. In the following Python code, which of the following is an "argument" to a function?

x = 'banana'

y = max(x)

print y

print x

X
41. In the following Python code, which of the following is an "argument" to a function?

x = 'banana'
y = max(x)
z = y * 2
x
42. What will the following Python code print out?
def func(x) :
    print(x)

func(10)
func(20)
10
20
43. Which line of the following Python program is useless?
def stuff():
print 'Hello'
return
print 'World'

stuff()
print 'World'
44. What will the following Python
program print out?
def greet(lang):
if lang == 'es':
return 'Hola'
elif lang == 'fr':
return 'Bonjour'
else:
return 'Hello'

print greet('fr'),'Michael'
Bonjour Michael
45. What does the following Python code print out? (Note that this is a bit of a trick question and
the code has what many would consider to be a flaw/bug - so read carefully).
def addtwo(a, b):
added = a + b
return a

x = addtwo(2, 7)
print x
2
46. What is the most important benefit of writing your own functions?
Avoiding writing the same non-trivial code more than once in your program

47. What is wrong with this Python loop:


n=5
while n > 0 :
print(n)
print('All done')
This loop will run forever
48. What does the break statement do?
Exits the currently executing loop

49. What does the continue statement do?


Jumps to the "top" of the loop and starts the next iteration

50. What does the following Python program print out?


tot = 0
for i in [5, 4, 3, 2, 1] :
tot = tot + 1
print(tot)
5
51. What is the iteration variable in the following Python code:
friends = ['Joseph', 'Glenn', 'Sally']
for friend in friends :
print('Happy New Year:', friend)
print('Done!')
Friend
52. What is a good description of the following bit of Python code?
zork = 0
for thing in [9, 41, 12, 3, 74, 15] :
zork = zork + thing
print('After', zork)
Sum all the elements of a list

53. What will the following code print out?


smallest_so_far = -1
for the_num in [9, 41, 12, 3, 74, 15] :
if the_num < smallest_so_far :
smallest_so_far = the_num
print(smallest_so_far)
-1
54. What is a good statement to describe the is operator as used in the following if statement:
if smallest is None :
smallest = value
not Looks up 'None' in the smallest variable if it is a string orifThe if statement is a syntax error
55. Which reserved word indicates the start of an "indefinite" loop in Python?
While
56. How many times will the body of the following loop be executed?
n=0
while n > 0 :
print('Lather')
print('Rinse')
print('Dry off!')
not this is an indefinite loop, 0
57. What is the difference between a Python tuple and Python list?
lists are mutable, tuples are immutable. Lists are mutable and tuples are not mutable
58. Which of the following methods work both in Python lists and Python tuples?
index()
59. What will end up in the variable ‘y’ after this code is executed?
x , y = 3, 4
4
60. 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 tuples
61. In the following Python code, what will end up in the variable y?
x = { 'chuck' : 1 , 'fred' : 42, 'jan': 100}
y = x.items()
(6, 0, 0)
62. What does the following Python code accomplish, assuming the c is a non-empty dictionary?
tmp = list()
for k, v in c.items() :
tmp.append( (v, k) )
It creates a list of tuples where each tuple is a value, key pair
63. If the variable data is a Python list, how do we sort it in reverse order?
data.sort(reverse=True)
64. Using the following tuple, how would you print 'Wed'?
days = ('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun')
print(days[2])
65. 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 items() method in dictionaries returns a list of tuples not Because for each item we
want the previous and current key not Because the keys for the dictionary are strings
66. Given that Python lists and Python tuples are quite similar - when might you prefer to use a
tuple over a list?
For a temporary variable that you will use and discard without modifying
67. How are Python dictionaries different from Python lists?
Python lists are indexed using integers and dictionaries can use strings as indexes
68. What is a term commonly used to describe the Python dictionary feature in other programming
languages?
Associative arrays
69. What would the following Python code print out?
stuff = dict()
print(stuff['candy'])
The program would fail with a traceback notcandy
70. What would the following Python code print out?
stuff = dict()
print(stuff.get('candy',-1))
-1 not The program would fail with a traceback
71. (T/F) When you add items to a dictionary they remain in the order in which you added them.
False
72. What is a common use of Python dictionaries in a program?
Building a histogram counting the occurrences of various strings in a file
73. 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] = counts.get(key,0) + 1
74. In the following Python, what does the for loop iterate through?
x = dict()
...
for y in x :
...
It loops through the keys in the dictionary
75. Which method in a dictionary object gives you a list of the values in the dictionary?
values()
76. What is the purpose of the second parameter of the get() method for Python dictionaries?
To provide a default value if the key is not found
77. Which of the following regular expressions would extract 'uct.ac.za' from this string using
re.findall?

\S@
78. What will the '\$' regular expression match?
Dollar sign
79. What would the following mean in a regular expression? [a-z0-9]
Match a lowercase letter or a digit
80. What is the type of the return value of the re.findall() method?
A list of strings
81. What is the "wild card" character in a regular expression (i.e., the character that matches any
character)?
.
82. What is the difference between the "+" and "*" character in regular expressions?
The "+" matches at least one character and the "*" matches zero or more characters
83. What does the "[0-9]+" match in a regular expression?
One or more digits
84. What does the following Python sequence print out?
['From: Using the :']
85. What character do you add to the "+" or "*" to indicate that the match is to be done in a non-
greedy manner?
?
86. Given the following line of text:

stephen.marquard@uct.ac.za
87. Which of the following best describes "Regular Expressions"?
A small programming language unto itself
88. Which of the following is the way we match the "start of a line" in a regular expression?
^
89. What do we call it when a browser uses the HTTP protocol to load a file or page from a server and
display it in the browser?
The Request/Response Cycle
90. What separates the HTTP headers from the body of the HTTP document?
A blank line
91. What must you do in Python before opening a socket?
import socket
92. In a client-server application on the web using sockets, which must come up first?
server
93. Which of the following is most like an open socket in an application?
An "in-progress" phone conversation
94. What does the "H" of HTTP stand for?
HyperText
95. What are the three parts of this URL (Uniform Resource Locator)?
Which application talks first? The client or server?
96. What are the three parts of this URL (Uniform Resource Locator)?

Protocol, host, and document


97. When you click on an anchor tag in a web page like below, what HTTP request is sent to the
server?

Get
98. Which organization publishes Internet Protocol Standards?
IETF
99. Which of the following Python data structures is most similar to the value returned in this line of
Python:

file handle
100. In this Python code, which line actually reads the data?
mysock.recv()
101. In this Python code, which line is most like the open() call to read a file:

mysock.connect()
102. Which HTTP header tells the browser the kind of document that is being returned?
Content-Type:
103. What should you check before scraping a web site?
That the web site allows scraping
104. What is the purpose of the BeautifulSoup Python library?
It repairs and parses HTML to make it easier for a program to understand
105. What ends up in the "x" variable in the following code:

A list of all the anchor tags (<a..) in the HTML from the URL
106. What is the most common Unicode encoding when moving data between systems?
UTF-8
107. What is the decimal (Base-10) numeric value for the upper case letter "G" in the ASCII character
set?
71
108. What word does the following sequence of numbers represent in ASCII:
108, 105, 110, 101
line
109. How are strings stored internally in Python 3?
Unicode
110. When reading data across the network (i.e. from a URL) in Python 3, what method must be used
to convert it to the internal format used by strings?
decode()
111. What is "serialization" when we are talking about web services?
The act of taking data stored in a program and formatting it so it can be sent across the network
112. Which of the following are not commonly used serialization formats?
Dictionaries, TCP, HTTP
113. In this XML, which are the "complex elements"?

people, person
114. In the following XML, which are attributes?

hide, type
115. In the following XML, which node is the parent node of node e

C
116. Looking at the following XML, what text value would we find at path "/a/c/e"

Z
117. What is the purpose of XML Schema?
To establish a contract as to what is valid XML
118. For this XML Schema:
And this XML,

Which tag is incorrect?


Age
119. What does the "Z" mean in this representation of a time:

This time is in the UTC timezone


120. Which of the following dates is in ISO8601 format?
2002-05-30T09:30:10Z
121. Who is credited with the REST approach to web services?
Roy Fielding
122. Which of the following is true about an API?
An API keeps servers running even when the power is off
123. Which of the following is a web services approach used by the Twitter API?
REST
124. What kind of variable will you get in Python when the following JSON is parsed:

A list with three items


125. Which of the following is not true about the service-oriented approach?
An application runs together all in one place
126. If the following JSON were parsed and put into the variable x,

what Python code would extract "Leah Culver" from the JSON?
x["users"]["name"]
127. What library call do you make to append properly encoded parameters to the end of a URL like
the following:
urlib.parse.urlencode()
128. What happens when you exceed the Google geocoding API rate limit?
You cannot use the API for 24 hours
129. What protocol does Twitter use to protect its API?
OAuth
130. What header does Twitter use to tell you how many more API requests you can make before you
will be rate limited?
x-rate-limit-remaining
131. What does the following Python Program print out?

Hellothere
132. What does the following Python program print out?

42
133. How would you use the index operator [] to print out the letter q from the following string?

print(x[8])
134. How would you use string slicing [:] to print out 'uct' from the following string?

print(x[14:17])
135. What is the iteration variable in the following Python code?

letter
136. What does the following Python code print out?

42
137. How would you print out the following variable in all upper case in Python?

print(greet.upper())
138. Which of the following is not a valid string method in Python?
twist()
139. What will the following Python code print out?
.ma
140. Which of the following string methods removes whitespace from both the beginning and end of
a string?
strip()
141. Given the architecture and terminology we introduced in Chapter 1, where are files stored?
Secondary memory
142. What is stored in a "file handle" that is returned from a successful open() call?
The handle is a connection to the file's data
143. What do we use the second parameter of the open() call to indicate?
Whether we want to read data from the file or write data to the file
144. What Python function would you use if you wanted to prompt the user for a file name to open?
input()
145. What is the purpose of the newline character in text files?
It indicates the end of one line of text and the beginning of another line of text
146. If we open a file as follows:

What statement would we use to read the file one line at a time?
For line in xfile:
147. What is the purpose of the following Python code?

Count the lines in the file 'mbox.txt'


148. If you write a Python program to read a text file and you see extra blank lines in the output that
are not present in the file input as shown below, what Python string function will likely solve the
problem?

rstrip()
149. The following code sequence fails with a traceback when the user enters a file that does not
exist. How would you avoid the traceback and make it so you could print out your own error
message when a bad file name was entered?

try / except
150. What does the following Python code do?

Reads the entire file into the variable inp as a string


151. How are "collection" variables different from normal variables?
Collection variables can store multiple values in a single variable
152. What are the Python keywords used to construct a loop to iterate through a list?
for / in
153. For the following list, how would you print out 'Sally'?

print(friends[2])
154. What would the following Python code print out?

Nothing would print - the program fails with a traceback error


155. Which of the following Python statements would print out the length of a list stored in the
variable data?
print(len(data))
156. What type of data is produced when you call the range() function?

A list of integers
157. What does the following Python code print out?

6
158. Which of the following slicing operations will produce the list [12, 3]?

t[2:4]
159. What list method adds a new item to the end of an existing list?
append()
160. What will the following Python code print out?

Glenn
1. Q-1 When Python is running in the interactive mode and displaying the chevron prompt (>>>) – what
question is Python asking you?

answer- What would you like to do?


2. What will the following program print out:

>>> x = 15;

>>> x = x + 5;

>>> print x

answer- 20

3.) Python scripts (files) have names that end with:

answrs- .py

4.) Which of these words are reserved words in Python ?

answer- if

break

5. ) What is the proper way to say “good-bye” to Python?

answer- quit()

6.) Which of the parts of a computer actually executes the program instructions?

answer- Central Processing Unit

7.) What is “code” in the context of this course?

answer- A sequence of instructions in a programming language

8.) A USB memory stick is an example of which of the following components of computer architecture?

answer- Secondary Memory

9.) What is the best way to think about a “Syntax Error” while programming?
answer- The computer did not understand the statement that you entered

10.) Which of the following is not one of the programming patterns covered in Chapter 1?

answer- Random steps

1.) In the following code, print 98.6. What is “98.6”?

answer- A constant

2. In the following code, x = 42. What is “x”?

A variable

3. Which of the following variables is the “most mnemonic”?

hours

4. Which of the following is not a Python reserved word?

speed

5. Assume the variable x has been initialized to an integer value (e.g., x = 3). What does the following
statement do? x = x + 2

Retrieve the current value for x, add two to it and put the sum back into x

6. Which of the following elements of a mathematical expression in Python is evaluated first?

–Parenthesis()

7. What is the value of the following expression

8. What will be the value of x after the following statement executes: x = 1 + 2 * 3 – 8 / 4


5

9. What will be the value of x when the following statement is executed: x = int(98.6)

98

10. What does the Python raw_input() function do?

Pause the program and read data from the user

1 What do we do to a Python statement that is immediately after an if statement to indicate that the
statement is to be executed only when the if statement is true?

ans Indent the line below the if statement

2 Which of these operators is not a comparison / logical operator?

Ans: =

3 What is true about the following code segment: if x == 5 : print ‘Is 5’ print ‘Is Still 5’ print ‘Third 5’

ans Depending on the value of x, either all three of the print statements will execute or none of the
statements will execute

4 When you have multiple lines in an if block, how do you indicate the end of the if block?

ans You de-indent the next line past the if block to the same level of indent as the original if statement

5 You look at the following text: if x == 6 : print ‘Is 6’ print ‘Is Still 6’ print ‘Third 6’. It looks perfect but
Python is giving you an ‘Indentation Error’ on the second print statement. What is the most likely
reason?

ans You have mixed tabs and spaces in the file


6 What is the Python reserved word that we use in two-way if tests to indicate the block of code that is
to be executed if the logical test is false?

ans else

7 What will the following code print out? x = 0 if x < 2 : print ‘Small’ elif x < 10 : print ‘Medium’ else :
print ‘LARGE’ print ‘All done’

ans Small All done

8 For the following code, if x < 2: print ‘Below 2’ elif x >= 2: print ‘Two or more’ else: print ‘Something
else’. What value of ‘x’ will cause ‘Something else’ to print out?

ans This code will never print ‘Something else’ regardless of the value for ‘x’

9 In the following code (numbers added) – which will be the last line to execute successfully? (1) astr =
‘Hello Bob’; (2) istr = int(astr); (3) print ‘First’, istr; (4) astr = ‘123’; (5) istr = int(astr); (6) print ‘Second’,
istr

ans 1

10 For the following code: astr = ‘Hello Bob’ istr = 0 try: istr = int(astr) except: istr = -1. What will the
value be for istr after this code executes?

ans -1

1. Which Python keyword indicates the start of a function definition?

ans- def

2. In Python, how do you indicate the end of the block of code that makes up the function?

ans- You de-indent a line of code to the same indent level as the def keyword

3. In Python what is the raw_input() feature best described as?


ans- A built-in function

4. What does the following code print out? def thing(): print 'Hello'; print 'There'

ans- There

5. In the following Python code, which of the following is an "argument" to a function? x = 'banana'; y =
max(x); print y

ans- x

6. What will the following Python code print out? def func(x) : print x; func(10); func(20)

ans- 10, 20

7. Which line of the following Python program is useless? def stuff(): print 'Hello' return print 'World'
stuff()

ans- print 'World'

8. -What will the following Python program print out? def greet(lang): if lang == 'es': return 'Hola' elif
lang == 'fr': return 'Bonjour' else: return 'Hello' print greet('fr'),'Michael'

ans- Bonjour Michael

9. What does the following Python code print out? (Note that this is a bit of a trick question and the
code has what many would consider to be a flaw/bug - so read carefully). def addtwo(a, b): added = a +
b return a; x = addtwo(2, 7); print x

ans- 2

10. What is the most important benefit of writing your own functions?
ans- Avoiding writing the same non-trivial code more than once in your program

1 What is wrong with this Python loop: n = 5; while n > 0 : print n; print 'All done'

ans This loop will run forever.

2 What does the break statement do?

ans Exits the currently executing loop.

3 What does the continue statement do?

ans Jumps to the "top" of the loop and starts the next iteration.

4 What does the following Python program print out? tot = 0; for i in [5, 4, 3, 2, 1] : tot = tot + 1; print
tot

ans 5

5 What is the iteration variable in the following Python code: friends = ['Joseph', 'Glenn', 'Sally']; for
friend in friends : print 'Happy New Year:', friend; print 'Done!'

ans friend

6 What is a good description of the following bit of Python code?; zork = 0; for thing in [9, 41, 12, 3, 74,
15] : zork = zork + thing; print 'After', zork

ans Sum all the elements of a list

7 What will the following code print out? smallest_so_far = -1; for the_num in [9, 41, 12, 3, 74, 15] : if
the_num < smallest_so_far : smallest_so_far = the_num; print smallest_so_far

ans -1
8 What is a good statement to describe the is operator as used in the following if statement: if smallest
is None : smallest = value

ans matches both type and value

9 Which reserved word indicates the start of an "indefinite" loop in Python?

ans while

10 How many times will the body of the following loop be executed? n = 0; while n > 0 : print 'Lather'
print 'Rinse'; print 'Dry off!'

ans 0

1> What does the following Python Program print out? str1 = "Hello"; str2 = 'there'; bob = str1 + str2;
print bob

sol) Hellothere

2> What does the following Python program print out? x = '40'; y = int(x) + 2; print y

sol) 42

3> How would you use the index operator [] to print out the letter q from the following string? x = 'From
marquard@uct.ac.za'

sol) print(x[8])

4> How would you use string slicing [:] to print out 'uct' from the following string? x = 'From
marquard@uct.ac.za'

sol) print(x[14:17])

5> What is the iteration variable in the following Python code? for letter in 'banana' : print letter

sol) letter

6> What does the following Python code print out? print len('banana')*7
sol) 42

7> How would you print out the following variable in all upper case in Python? greet = 'Hello Bob'

sol) print(greet.upper())

8> Which of the following is not a valid string method in Python?

sol) twist()

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

sol) .ma

10> Which of the following string methods removes whitespace from both the beginning and end of a
string?

sol) strip()

1> Given the architecture and terminology we introduced in Chapter 1, where are files stored?

sol) Secondary memory

2> What is stored in a "file handle" that is returned from a successful open() call?

sol) The handle is a connection to the file's data

3> What do we use the second parameter of the open() call to indicate?

sol) Whether we want to read data from the file or write data to the file

4> What Python function would you use if you wanted to prompt the user for a file name to open?

sol) input()

5> What is the purpose of the newline character in text files?

sol) It indicates the end of one line of text and the beginning of another line of text

6> If we open a file as follows: xfile = open('mbox.txt'). What statement would we use to read the file
one line at a time?
sol) for line in xfile:

7> What is the purpose of the following Python code? fhand = open('mbox.txt'); x = 0; for line in fhand: x
= x + 1; print x

sol) Count the lines in the file 'mbox.txt'

8> If you write a Python program to read a text file and you see extra blank lines in the output that are
not present in the file input as shown below, what Python string function will likely solve the problem?.
From: stephen.marquard@uct.ac.za; From: louis@media.berkeley.edu; From: zqian@umich.edu; From:
rjlowe@iupui.edu ...

sol) strip()

9> The following code sequence fails with a traceback when the user enters a file that does not exist.
How would you avoid the traceback and make it so you could print out your own error message when a
bad file name was entered? fname = raw_input('Enter the file name: '); fhand = open(fname)

sol) try / except

10> What does the following Python code do? fhand = open('mbox-short.txt'); inp = fhand.read()

sol) Reads the entire file into the variable inp as a string

1> How are "collection" variables different from normal variables?

sol) Collection variables can store multiple values in a single variable

2> What are the Python keywords used to construct a loop to iterate through a list?

sol) for/in

3> For the following list, how would you print out 'Sally'? friends = [ 'Joseph', 'Glenn',
'Sally']

sol) print(friends[2])

4> fruit = 'Banana' fruit[0] = 'b'; print(fruit)

sol) Nothing would print the program fails with a traceback


5> Which of the following Python statements would print out the length of a list stored
in the variable data?

sol) print(len(data))

6> What type of data is produced when you call the range() function? x = range(5)

sol) A list of integers

7> What does the following Python code print out? a = [1, 2, 3]; b = [4, 5, 6]; c = a + b;
print len(c)

sol) 6

8> Which of the following slicing operations will produce the list [12, 3]? t = [9, 41, 12, 3,
74, 15]

sol) t[2:4]

9> What list method adds a new item to the end of an existing list?

sol) append()

10> What will the following Python code print out? friends = [ 'Joseph', 'Glenn', 'Sally' ];
friends.sort(); print(friends[0])

sol) Glenn

1> How are Python dictionaries different from Python lists?

sol) Python lists maintain order and dictionaries do not maintain order
2> What is a term commonly used to describe the Python dictionary feature in other programming
languages?

sol) Associative arrays

3> What would the following Python code print out? stuff = dict(); print(stuff['candy'])

sol) The program would fail with a traceback

4> What would the following Python code print out? stuff = dict(); print(stuff.get('candy',-1))

sol) -1

5> (T/F) When you add items to a dictionary they remain in the order in which you added them.

sol) False

6> What is a common use of Python dictionaries in a program?

sol) Building a histogram counting the occurrences of various strings in a file

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

sol) counts[key] = counts.get(key,0) + 1

8> In the following Python, what does the for loop iterate through? x = dict() ... for y in x : ...

sol) It loops through the keys in the dictionary

9> Which method in a dictionary object gives you a list of the values in the dictionary?

sol) values()

10> What is the purpose of the second parameter of the get() method for Python dictionaries?

sol) To provide a default value if the key is not found

1> What is the difference between a Python tuple and Python list?

sol) Lists are mutable and tuples are not mutable


2> Which of the following methods work both in Python lists and Python tuples?

sol) index()

3> What will end up in the variable y after this code is executed? x , y = 3, 4

sol) 4

4> In the following Python code, what will end up in the variable y? x = { 'chuck' : 1 , 'fred' : 42, 'jan':
100}; y = x.items()

sol) A list of tuples

5> Which of the following tuples is greater than x in the following Python sequence? x = (5, 1, 3); if ??? >
x : ...

sol) (6, 0, 0)

6> What does the following Python code accomplish, assuming the c is a non-empty dictionary? tmp =
list(); for k, v in c.items(): tmp.append( (v, k))

sol) It creates a list of tuples where each tuple is a value, key pair

7> If the variable data is a Python list, how do we sort it in reverse order?

sol) data.sort(reverse=True)

8> Using the following tuple, how would you print 'Wed'? days = ('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat',
'Sun')

sol) print(days[2])

9> 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() : ...

sol) Because the items() method in dictionaries returns a list of tuples

10> Given that Python lists and Python tuples are quite similar - when might you prefer to use a tuple
over a list?

sol) For a temporary variable that you will use and discard without modifying

1. Which of the following best describes "Regular Expressions"?

Ans: A way to calculate mathematical values paying attention to operator precedence _> wrong
2. Which of the following is the way we match the "start of a line" in a regular expression?

Ans: ^

3. What would the following mean in a regular expression? [a-z0-9]

Ans: Match an entire line as long as it is lowercase letters or digits _> wrong

4. What is the type of the return value of the re.findall() method?

Ans: A list of strings

5. What is the "wild card" character in a regular expression (i.e., the character that matches any
character)?

Ans: "."

6. What is the difference between the "+" and "*" character in regular expressions?

Ans: The "+" matches at least one character and the "*" matches zero or more characters

7. What does the "[0-9]+" match in a regular expression?

Ans: One or more digits

8. What does the following Python sequence print out?

In [2]:

import re

x = 'From: Using the : character'

y = re.findall('^F.+:', x)

print(y)

['From: Using the :']

Ans: ['From: Using the :']

9. What character do you add to the "+" or "*" to indicate that the match is to be done in a non-greedy
manner?

Ans: ?

10. Given the following line of text:


In [3]:

import re

line = 'From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008'

v = re.findall('\S+?@\S+', line)

print(v)

['stephen.marquard@uct.ac.za']

Ans: stephen.marquard@uct.ac.za

1. What do we call it when a browser uses the HTTP protocol to load a file or page from a server and
display it in the browser?

Ans: The Request/Response Cycle

2. Which of the following is most similar to a TCP port number?

Ans: A telephone extension

3. What must you do in Python before opening a socket?

Ans: import socket

4. Which of the following TCP sockets is most commonly used for the web protocol (HTTP)?

Ans: 80

5. Which of the following is most like an open socket in an application?

Ans: An "in-progress" phone conversation

6. What does the "H" of HTTP stand for?

Ans: HyperText

7. What is an important aspect of an Application Layer protocol like HTTP?

Ans: Which application talks first? The client or server?

8. What are the three parts of this URL (Uniform Resource Locator)?

Ans: Protocol, host, and document


9. When you click on an anchor tag in a web page like below, what HTTP request is sent to the server?

Please click here.

Ans: GET

10. Which organization publishes Internet Protocol Standards?

Ans: IETF

1. Which of the following Python data structures is most similar to the value returned in this line of
Python:

x = urllib.request.urlopen('http://data.pr4e.org/romeo.txt')

/////////////Ans: file handle

2. In this Python code, which line actually reads the data?

In [3]:

import socket

mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

mysock.connect(('data.pr4e.org', 80))

cmd = 'GET http://data.pr4e.org/romeo.txt HTTP/1.0\n\n'.encode()

mysock.send(cmd)

while True:

data = mysock.recv(512)

if (len(data) < 1):

break

print(data.decode())

mysock.close()

HTTP/1.1 400 Bad Request

Date: Fri, 12 Oct 2018 10:26:37 GMT

Server: Apache/2.4.18 (Ubuntu)


Content-Length: 308

Connection: close

Content-Type: text/html; charset=iso-8859-1

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">

<html><head>

<title>400 Bad Request</title>

</head><body>

<h1>Bad Request</h1>

<p>Your browser sent a request that this server could not understand.<br />

</p>

<hr>

<address>Apache/2.4.18 (Ubuntu) Server at do1.dr-chuck.com Port 80</address>

</body></html>

//////////Ans: mysock.recv()

3. Which of the following regular expressions would extract the URL from this line of HTML:

In [6]:

import re

text = '<p>Please click <a href="http://www.dr-chuck.com">here</a></p>'

temp = re.findall('href="(.+)"', text)

print(temp)

['http://www.dr-chuck.com']

///////////////Ans: href="(.+)"

4(wrong). In this Python code, which line is most like the open() call to read a file:

In [8]:

import socket

mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

mysock.connect(('data.pr4e.org', 80))
cmd = 'GET http://data.pr4e.org/romeo.txt HTTP/1.0\n\n'.encode()

mysock.send(cmd)

while True:

data = mysock.recv(512)

if (len(data) < 1):

break

print(data.decode())

mysock.close()

HTTP/1.1 400 Bad Request

Date: Fri, 12 Oct 2018 10:31:02 GMT

Server: Apache/2.4.18 (Ubuntu)

Content-Length: 308

Connection: close

Content-Type: text/html; charset=iso-8859-1

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">

<html><head>

<title>400 Bad Request</title>

</head><body>

<h1>Bad Request</h1>

<p>Your browser sent a request that this server could not understand.<br />

</p>

<hr>

<address>Apache/2.4.18 (Ubuntu) Server at do1.dr-chuck.com Port 80</address>

</body></html>

//////////////Ans: mysock.recv()

5. Which HTTP header tells the browser the kind of document that is being returned?

////////Ans: Content-Type:
6. What should you check before scraping a web site?

////////////Ans: That the web site allows scraping

7. What is the purpose of the BeautifulSoup Python library?

///////////Ans: It repairs and parses HTML to make it easier for a program to understand

8. What ends up in the "x" variable in the following code:

html = urllib.request.urlopen(url).read()

soup = BeautifulSoup(html, 'html.parser')

x = soup('a')

/////////////Ans: A list of all the anchor tags (<a..) in the HTML from the URL

9. What is the most common Unicode encoding when moving data between systems?

/////////Ans: UTF-8

10. What is the decimal (Base-10) numeric value for the upper case letter "G" in the ASCII character set?

In [10]:

print(ord('G'))

71

///////////Ans: 71

11. What word does the following sequence of numbers represent in ASCII:

108, 105, 110, 101

In [11]:

print(ord('l'))

print(ord('p'))
print(ord('t'))

print(ord('f'))

108

112

116

102

In [12]:

print(ord('i'))

print(ord('o'))

105

111

//////////Ans: line

12. How are strings stored internally in Python 3?

In [13]:

help(str)

Help on class str in module builtins:

class str(object)

| str(object='') -> str

| str(bytes_or_buffer[, encoding[, errors]]) -> str

| Create a new string object from the given object. If encoding or

| errors is specified, then the object must expose a data buffer

| that will be decoded using the given encoding and error handler.

| Otherwise, returns the result of object.__str__() (if defined)

| or repr(object).

| encoding defaults to sys.getdefaultencoding().

| errors defaults to 'strict'.

| Methods defined here:

|
| __add__(self, value, /)

| Return self+value.

| __contains__(self, key, /)

| Return key in self.

| __eq__(self, value, /)

| Return self==value.

| __format__(...)

| S.__format__(format_spec) -> str

| Return a formatted version of S as described by format_spec.

| __ge__(self, value, /)

| Return self>=value.

| __getattribute__(self, name, /)

| Return getattr(self, name).

| __getitem__(self, key, /)

| Return self[key].

| __getnewargs__(...)

| __gt__(self, value, /)

| Return self>value.

| __hash__(self, /)

| Return hash(self).

| __iter__(self, /)

| Implement iter(self).
|

| __le__(self, value, /)

| Return self<=value.

| __len__(self, /)

| Return len(self).

| __lt__(self, value, /)

| Return self<value.

| __mod__(self, value, /)

| Return self%value.

| __mul__(self, value, /)

| Return self*value.n

| __ne__(self, value, /)

| Return self!=value.

| __new__(*args, **kwargs) from builtins.type

| Create and return a new object. See help(type) for accurate signature.

| __repr__(self, /)

| Return repr(self).

| __rmod__(self, value, /)

| Return value%self.

| __rmul__(self, value, /)

| Return self*value.

| __sizeof__(...)

| S.__sizeof__() -> size of S in memory, in bytes


|

| __str__(self, /)

| Return str(self).

| capitalize(...)

| S.capitalize() -> str

| Return a capitalized version of S, i.e. make the first character

| have upper case and the rest lower case.

| casefold(...)

| S.casefold() -> str

| Return a version of S suitable for caseless comparisons.

| center(...)

| S.center(width[, fillchar]) -> str

| Return S centered in a string of length width. Padding is

| done using the specified fill character (default is a space)

| count(...)

| S.count(sub[, start[, end]]) -> int

| Return the number of non-overlapping occurrences of substring sub in

| string S[start:end]. Optional arguments start and end are

| interpreted as in slice notation.

| encode(...)

| S.encode(encoding='utf-8', errors='strict') -> bytes

| Encode S using the codec registered for encoding. Default encoding

| is 'utf-8'. errors may be given to set a different error


| handling scheme. Default is 'strict' meaning that encoding errors raise

| a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and

| 'xmlcharrefreplace' as well as any other name registered with

| codecs.register_error that can handle UnicodeEncodeErrors.

| endswith(...)

| S.endswith(suffix[, start[, end]]) -> bool

| Return True if S ends with the specified suffix, False otherwise.

| With optional start, test S beginning at that position.

| With optional end, stop comparing S at that position.

| suffix can also be a tuple of strings to try.

| expandtabs(...)

| S.expandtabs(tabsize=8) -> str

| Return a copy of S where all tab characters are expanded using spaces.

| If tabsize is not given, a tab size of 8 characters is assumed.

| find(...)

| S.find(sub[, start[, end]]) -> int

| Return the lowest index in S where substring sub is found,

| such that sub is contained within S[start:end]. Optional

| arguments start and end are interpreted as in slice notation.

| Return -1 on failure.

| format(...)

| S.format(*args, **kwargs) -> str

| Return a formatted version of S, using substitutions from args and kwargs.

| The substitutions are identified by braces ('{' and '}').


|

| format_map(...)

| S.format_map(mapping) -> str

| Return a formatted version of S, using substitutions from mapping.

| The substitutions are identified by braces ('{' and '}').

| index(...)

| S.index(sub[, start[, end]]) -> int

| Return the lowest index in S where substring sub is found,

| such that sub is contained within S[start:end]. Optional

| arguments start and end are interpreted as in slice notation.

| Raises ValueError when the substring is not found.

| isalnum(...)

| S.isalnum() -> bool

| Return True if all characters in S are alphanumeric

| and there is at least one character in S, False otherwise.

| isalpha(...)

| S.isalpha() -> bool

| Return True if all characters in S are alphabetic

| and there is at least one character in S, False otherwise.

| isdecimal(...)

| S.isdecimal() -> bool

| Return True if there are only decimal characters in S,

| False otherwise.
|

| isdigit(...)

| S.isdigit() -> bool

| Return True if all characters in S are digits

| and there is at least one character in S, False otherwise.

| isidentifier(...)

| S.isidentifier() -> bool

| Return True if S is a valid identifier according

| to the language definition.

| Use keyword.iskeyword() to test for reserved identifiers

| such as "def" and "class".

| islower(...)

| S.islower() -> bool

| Return True if all cased characters in S are lowercase and there is

| at least one cased character in S, False otherwise.

| isnumeric(...)

| S.isnumeric() -> bool

| Return True if there are only numeric characters in S,

| False otherwise.

| isprintable(...)

| S.isprintable() -> bool

| Return True if all characters in S are considered

| printable in repr() or S is empty, False otherwise.


|

| isspace(...)

| S.isspace() -> bool

| Return True if all characters in S are whitespace

| and there is at least one character in S, False otherwise.

| istitle(...)

| S.istitle() -> bool

| Return True if S is a titlecased string and there is at least one

| character in S, i.e. upper- and titlecase characters may only

| follow uncased characters and lowercase characters only cased ones.

| Return False otherwise.

| isupper(...)

| S.isupper() -> bool

| Return True if all cased characters in S are uppercase and there is

| at least one cased character in S, False otherwise.

| join(...)

| S.join(iterable) -> str

| Return a string which is the concatenation of the strings in the

| iterable. The separator between elements is S.

| ljust(...)

| S.ljust(width[, fillchar]) -> str

| Return S left-justified in a Unicode string of length width. Padding is

| done using the specified fill character (default is a space).

|
| lower(...)

| S.lower() -> str

| Return a copy of the string S converted to lowercase.

| lstrip(...)

| S.lstrip([chars]) -> str

| Return a copy of the string S with leading whitespace removed.

| If chars is given and not None, remove characters in chars instead.

| partition(...)

| S.partition(sep) -> (head, sep, tail)

| Search for the separator sep in S, and return the part before it,

| the separator itself, and the part after it. If the separator is not

| found, return S and two empty strings.

| replace(...)

| S.replace(old, new[, count]) -> str

| Return a copy of S with all occurrences of substring

| old replaced by new. If the optional argument count is

| given, only the first count occurrences are replaced.

| rfind(...)

| S.rfind(sub[, start[, end]]) -> int

| Return the highest index in S where substring sub is found,

| such that sub is contained within S[start:end]. Optional

| arguments start and end are interpreted as in slice notation.

| Return -1 on failure.
|

| rindex(...)

| S.rindex(sub[, start[, end]]) -> int

| Return the highest index in S where substring sub is found,

| such that sub is contained within S[start:end]. Optional

| arguments start and end are interpreted as in slice notation.

| Raises ValueError when the substring is not found.

| rjust(...)

| S.rjust(width[, fillchar]) -> str

| Return S right-justified in a string of length width. Padding is

| done using the specified fill character (default is a space).

| rpartition(...)

| S.rpartition(sep) -> (head, sep, tail)

| Search for the separator sep in S, starting at the end of S, and return

| the part before it, the separator itself, and the part after it. If the

| separator is not found, return two empty strings and S.

| rsplit(...)

| S.rsplit(sep=None, maxsplit=-1) -> list of strings

| Return a list of the words in S, using sep as the

| delimiter string, starting at the end of the string and

| working to the front. If maxsplit is given, at most maxsplit

| splits are done. If sep is not specified, any whitespace string

| is a separator.

| rstrip(...)
| S.rstrip([chars]) -> str

| Return a copy of the string S with trailing whitespace removed.

| If chars is given and not None, remove characters in chars instead.

| split(...)

| S.split(sep=None, maxsplit=-1) -> list of strings

| Return a list of the words in S, using sep as the

| delimiter string. If maxsplit is given, at most maxsplit

| splits are done. If sep is not specified or is None, any

| whitespace string is a separator and empty strings are

| removed from the result.

| splitlines(...)

| S.splitlines([keepends]) -> list of strings

| Return a list of the lines in S, breaking at line boundaries.

| Line breaks are not included in the resulting list unless keepends

| is given and true.

| startswith(...)

| S.startswith(prefix[, start[, end]]) -> bool

| Return True if S starts with the specified prefix, False otherwise.

| With optional start, test S beginning at that position.

| With optional end, stop comparing S at that position.

| prefix can also be a tuple of strings to try.

| strip(...)

| S.strip([chars]) -> str

| Return a copy of the string S with leading and trailing


| whitespace removed.

| If chars is given and not None, remove characters in chars instead.

| swapcase(...)

| S.swapcase() -> str

| Return a copy of S with uppercase characters converted to lowercase

| and vice versa.

| title(...)

| S.title() -> str

| Return a titlecased version of S, i.e. words start with title case

| characters, all remaining cased characters have lower case.

| translate(...)

| S.translate(table) -> str

| Return a copy of the string S in which each character has been mapped

| through the given translation table. The table must implement

| lookup/indexing via __getitem__, for instance a dictionary or list,

| mapping Unicode ordinals to Unicode ordinals, strings, or None. If

| this operation raises LookupError, the character is left untouched.

| Characters mapped to None are deleted.

| upper(...)

| S.upper() -> str

| Return a copy of S converted to uppercase.

| zfill(...)

| S.zfill(width) -> str

|
| Pad a numeric string S with zeros on the left, to fill a field

| of the specified width. The string S is never truncated.

| ----------------------------------------------------------------------

| Static methods defined here:

| maketrans(x, y=None, z=None, /)

| Return a translation table usable for str.translate().

| If there is only one argument, it must be a dictionary mapping Unicode

| ordinals (integers) or characters to Unicode ordinals, strings or None.

| Character keys will be then converted to ordinals.

| If there are two arguments, they must be strings of equal length, and

| in the resulting dictionary, each character in x will be mapped to the

| character at the same position in y. If there is a third argument, it

| must be a string, whose characters will be mapped to None in the result.

////////////Ans: Unicode

13. When reading data across the network (i.e. from a URL) in Python 3, what method must be used to
convert it to the internal format used by strings?

////////////Ans: decode()

1. What is the name of the Python 2.x library to parse XML data?

Ans: xml.etree.ElementTree

2. Which of the following are not commonly used serialization formats?

Ans:

 Dictionaries
 HTTP
 TCP

3. In this XML, which are the "simple elements"?

Ans:

 name
 phone

4. In the following XML, which are attributes?

Ans:

 type
 hide

5. In the following XML, which node is the parent node of node e

Ans: c

6. Looking at the following XML, what text value would we find at path "/a/c/e"

Ans: Z

7. What is the purpose of XML Schema?

Ans: To establish a contract as to what is valid XML

8. For this XML Schema:

And this XML,

Which tag is incorrect?

Ans: Age

9. What is a good time zone to use when computers are exchanging data over APIs?

Ans: Universal Time / GMT

10. Which of the following dates is in ISO8601 format?

Ans: 2002-05-30T09:30:10Z
1. Who is credited with getting the JSON movement started?

Ans: Douglas Crockford

2. Which of the following is true about an API?

Ans: An API is a contract that defines how to use a software library

3. Which of the following is a web services approach used by the Twitter API?

Ans: REST

4. What kind of variable will you get in Python when the following JSON is parsed:

{ "id" : "001", "x" : "2", "name" : "Chuck" }

Ans: A dictionary with three key / value pairs

5. Which of the following is not true about the service-oriented approach?

Ans: An application runs together all in one place

6. If the following JSON were parsed and put into the variable x,

{ "users": [ { "status": { "text": "@jazzychad I just bought one .__.", }, "location": "San Francisco,
California", "screen_name": "leahculver", "name": "Leah Culver", }, ...

what Python code would extract "Leah Culver" from the JSON?

Ans: x["users"][0]["name"]

7. What library call do you make to append properly encoded parameters to the end of a URL like the
following:

http://maps.googleapis.com/maps/api/geocode/json?sensor=false&address=Ann+Arbor%2C+MI

Ans: urllib.parse.urlencode()

8. What happens when you exceed the Google geocoding API rate limit?

Ans: You cannot use the API for 24 hours

9. What protocol does Twitter use to protect its API?

Ans: OAuth
10. What header does Twitter use to tell you how many more API requests you can make before you will
be rate limited?

Ans: x-rate-limit-remaining

You might also like