324 |
325 |
326 |
327 |
328 |
329 |
330 |
331 |
332 |
333 |
334 |
335 |
336 |
337 |
338 |
339 |
340 |
341 |
342 |
343 |
344 |
345 |
346 |
347 |
348 |
349 |
350 |
351 |
352 |
353 |
354 |
355 |
356 |
357 |
358 |
359 |
360 |
361 |
362 |
363 |
364 |
365 |
366 |
367 |
368 |
369 |
370 |
371 |
372 |
373 |
374 |
375 |
376 |
377 |
378 |
379 |
380 |
381 |
382 |
383 |
384 |
385 |
386 |
387 |
388 |
389 |
390 |
391 |
392 |
393 |
394 |
395 |
396 |
397 |
398 |
399 |
400 |
401 |
402 |
403 |
404 |
405 |
406 |
407 |
408 |
409 |
410 |
411 |
412 |
413 |
414 |
415 |
416 |
417 |
418 |
419 |
420 |
421 |
422 |
423 |
424 |
425 |
426 |
427 |
428 |
429 |
430 |
431 |
432 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # python-for-everybody
2 | Class notes
3 |
4 |
5 | Course Link (Coursera): https://www.coursera.org/specializations/python
6 |
--------------------------------------------------------------------------------
/wk 10 - assignment 10.2.py:
--------------------------------------------------------------------------------
1 | __author__ = 'edwardlau'
2 | """
3 | 10.2 Write a program to read through the mbox-short.txt and
4 | figure out the distribution by hour of the day for each of the messages.
5 | You can pull the hour out from the 'From ' line by finding the time
6 | and then splitting the string a second time using a colon.
7 | From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
8 | Once you have accumulated the counts for each hour, print out the counts,
9 | sorted by hour as shown below. Note that the autograder
10 | does not have support for the sorted() function.
11 | """
12 |
13 |
14 |
15 | name = raw_input("Enter file:")
16 | if len(name) < 1 : name = "mbox-short.txt"
17 | handle = open(name)
18 |
19 | hcount = dict() #create empty dictionary
20 | hlst = [] #create empty list
21 |
22 | for line in handle:
23 | words = line.split()
24 | if len(words) > 2 and words[0] == 'From': #Select lines with 'From'
25 | hr = words[5].split(':') #Select hour (5th index) and split string with colon
26 | hcount[hr[0]] = hcount.get(hr[0], 0) + 1 #increase count for each hour
27 | else:
28 | continue
29 |
30 | for k,v in hcount.items(): #k = hour, v = count
31 | hlst.append((k,v)) #append tuples to list
32 |
33 | hlst.sort() #sort list by hour
34 | for k,v in hlst: #loop through list of tuples
35 | print(k,v) #print counts sorted by hour
36 |
--------------------------------------------------------------------------------
/wk 10 - quiz.py:
--------------------------------------------------------------------------------
1 | __author__ = 'edwardlau'
2 | """
3 | Question 1
4 | What is the difference between a Python tuple and Python list?
5 | Lists are mutable and tuples are not mutable
6 | Tuples can be expanded after they are created and lists cannot
7 | Lists maintain the order of the items and tuples do not maintain order
8 | Lists are indexed by integers and tuples are indexed by strings
9 | """
10 |
11 | # Answer: Lists are mutable and tuples are not mutable
12 |
13 | """
14 | Question 2
15 | Which of the following methods work both in Python lists and Python tuples?
16 | reverse()
17 | sort()
18 | append()
19 | pop()
20 | index()
21 | """
22 |
23 | # Answer: index()
24 |
25 | """
26 | Question 3
27 | What will end up in the variable y after this code is executed?
28 | x , y = 3, 4
29 | 3
30 | A two item tuple
31 | 4
32 | A dictionary with the key 3 mapped to the value 4
33 | A two item list
34 | """
35 |
36 | # Answer: 4
37 |
38 |
39 | """
40 | Question 4
41 | In the following Python code, what will end up in the variable y?
42 | x = { 'chuck' : 1 , 'fred' : 42, 'jan': 100}
43 | y = x.items()
44 | A list of integers
45 | A list of strings
46 | A list of tuples
47 | A tuple with three integers
48 | """
49 |
50 | # Answer: A list of tuples
51 |
52 |
53 | """
54 | Question 5
55 | Which of the following tuples is greater than x in the following Python sequence?
56 | x = (5, 1, 3)
57 | if ??? > x :
58 | ...
59 | (6, 0, 0)
60 | (4, 100, 200)
61 | (5, 0, 300)
62 | (0, 1000, 2000)
63 | """
64 |
65 | # Answer: (6,0,0)
66 |
67 | """
68 | Question 6
69 | What does the following Python code accomplish, assuming the c is a non-empty dictionary?
70 | tmp = list()
71 | for k, v in c.items() :
72 | tmp.append( (v, k) )
73 | It sorts the dictionary based on its key values
74 | It creates a list of tuples where each tuple is a value, key pair
75 | It computes the largest of all of the values in the dictionary
76 | It computes the average of all of the values in the dictionary
77 | """
78 |
79 | # Answer: It creates a list of tuples where each tuple is a value, key pair
80 |
81 | """
82 | Question 7
83 | If the variable data is a Python list, how do we sort it in reverse order?
84 | data = data.sort(-1)
85 | data.sort(reverse=True)
86 | data.sort.reverse()
87 | data = sortrev(data)
88 | """
89 |
90 | # Answer: data.sort(reverse=True)
91 |
92 | """
93 | Question 8
94 | Using the following tuple, how would you print 'Wed'?
95 | days = ('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun')
96 | print(days[1])
97 | print(days(2))
98 | print(days{2})
99 | print(days.get(1,-1))
100 | print(days[2])
101 | """
102 |
103 | # Answer: print(days[2])
104 |
105 | """
106 | Question 9
107 | In the following Python loop, why are there two iteration variables (k and v)?
108 | c = {'a':10, 'b':1, 'c':22}
109 | for k, v in c.items() :
110 | ...
111 | Because for each item we want the previous and current key
112 | Because the items() method in dictionaries returns a list of tuples
113 | Because there are two items in the dictionary
114 | Because the keys for the dictionary are strings
115 | """
116 |
117 | # Answer: Because the items() method in dictionaries returns a list of tuples
118 |
119 | """
120 | Question 10
121 | Given that Python lists and Python tuples are quite similar - when might you prefer to use a tuple over a list?
122 | For a list of items that want to use strings as key values instead of integers
123 | For a list of items that will be extended as new items are found
124 | For a temporary variable that you will use and discard without modifying
125 | For a list of items you intend to sort in place
126 | """
127 |
128 | # Answer: For a temporary variable that you will use and discard without modifying
129 |
130 |
--------------------------------------------------------------------------------
/wk1 - assignment 1.1.py:
--------------------------------------------------------------------------------
1 | python
2 | print("Hello World")
3 |
--------------------------------------------------------------------------------
/wk1 - bonus - screen 1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ed-lau/python-for-everybody/aa5eabfe8c87b286e88c5d5ad3b0d4e71fb6eb46/wk1 - bonus - screen 1.png
--------------------------------------------------------------------------------
/wk1 - bonus - screen 2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ed-lau/python-for-everybody/aa5eabfe8c87b286e88c5d5ad3b0d4e71fb6eb46/wk1 - bonus - screen 2.png
--------------------------------------------------------------------------------
/wk1 - quiz.py:
--------------------------------------------------------------------------------
1 | Question 1
2 | When Python is running in the interactive mode and displaying the chevron prompt (>>>) -
3 | what question is Python asking you?
4 |
5 | What Python statement would you like me to run?
6 | What is the air-speed velocity of an unladen swallow?
7 | What is the next machine language instruction to run?
8 | What Python script would you like me to run?
9 |
10 | Answer: What Python statement would you like me to run?
11 |
12 | Question 2
13 | What will the following program print out:
14 | >>> x = 15
15 | >>> x = x + 5
16 | >>> print(x)
17 |
18 | 15
19 | 20
20 | x + 5
21 | "print x"
22 | 5
23 |
24 | Answer: 20
25 |
26 | Question 3
27 | Python scripts (files) have names that end with:
28 |
29 | .png
30 | .exe
31 | .py
32 | .doc
33 |
34 | Answer: .py
35 |
36 | Question 4
37 | Which of these words is a reserved word in Python ?
38 |
39 | copy
40 | if
41 | make
42 | names
43 |
44 | Answer: if
45 |
46 | Question 5
47 | What is the proper way to say “good-bye” to Python?
48 |
49 | while
50 | quit()
51 | #EXIT
52 | // stop
53 |
54 | Answer: quit()
55 |
56 | Question 6
57 | Which of the parts of a computer actually execute the program instructions?
58 |
59 | Central Processing Unit
60 | Main Memory
61 | Secondary Memory
62 | Input/Output Devices
63 |
64 | Answer: Central Processing Unit
65 |
66 | Question 7
67 | What is "code" in the context of this course?
68 |
69 | A password we use to unlock Python features
70 | A set of rules that govern the style of programs
71 | A way to encrypt data during World War II
72 | A sequence of instructions in a programming language
73 |
74 | Answer: A sequence of instructions in a programming language
75 |
76 | Question 8
77 | A USB memory stick is an example of which of the following components of computer architecture?
78 |
79 | Central Processing Unit
80 | Secondary Memory
81 | Output Device
82 | Main Memory
83 |
84 | Answer: Secondary Memory
85 |
86 | Question 9
87 | What is the best way to think about a "Syntax Error" while programming?
88 |
89 | The computer is overheating and just wants you to stop to let it cool down
90 | You will never learn how to program
91 | The computer did not understand the statement that you entered
92 | The computer has used GPS to find your location and hates everyone from your town
93 |
94 | Answer: The computer did not understand the statement that you entered
95 |
96 | Question 10
97 | Which of the following is not one of the programming patterns covered in Chapter 1?
98 |
99 | Random steps
100 | Sequential Steps
101 | Conditional Steps
102 | Repeated Steps
103 |
104 | Answer: Random steps
--------------------------------------------------------------------------------
/wk10 - final exam.py:
--------------------------------------------------------------------------------
1 | __author__ = 'edwardlau'
2 | """
3 | Question 1
4 | What will the following Python program print out:
5 | def fred():
6 | print("Zap")
7 |
8 | def jane():
9 | print("ABC")
10 |
11 | fred()
12 | jane()
13 | fred()
14 | """
15 | #Answer: Zap ABC Zap
16 |
17 | """
18 | Question 2
19 | What would the following Python code sequence print?
20 | str = "hello there bob"
21 | print(str[0])
22 | there
23 | hello there bob
24 | h
25 | It would fail with an index error
26 | """
27 | #Answer: h
28 |
29 | """
30 | Question 3
31 | What part of a computer is actually doing the addition and subtraction in the following statement:
32 | x = 1 + 2 - 3 * 4 / 5 + 6
33 | Central Processing Unit
34 | Network Controller
35 | Input Devices
36 | Cloud
37 | """
38 | #Answer: Central Processing Unit
39 |
40 | """
41 | Question 4
42 | Which of the following lines will never print out regardless of the value for x?
43 | if x < 2 :
44 | print("Below 2")
45 | elif x < 0 :
46 | print("Negative")
47 | else :
48 | print("Something else")
49 | All three lines will print all the time
50 | Negative
51 | Something else
52 | Below 2
53 | """
54 | #Answer: Negative
55 |
56 |
57 | """
58 | Question 5
59 | What will the following code print out?
60 | x = 12
61 | if x <= 10:
62 | if x > 4:
63 | print("One")
64 | else:
65 | print("Two")
66 | else:
67 | if x >= 11:
68 | print("Three")
69 | else:
70 | print("Four")
71 | One
72 | Three
73 | Two
74 | Four
75 | """
76 | #Answer: Three
77 |
78 | """
79 | Question 6
80 | What would the following Python print out?
81 | abc = "With three words"
82 | stuff = abc.split()
83 | print(len(stuff))
84 | ['With three words']
85 | 14
86 | 16
87 | ['With', 'three', 'words']
88 | 2
89 | 3
90 | 6
91 | """
92 | #Answer: 3
93 |
94 |
95 | """
96 | Question 7
97 | What would the value of the following expression be:
98 | abc = 1 + 2 - 3 * 4 + 5 - 6 / 3
99 | 36
100 | 0.9675
101 | 42
102 | -6
103 | """
104 | #Answer: -6
105 |
106 |
107 | """
108 | Question 8
109 | What is the primary use of the Python dictionary?
110 | To make sure that the definitions of the Python reserved words are available in different languages (French, Spanish, etc)
111 | To insure that all Python reserved words are properly spelled
112 | To store key / value pairs
113 | To store items in order (like a can of Pringles potato chips)
114 | """
115 |
116 | #Answer: To store key / value pairs
117 |
118 | """
119 | Question 9
120 | What will the following Python program print out:
121 | def fred():
122 | print("Zap")
123 |
124 | def jane():
125 | print("ABC")
126 |
127 | jane()
128 | fred()
129 | jane()
130 | """
131 | #Answer: ABC Zap ABC
132 |
133 | """
134 | Question 10
135 | Which of these is not one of the four types of control flow used in programs:
136 | Conditional
137 | Repeated
138 | Store and Reuse
139 | Fused / Multi-Path
140 | """
141 | Answer: Fused/ Multi-Path
142 |
143 |
144 | """
145 | Question 11
146 | What would happen if the following Python code were executed?
147 | st = "abc"
148 | ix = int(st)
149 | The variable ix would contain 0
150 | The variable ix would contain None
151 | The program would show an error and a traceback on the second line
152 | The variable ix would contain -1
153 | """
154 |
155 | # Answer: The program would show an error and a traceback on the second line
156 |
157 | """
158 | Question 12
159 | What would this code print out?
160 | lst = []
161 | lst.append(4)
162 | lst.append(10)
163 | lst.append(21)
164 | lst.append(6)
165 | print(lst[2])
166 | none of the above
167 | 21
168 | 10
169 | 4
170 | """
171 |
172 | #Answer: 21
173 |
174 | """
175 | Question 13
176 | If all of the following were used in a Python expression, which would have the highest precedence (i.e. which would be evaluated first)?
177 | Subtraction
178 | Modulo (i.e. remainder)
179 | Parenthesis
180 | Addition
181 | """
182 |
183 | # Answer: Parenthesis
184 |
185 | """
186 | Question 14
187 | If you want your program to recover from errors that would otherwise cause a trace back and your program to stop, what language element of Python would you use?
188 | try / except
189 | on_error / goto
190 | repeat / on_error
191 | when / error
192 | """
193 |
194 | # Answer: try/except
195 |
196 | """
197 | Question 15
198 | You develop the following program in Python:
199 | f = int(raw_input("Enter:"))
200 | c = ( f - 32 ) * ( 5 / 9 )
201 | print("Celsius",c)
202 | And when you run it three times you get the following output:
203 | Enter:212
204 | Celsius 0
205 |
206 | Enter:72
207 | Celsius 0
208 |
209 | Enter:15
210 | Celsius 0
211 | What part of the program is causing the output to always be zero?
212 | ( f - 32 )
213 | Using single character variables
214 | Using double quotes for all the strings
215 | ( 5 / 9 )
216 | """
217 |
218 | #Answer: (5/9)
219 |
220 | """
221 | Question 16
222 | For the following Python program, what will it print out?
223 | x = 0
224 | for value in [3, 41, 12, 9, 74, 15] :
225 | if value < 10 :
226 | x = x + value
227 | print(x)
228 | 41
229 | 12
230 | 15
231 | 9
232 | """
233 |
234 | #Answer: 12
235 |
236 | """
237 | Question 17
238 | What would the following Python code print out?
239 | fline = "blah blah"
240 |
241 | if len(fline) > 1 :
242 | print("More than one")
243 | if fline[0] == "h" :
244 | print("Has an h")
245 | print("All done")
246 | More than one
247 | All done
248 | More than one
249 | Has an h
250 | All done
251 | Has an h
252 | All done
253 | Nothing will print
254 | """
255 |
256 | #Answer: More than one, all done
257 |
258 | """
259 | Question 18
260 | What is the value of the following expression:
261 | abc = 1 - 2 + 3 * 4 - 5 - 6 / 3
262 | 4
263 | 18
264 | 42
265 | 0
266 | """
267 |
268 | # Answer: 4
269 |
270 | """
271 | Question 19
272 | What would the following Python code print out?
273 | stx = "hello there bob how are you"
274 | wds = stx.split()
275 | print(wds[2])
276 | bob
277 | are
278 | e
279 | how
280 | """
281 |
282 | # Answer: bob
283 |
284 | """
285 | Question 20
286 | For the following Python program, what will it print out?
287 | x = -1
288 | for value in [3, 41, 12, 9, 74, 15] :
289 | if value < x :
290 | x = value
291 | print(x)
292 | 21
293 | 74
294 | 15
295 | -1
296 | """
297 |
298 | # Answer: -1
--------------------------------------------------------------------------------
/wk2 - assignment 2.2.py:
--------------------------------------------------------------------------------
1 | python
2 |
3 | name = raw_input("Enter your name")
4 | print("Hello" + ' ' + name) # 'space' to add space between words, and () to make python 3 print statement
5 |
--------------------------------------------------------------------------------
/wk2 - assignment 2.3.py:
--------------------------------------------------------------------------------
1 |
2 | # 2.3 Write a program to prompt the user for hours and rate per hour using raw_input to compute gross pay.
3 | # Use 35 hours and a rate of 2.75 per hour to test the program (the pay should be 96.25).
4 | # You should use raw_input to read a string and float() to convert the string to a number.
5 | # Do not worry about error checking or bad user data.
6 |
7 |
8 | # This first line is provided for you
9 |
10 | hrs = raw_input("Enter Hours:")
11 |
12 | rate = raw_input("Enter Rate:")
13 |
14 | hrs = float(hrs)
15 |
16 | rate = float(rate)
17 |
18 | pay = hrs*rate
19 |
20 | print(pay)
--------------------------------------------------------------------------------
/wk2 - quiz.py:
--------------------------------------------------------------------------------
1 |
2 | Question 1
3 | Which of the following is a comment in Python?
4 |
5 | * This is a test
6 | // This is a test
7 | # This is a test
8 | /* This is a test */
9 |
10 |
11 | Answer: # This is a test
12 |
13 | Question 2
14 | What does the following code print out?
15 |
16 | print("123" + "abc")
17 | This is a syntax error because you cannot add strings
18 | hello world
19 | 123abc
20 | 123+abc
21 |
22 | Answer: 123abc
23 |
24 | Question 3
25 | Which of the following is a bad Python variable name?
26 |
27 | spam23
28 | SPAM23
29 | 23spam
30 | spam_23
31 |
32 | Answer: 23spam
33 |
34 | Question 4
35 | Which of the following is not a Python reserved word?
36 | spam
37 | else
38 | for
39 | if
40 |
41 | Answer: spam
42 |
43 | Question 5
44 | What does the following statement do?
45 | x = x + 2
46 |
47 | Exit the program
48 | This would fail as it is a syntax error
49 | Increase the speed of the program by a factor of 2
50 | Retrieve the current value for x, add two to it and put the sum back into x
51 |
52 | Answer: Retrieve the current value for x, add two to it and put the sum back into x
53 |
54 | Question 6
55 | Which of the following elements of a mathematical expression in Python is evaluated first?
56 |
57 | Parenthesis ( )
58 | Subtraction -
59 | Multiplication *
60 | Addition +
61 |
62 | Answer: Parenthesis ( )
63 |
64 | Question 7
65 | What is the value of the following expression
66 | 42 % 10
67 |
68 | Hint - the "%" is the remainder operator
69 | 0.42
70 | 420
71 | 1042
72 | 2
73 |
74 | Answer: 2
75 |
76 |
77 | Question 8
78 | What is the value in x after the following statement executes:
79 | x = 1 + 2 * 3 - 8 / 4
80 |
81 | 5
82 | 4
83 | 15
84 | 8
85 |
86 | Answer: 5
87 |
88 | Question 9
89 | What value be in the variable x when the following statement is executed
90 |
91 | x = int(98.6)
92 | 100
93 | 99
94 | 98
95 | 6
96 |
97 | Answer: 98
98 |
99 | Question 10
100 | What does the Python raw_input() function do?
101 |
102 | Connect to the network and retrieve a web page.
103 | Take a screen shot from an area of the screen
104 | Pause the program and read data from the user
105 | Read the memory of the running program
106 |
107 | Answer: Pause the program and read data from the user
--------------------------------------------------------------------------------
/wk3 - assignment 3.1.py:
--------------------------------------------------------------------------------
1 | 3.1 Write a program to prompt the user for hours and rate per hour using raw_input to compute gross pay. Pay the hourly rate for the hours up to 40 and 1.5 times the hourly rate for all hours worked above 40 hours. Use 45 hours and a rate of 10.50 per hour to test the program (the pay should be 498.75). You should use raw_input to read a string and float() to convert the string to a number. Do not worry about error checking the user input - assume the user types numbers properly.
2 |
3 |
4 | hrs = raw_input("Enter Hours:")
5 | h = float(hrs)
6 |
7 | rate = raw_input("Enter Rate:")
8 | rate = float(rate)
9 |
10 | if h <= 40:
11 | pay = h * rate
12 | elif h > 40:
13 | pay = 40*rate + (h-40)*rate*1.5
14 |
15 | print(pay)
--------------------------------------------------------------------------------
/wk3 - assignment 3.3.py:
--------------------------------------------------------------------------------
1 | 3.3 Write a program to prompt for a score between 0.0 and 1.0. If the score is out of range, print an error. If the score is between 0.0 and 1.0, print a grade using the following table:
2 | Score Grade
3 | >= 0.9 A
4 | >= 0.8 B
5 | >= 0.7 C
6 | >= 0.6 D
7 | < 0.6 F
8 | If the user enters a value out of range, print a suitable error message and exit. For the test, enter a score of 0.85.
9 |
10 | python
11 | number = raw_input("Enter number:")
12 |
13 | try:
14 | number = float(number)
15 | except:
16 | number = -1
17 |
18 | if number >= 0.9:
19 | print("A")
20 | elif number >= 0.8:
21 | print("B")
22 | elif number >= 0.7:
23 | print("C")
24 | elif number >= 0.6:
25 | print("D")
26 | elif number < 0.6:
27 | print("F")
28 | else:
29 | print("Error!")
30 | quit()
31 |
32 |
--------------------------------------------------------------------------------
/wk3 - quiz.py:
--------------------------------------------------------------------------------
1 | Question 1
2 | 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?
3 |
4 | Begin the statement with a curly brace {
5 | Start the statement with a "#" character
6 | Indent the line below the if statement
7 | Underline all of the conditional code
8 |
9 | Answer: Indent the line below the if statement
10 |
11 | Question 2
12 | Which of these operators is not a comparison / logical operator?
13 | =
14 | <
15 | ==
16 | >=
17 | >
18 |
19 | Answer: =
20 |
21 | Question 3
22 | What is true about the following code segment:
23 | if x == 5 :
24 | print('Is 5')
25 | print('Is Still 5')
26 | print('Third 5')
27 | Depending on the value of x, either all three of the print statements will execute or none of the statements will execute
28 | The string 'Is 5' will always print out regardless of the value for x.
29 | The string 'Is 5' will never print out regardless of the value for x.
30 | Only two of the three print statements will print out if the value of x is less than zero.
31 |
32 | Answer: Depending on the value of x, either all three of the print statements will execute or none of the statements will execute
33 |
34 | Question 4
35 | When you have multiple lines in an if block, how do you indicate the end of the if block?
36 |
37 | You de-indent the next line past the if block to the same level of indent as the original if statement
38 | You put the colon : character on a line by itself to indicate we are done with the if block
39 | You use a curly brace { after the last line of the if block
40 | You capitalize the first letter of the line following the end of the if block
41 |
42 | Answer: You de-indent the next line past the if block to the same level of indent as the original if statement
43 |
44 | Question 5
45 | You look at the following text:
46 | if x == 6 :
47 | print('Is 6')
48 | print('Is Still 6')
49 | print('Third 6')
50 | It looks perfect but Python is giving you an 'Indentation Error' on the second print statement. What is the most likely reason?
51 | Python has reached its limit on the largest Python program that can be run
52 | Python thinks 'Still' is a mis-spelled word in the string
53 | You have mixed tabs and spaces in the file
54 | In order to make humans feel inadequate, Python randomly emits 'Indentation Errors' on perfectly good code - after about an hour the error will just go away without any changes to your program
55 |
56 | Answer: You have mixed tabs and spaces in the file
57 |
58 | Question 6
59 | 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?
60 | toggle
61 | switch
62 | else
63 | A closing curly brace followed by an open curly brace like this }{
64 |
65 | Answer: else
66 |
67 | Question 7
68 | What will the following code print out?
69 | x = 0
70 | if x < 2 :
71 | print('Small')
72 | elif x < 10 :
73 | print('Medium')
74 | else :
75 | print('LARGE')
76 | print('All done')
77 | Small
78 | Medium
79 | All done
80 | Small
81 | All done
82 | Small
83 | Medium
84 | LARGE
85 | All done
86 |
87 | Answer: Small// All done
88 |
89 | Question 8
90 | For the following code,
91 | if x < 2 :
92 | print('Below 2')
93 | elif x >= 2 :
94 | print('Two or more')
95 | else :
96 | print('Something else')
97 | What value of 'x' will cause 'Something else' to print out?
98 | x = -22
99 | x = -2.0
100 | This code will never print 'Something else' regardless of the value for 'x'
101 | x = 2.0
102 |
103 | Answer: This code will never print 'Something else' regardless of the value for 'x'
104 |
105 | Question 9
106 | 'In the following code (numbers added) - which will be the last line to execute successfully?
107 | (1) astr = 'Hello Bob'
108 | (2) istr = int(astr)
109 | (3) print('First', istr)
110 | (4) astr = '123'
111 | (5) istr = int(astr)
112 | (6) print('Second', istr)
113 | 5
114 | 1
115 | 6
116 | 2
117 |
118 | Answer: 1
119 |
120 | Question 10
121 | For the following code:
122 | astr = 'Hello Bob'
123 | istr = 0
124 | try:
125 | istr = int(astr)
126 | except:
127 | istr = -1
128 | What will the value for istr after this code executes?
129 | false
130 | It will be a random number depending on the operating system the program runs on
131 | -1
132 | 9 (the number of characters in 'Hello Bob')
133 |
134 | Answer: -1
135 |
--------------------------------------------------------------------------------
/wk4 - assignment 4.6.py:
--------------------------------------------------------------------------------
1 | 4.6 Write a program to prompt the user for hours and rate per hour using raw_input to compute gross pay. Award time-and-a-half for the hourly rate for all hours worked above 40 hours. Put the logic to do the computation of time-and-a-half in a function called computepay() and use the function to do the computation. The function should return a value. Use 45 hours and a rate of 10.50 per hour to test the program (the pay should be 498.75). You should use raw_input to read a string and float() to convert the string to a number. Do not worry about error checking the user input unless you want to - you can assume the user types numbers properly.
2 |
3 | python
4 | def computepay(h,r):
5 | if h > 40:
6 | return (40*r)+(h-40)*(r*1.5)
7 | else:
8 | return h*r
9 |
10 | hrs = raw_input("Enter Hours:")
11 | rate = raw_input("Enter Rate:")
12 |
13 | hrs = float(hrs)
14 | rate = float(rate)
15 |
16 | p = computepay(hrs, rate)
17 | print(p)
--------------------------------------------------------------------------------
/wk4 - quiz.py:
--------------------------------------------------------------------------------
1 | Question 1
2 | Which Python keyword indicates the start of a function definition?
3 | help
4 | rad
5 | break
6 | def
7 |
8 | Answer: def
9 |
10 | Question 2
11 | In Python, how do you indicate the end of the block of code that makes up the function?
12 | You put a # character at the end of the last line of the function
13 | You de-indent a line of code to the same indent level as the def keyword
14 | You add a line that has at least 10 dashes
15 | You put the colon character (:) in the first column of a line
16 |
17 | Answer: You de-indent a line of code to the same indent level as the def keyword
18 |
19 | Question 3
20 | In Python what is the raw_input() feature best described as?
21 | A conditional statement
22 | A data structure that can hold multiple values using strings as keys
23 | A built-in function
24 | A reserved word
25 |
26 | Answer:A built-in function
27 |
28 | What does the following code print out?
29 | def thing():
30 | print('Hello')
31 |
32 | print('There')
33 | thing
34 | Hello
35 | There
36 | There
37 | Hello
38 | def
39 | thing
40 |
41 | Answer: There
42 |
43 | Question 5
44 | In the following Python code, which of the following is an "argument" to a function?
45 | x = 'banana'
46 | y = max(x)
47 | print(y)
48 | print(x)
49 | y
50 | x
51 | print
52 | max
53 |
54 |
55 | Answer: x
56 |
57 |
58 | What will the following Python code print out?
59 | def func(x) :
60 | print(x)
61 |
62 | func(10)
63 | func(20)
64 | 10
65 | 20
66 | x
67 | 10
68 | x
69 | 20
70 | x
71 | x
72 | func
73 | func
74 |
75 | Answer: 10 20
76 |
77 | Question 7
78 | Which line of the following Python program is useless?
79 | def stuff():
80 | print('Hello')
81 | return
82 | print('World')
83 |
84 | stuff()
85 | print('Hello')
86 | def stuff():
87 | stuff()
88 | print('World')
89 | return
90 |
91 | Answer: print("World")
92 |
93 |
94 | Question 8
95 | What will the following Python program print out?
96 | def greet(lang):
97 | if lang == 'es':
98 | return 'Hola'
99 | elif lang == 'fr':
100 | return 'Bonjour'
101 | else:
102 | return 'Hello'
103 |
104 | print(greet('fr'),'Michael')
105 | Bonjour Michael
106 | Hello Michael
107 | def Michael
108 | Hola
109 | Bonjour
110 | Hello
111 | Michael
112 |
113 | Answer: Bonjour Michaels
114 |
115 |
116 | Question 9
117 | 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).
118 | def addtwo(a, b):
119 | added = a + b
120 | return a
121 |
122 | x = addtwo(2, 7)
123 | print(x)
124 | addtwo
125 | 2
126 | 9
127 | Traceback
128 |
129 | Answer: 2
130 |
131 | Question 10
132 | What is the most important benefit of writing your own functions?
133 | To avoid having more than 10 lines of sequential code without an indent or de-indent
134 | Following the rule that whenever a program is more than 10 lines you must use a function
135 | Following the rule that no function can have more than 10 statements in it
136 | Avoiding writing the same non-trivial code more than once in your program
137 |
138 | Answer: Avoiding writing the same non-trivial code more than once in your program
139 |
140 |
--------------------------------------------------------------------------------
/wk5 - assignment 5.2.py:
--------------------------------------------------------------------------------
1 | 5.2 Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'.
2 | Once 'done' is entered, print out the largest and smallest of the numbers.
3 | If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number.
4 | Enter the numbers from the book for problem 5.1 and Match the desired output as shown.
5 | '
6 |
7 | largest = None
8 | smallest = None
9 | while True:
10 | num = raw_input("Enter a number: ")
11 | if num == "done" : break
12 |
13 |
14 | try:
15 | num = int(num)
16 | except:
17 | print("Invalid input")
18 | continue
19 |
20 | if largest is None:
21 | largest = num
22 | elif largest < num:
23 | largest = num
24 |
25 | if smallest is None:
26 | smallest = num
27 | elif smallest > num:
28 | smallest = num
29 |
30 |
31 | print("Maximum is", largest)
32 | print("Minimum is", smallest)
--------------------------------------------------------------------------------
/wk5 - quiz.py:
--------------------------------------------------------------------------------
1 | Question 1
2 | What is wrong with this Python loop:
3 | n = 5
4 | while n > 0 :
5 | print(n)
6 | print('All done')
7 | This loop will run forever
8 | There should be no colon on the while statement
9 | The print 'All done' statement should be indented four spaces
10 | while is not a Python reserved word
11 |
12 | Answer: This loop will run forever
13 |
14 | Question 2
15 | What does the break statement do?
16 | Jumps to the "top" of the loop and starts the next iteration
17 | Resets the iteration variable to its initial value
18 | Exits the currently executing loop
19 | Exits the program
20 |
21 | Answer: Exits the currently executing loop
22 |
23 | Question 3
24 | What does the continue statement do?
25 | Resets the iteration variable to its initial value
26 | Exits the currently executing loop
27 | Jumps to the "top" of the loop and starts the next iteration
28 | Exits the program
29 |
30 | Answer: Jumps to the "top" of the loop and starts the next iteration
31 |
32 | Question 4
33 | What does the following Python program print out?
34 | tot = 0
35 | for i in [5, 4, 3, 2, 1] :
36 | tot = tot + 1
37 | print(tot)
38 | 0
39 | 5
40 | 10
41 | 15
42 |
43 | Answer: 5
44 |
45 | Question 5
46 | What is the iteration variable in the following Python code:
47 | friends = ['Joseph', 'Glenn', 'Sally']
48 | for friend in friends :
49 | print('Happy New Year:', friend)
50 | print('Done!')
51 | friend
52 | friends
53 | Sally
54 | Joseph
55 |
56 | Answer: friend
57 |
58 |
59 | Question 6
60 | What is a good description of the following bit of Python code?
61 | zork = 0
62 | for thing in [9, 41, 12, 3, 74, 15] :
63 | zork = zork + thing
64 | print('After', zork)
65 | Sum all the elements of a list
66 | Find the smallest item in a list
67 | Count all of the elements in a list
68 | Compute the average of the elements in a list
69 |
70 | Answer: Sum all the elements of a list
71 |
72 | Question 7
73 | What will the following code print out?
74 | smallest_so_far = -1
75 | for the_num in [9, 41, 12, 3, 74, 15] :
76 | if the_num < smallest_so_far :
77 | smallest_so_far = the_num
78 | print(smallest_so_far)
79 | Hint: This is a trick question and most would say this code has a bug - so read carefully
80 | -1
81 | 3
82 | 74
83 | 42
84 |
85 | Answer: -1
86 |
87 | Question 8
88 | What is a good statement to describe the is operator as used in the following if statement:
89 | if smallest is None :
90 | smallest = value
91 | The if statement is a syntax error
92 | matches both type and value
93 | Is true if the smallest variable has a value of -1
94 | Looks up 'None' in the smallest variable if it is a string
95 |
96 | Answer: matches both type and value
97 |
98 | Question 9
99 | Which reserved word indicates the start of an "indefinite" loop in Python?
100 | while
101 | def
102 | break
103 | for
104 | indef
105 |
106 | Answer: while
107 |
108 | Question 10
109 | How many times will the body of the following loop be executed?
110 | n = 0
111 | while n > 0 :
112 | print('Lather')
113 | print('Rinse')
114 | print('Dry off!')
115 | 1
116 | 0
117 | 5
118 | This in an infinite loop
119 | Answer: 0
--------------------------------------------------------------------------------
/wk6 - assignment 6.5.py:
--------------------------------------------------------------------------------
1 | #6.5 Write code using find() and string slicing (see section 6.10) to extract the number at the end of the line below.
2 | #Convert the extracted value to a floating point number and print it out.
3 |
4 | text = "X-DSPAM-Confidence: 0.8475"
5 | start = text.find('0')
6 | result =float(text[start : ])
7 | print (result)
8 |
9 |
--------------------------------------------------------------------------------
/wk6 - quiz.py:
--------------------------------------------------------------------------------
1 | Question 1
2 | What does the following Python Program print out?
3 | str1 = "Hello"
4 | str2 = 'there'
5 | bob = str1 + str2
6 | print(bob)
7 | Hello
8 | Hellothere
9 | 0
10 | Hello
11 | there
12 |
13 | Answer: Hellothere
14 |
15 |
16 | Question 2
17 | What does the following Python program print out?
18 | x = '40'
19 | y = int(x) + 2
20 | print(y)
21 | 42
22 | x2
23 | 402
24 | int402
25 |
26 | Answer: 42
27 |
28 | Question 3
29 | How would you use the index operator [] to print out the letter q from the following string?
30 | x = 'From marquard@uct.ac.za'
31 | print(x[9])
32 | print(x[q])
33 | print(x[-1])
34 | print(x[7])
35 | print(x[8])
36 |
37 |
38 | Answer: print(x[8])
39 |
40 | Question 4
41 | How would you use string slicing [:] to print out 'uct' from the following string?
42 | x = 'From marquard@uct.ac.za'
43 | print(x[14:3])
44 | print(x[14+17])
45 | print(x[15:18])
46 | print(x[14:17])
47 | print(x[14/17])
48 | print(x[15:3])
49 |
50 | Answer: print(x[14:17])
51 |
52 | Question 5
53 | What is the iteration variable in the following Python code?
54 | for letter in 'banana' :
55 | print(letter)
56 | for
57 | letter
58 | print
59 | 'banana'
60 | in
61 |
62 | Answer: letter
63 |
64 | Question 6
65 | What does the following Python code print out?
66 | print(len('banana')*7)
67 | -1
68 | banana banana banana banana banana banana banana
69 | 0
70 | 42
71 |
72 | Answer: 42
73 |
74 |
75 | How would you print out the following variable in all upper case in Python?
76 | greet = 'Hello Bob'
77 |
78 | puts greet.ucase;
79 |
80 | console.log(greet.toUpperCase());
81 |
82 | print(uc($greet);)
83 |
84 | print(greet.upper())
85 |
86 | Answer: print(greet.upper())
87 |
88 | Question 8
89 | Which of the following is not a valid string method in Python?
90 | join()
91 | upper()
92 | twist()
93 | lstrip()
94 |
95 | Answer: twist
96 |
97 | Question 9
98 | What will the following Python code print out?
99 | data = 'From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008'
100 | pos = data.find('.')
101 | print(data[pos:pos+3])
102 | .ma
103 | mar
104 | Sat
105 | 09:14
106 |
107 | Answer: .ma
108 |
109 | Question 10
110 | Which of the following string methods removes whitespace from both the beginning and end of a string?
111 | strip()
112 | wsrem()
113 | strtrunc()
114 | split()
115 |
116 | Answer: strip()
--------------------------------------------------------------------------------
/wk7 - assignment 7.1.py:
--------------------------------------------------------------------------------
1 | 7.1 Write a program that prompts for a file name, then opens that file and reads through the file, and print the contents of the file in upper case. Use the file words.txt to produce the output below.
2 | You can download the sample data at http://www.pythonlearn.com/code/words.txt
3 |
4 | # Use words.txt as the file name
5 | fname = raw_input("Enter file name: ")
6 | fh = open(fname)
7 |
8 | for line in fh:
9 | line = line.rstrip()
10 | line = line.upper()
11 | print(line)
12 |
13 |
--------------------------------------------------------------------------------
/wk7 - assignment 7.2.py:
--------------------------------------------------------------------------------
1 | 7.2 Write a program that prompts for a file name, then opens that file and reads through the file, looking for lines of the form:
2 | X-DSPAM-Confidence: 0.8475
3 | Count these lines and extract the floating point values from each of the lines and compute the average
4 | of those values and produce an output as shown below.
5 | You can download the sample data at http://www.pythonlearn.com/code/mbox-short.txt when
6 | you are testing below enter mbox-short.txt as the file name.
7 |
8 |
9 | # Use the file name mbox-short.txt as the file name
10 | fname = input("Enter file name: ")
11 | fh = open(fname)
12 | sum = 0.0
13 | count = 0
14 |
15 | for line in fh:
16 | if not line.startswith("X-DSPAM-Confidence:") :
17 | continue
18 | else:
19 | sum = sum + float(line[20:])
20 | count = count + 1
21 |
22 | print("Average spam confidence:", sum/count)
23 |
24 |
--------------------------------------------------------------------------------
/wk7 - quiz.py:
--------------------------------------------------------------------------------
1 | Question 1
2 | Given the architecture and terminology we introduced in Chapter 1, where are files stored?
3 | Motherboard
4 | Central Processor
5 | Machine Language
6 | Secondary memory
7 |
8 | Answer: Secondary memory
9 |
10 | Question 2
11 | What is stored in a "file handle" that is returned from a successful open() call?
12 | The handle has a list of all of the files in a particular folder on the hard drive
13 | The handle is a connection to the file's data
14 | The handle contains the first 10 lines of a file
15 | All the data from the file is read into memory and stored in the handle
16 |
17 | Answer: The handle is a connection to the file's data
18 |
19 | Question 3
20 | What do we use the second parameter of the open() call to indicate?
21 | How large we expect the file to be
22 | The list of folders to be searched to find the file we want to open
23 | Whether we want to read data from the file or write data to the file
24 | What disk drive the file is stored on
25 |
26 | Answer: Whether we want to read data from the file or write data to the file
27 |
28 | Question 4
29 | What Python function would you use if you wanted to prompt the user for a file name to open?
30 | file_input()
31 | read()
32 | input()
33 | cin
34 |
35 | Answer: input()
36 |
37 | Question 5
38 | What is the purpose of the newline character in text files?
39 | It adds a new network connection to retrieve files from the network
40 | It indicates the end of one line of text and the beginning of another line of text
41 | It enables random movement throughout the file
42 | It allows us to open more than one files and read them in a synchronized manner
43 |
44 | Answer: It indicates the end of one line of text and the beginning of another line of text
45 |
46 | Question 6
47 | If we open a file as follows:
48 | xfile = open('mbox.txt')
49 | What statement would we use to read the file one line at a time?
50 |
51 | for line in xfile:
52 | while ( getline (xfile,line) ) {
53 | READ xfile INTO LINE
54 | READ (xfile,*,END=10) line
55 |
56 | Answer: for line in xfile
57 |
58 | Question 7
59 | What is the purpose of the following Python code?
60 | fhand = open('mbox.txt')
61 | x = 0
62 | for line in fhand:
63 | x = x + 1
64 | print(x)
65 | Count the lines in the file 'mbox.txt'
66 | Reverse the order of the lines in mbox.txt
67 | Remove the leading and trailing spaces from each line in mbox.txt
68 | Convert the lines in mbox.txt to upper case
69 |
70 | Answer: Count the lines in the file 'mbox.txt'
71 |
72 | Question 8
73 | 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?
74 | From: stephen.marquard@uct.ac.za
75 |
76 | From: louis@media.berkeley.edu
77 |
78 | From: zqian@umich.edu
79 |
80 | From: rjlowe@iupui.edu
81 | ...
82 | find()
83 | startswith()
84 | rstrip()
85 | split()
86 | Answer: rstrip()
87 |
88 | Question 9
89 | 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?
90 | fname = raw_input('Enter the file name: ')
91 | fhand = open(fname)
92 | try / except
93 | signal handlers
94 | try / catch / finally
95 | on error resume next
96 |
97 | Answer: try/ except
98 |
99 | Question 10
100 | What does the following Python code do?
101 | fhand = open('mbox-short.txt')
102 | inp = fhand.read()
103 | Checks to see if the file exists and can be written
104 | Turns the text in the file into a graphic image like a PNG or JPG
105 | Reads the entire file into the variable inp as a string
106 | Prompts the user for a file name
107 |
108 | Answer: Reads the entire file into the variable inp as a string
109 |
110 |
111 |
--------------------------------------------------------------------------------
/wk8 - assignment 8.4.py:
--------------------------------------------------------------------------------
1 | fname = input("Enter file name: ")
2 | fh = open(fname)
3 | data=[]
4 | for each in fh:
5 | words=each.split()
6 | for word in words:
7 | if word not in data:
8 | data.append(word)
9 | print(sorted(data))
10 |
--------------------------------------------------------------------------------
/wk8 - assignment 8.5.py:
--------------------------------------------------------------------------------
1 | fname = input("Enter file name: ")
2 | if len(fname) < 1 : fname = "mbox-short.txt"
3 | #opening the file
4 | fh = open(fname)
5 | count = 0
6 | #to store the lines
7 | data=[]
8 | for each in fh:
9 | # To check whether the line have more than two elements space seperated
10 | if each.startswith("From") and len(each.split())>2:
11 | temp=each.split()
12 | data.append(temp[1])
13 | for each in data:
14 | print(each)
15 | print("There were", len(data), "lines in the file with From as the first word")
16 |
--------------------------------------------------------------------------------
/wk8 - quiz.py:
--------------------------------------------------------------------------------
1 | ###
2 | Question 1
3 | How are "collection" variables different from normal variables?
4 | Collection variables can only store a single value
5 | Collection variables can store multiple values in a single variable
6 | Collection variables merge streams of output into a single stream
7 | Collection variables pull multiple network documents together
8 |
9 | Answer: Collection variables can store multiple values in a single variable
10 |
11 | Question 2
12 | What are the Python keywords used to construct a loop to iterate through a list?
13 | for / in
14 | foreach / in
15 | try / except
16 | def / return
17 |
18 | Answer: for/in
19 |
20 | Question 3
21 | For the following list, how would you print out 'Sally'?
22 | friends = [ 'Joseph', 'Glenn', 'Sally' ]
23 | print(friends[2])
24 | print(friends[3])
25 | print(friends[2:1])
26 | print(friends['Sally'])
27 |
28 | Answer: print(friends[2])
29 |
30 | Question 4
31 | What would the following Python code print out?
32 | fruit = 'Banana'
33 | fruit[0] = 'b'
34 | print(fruit)
35 | Nothing would print - the program fails with a traceback
36 | b
37 | banana
38 | Banana
39 | B
40 |
41 | Answer: Nothing would print - the program fails with a traceback
42 |
43 | Question 5
44 | Which of the following Python statements would print out the length of a list stored in the variable data?
45 | print(data.length())
46 | print(len(data))
47 | print(data.length)
48 | print(strlen(data))
49 | print(length(data))
50 | print(data.Len)
51 |
52 | Answer: print(len(data))
53 |
54 | Question 6
55 | What type of data is produced when you call the range() function?
56 | x = range(5)
57 | A boolean (true/false) value
58 | A list of words
59 | A list of integers
60 | A string
61 | A list of characters
62 |
63 | Answer: A list of integers
64 |
65 | Question 7
66 | What does the following Python code print out?
67 | a = [1, 2, 3]
68 | b = [4, 5, 6]
69 | c = a + b
70 | print(len(c))
71 | [1, 2, 3, 4, 5, 6]
72 | [1, 2, 3]
73 | 21
74 | [4, 5, 6]
75 | 15
76 | 6
77 |
78 | Answer: 6
79 |
80 | Question 8
81 | Which of the following slicing operations will produce the list [12, 3]?
82 | t = [9, 41, 12, 3, 74, 15]
83 | t[12:3]
84 | t[1:3]
85 | t[2:2]
86 | t[:]
87 | t[2:4]
88 |
89 | Answer: t[2:4]
90 |
91 | Question 9
92 | What list method adds a new item to the end of an existing list?
93 | push()
94 | index()
95 | pop()
96 | forward()
97 | add()
98 | append()
99 |
100 | Answer: append()
101 |
102 | Question 10
103 | What will the following Python code print out?
104 | friends = [ 'Joseph', 'Glenn', 'Sally' ]
105 | friends.sort()
106 | print(friends[0])
107 | Joseph
108 | Sally
109 | Glenn
110 | friends
111 |
112 | Answer: Glenn
--------------------------------------------------------------------------------
/wk9 - assignment 9.4.py:
--------------------------------------------------------------------------------
1 | __author__ = 'edwardlau'
2 |
3 |
4 | """
5 | 9.4 Write a program to read through the mbox-short.txt and
6 | figure out who has the sent the greatest number of mail messages.
7 | The program looks for 'From ' lines and takes the second word of those
8 | lines as the person who sent the mail. The program creates a Python dictionary
9 | that maps the sender's mail address to a count of the number of times they appear in
10 | the file. After the dictionary is produced,
11 | the program reads through the dictionary using a maximum loop to find the most prolific committer.
12 |
13 |
14 |
15 | name = input("Enter file:")
16 | if len(name) < 1 : name = "mbox-short.txt"
17 | text = open(name)
18 |
19 | maxauthor = dict()
20 |
21 | for line in text:
22 | line.rstrip()
23 | if not line.startswith("From "): continue
24 | words = line.split()
25 | maxauthor[words[1]] = maxauthor.get(words[1],0)+1
26 |
27 | largest = None
28 | largest_author = None
29 |
30 | for key in maxauthor:
31 | if largest is None: largest = maxauthor[key]
32 |
33 | if largest < maxauthor[key]:
34 | largest = maxauthor[key]
35 | largest_author = key
36 |
37 | print(largest_author, largest)
38 |
--------------------------------------------------------------------------------
/wk9 - quiz.py:
--------------------------------------------------------------------------------
1 | __author__ = 'edwardlau'
2 | """
3 | Question 1
4 | How are Python dictionaries different from Python lists?
5 | Python lists are indexed using integers and dictionaries can use strings as indexes
6 | Python dictionaries are a collection and lists are not a collection
7 | Python lists can store strings and dictionaries can only store words
8 | Python lists store multiple values and dictionaries store a single value
9 | """
10 |
11 | # Answer: Python lists are indexed using integers and dictionaries can use strings as indexes
12 |
13 | """
14 | Question 2
15 | What is a term commonly used to describe the Python dictionary feature in other programming languages?
16 | Closures
17 | Sequences
18 | Associative arrays
19 | Lambdas
20 | """
21 |
22 | # Answer: Associative arrays
23 |
24 | """
25 | Question 3
26 | What would the following Python code print out?
27 | """
28 |
29 | stuff = dict()
30 | print(stuff['candy'])
31 |
32 | """
33 | The program would fail with a traceback
34 | 0
35 | -1
36 | candy
37 | """
38 |
39 | # Answer: The program would fail with a traceback
40 |
41 | """
42 | Question 4
43 | What would the following Python code print out?
44 | stuff = dict()
45 | print(stuff.get('candy',-1))
46 | The program would fail with a traceback
47 | 'candy'
48 | 0
49 | -1
50 | """
51 |
52 | # Answer: -1
53 |
54 | """
55 | Question 5
56 | (T/F) When you add items to a dictionary they remain in the order in which you added them.
57 | False
58 | True
59 | """
60 |
61 | # Answer: False
62 |
63 | """
64 | Question 6
65 | What is a common use of Python dictionaries in a program?
66 | Computing an average of a set of numbers
67 | Sorting a list of names into alphabetical order
68 | Building a histogram counting the occurrences of various strings in a file
69 | Splitting a line of input into words using a space as a delimiter
70 | """
71 |
72 | # Answer: Building a histogram counting the occurrences of various strings in a file
73 |
74 | """
75 | Question 7
76 | Which of the following lines of Python is equivalent to the following sequence of statements assuming that counts is a dictionary?
77 | if key in counts:
78 | counts[key] = counts[key] + 1
79 | else:
80 | counts[key] = 1
81 | counts[key] = counts.get(key,0) + 1
82 | counts[key] = counts.get(key,-1) + 1
83 | counts[key] = (key in counts) + 1
84 | counts[key] = key + 1
85 | counts[key] = (counts[key] * 1) + 1
86 | """
87 |
88 | # Answer: counts[key] = counts.get(key,0) + 1
89 |
90 | """
91 | Question 8
92 | In the following Python, what does the for loop iterate through?
93 | x = dict()
94 | ...
95 | for y in x :
96 | ...
97 | It loops through the integers in the range from zero through the length of the dictionary
98 | It loops through all of the dictionaries in the program
99 | It loops through the values in the dictionary
100 | It loops through the keys in the dictionary
101 | """
102 | # Answer: It loops through the keys in the dictionary
103 |
104 | """
105 | Question 9
106 | Which method in a dictionary object gives you a list of the values in the dictionary?
107 | items()
108 | keys()
109 | values()
110 | all()
111 | each()
112 | """
113 |
114 | # Answer: values()
115 |
116 | """
117 | Question 10
118 | What is the purpose of the second parameter of the get() method for Python dictionaries?
119 | An alternate key to use if the first key cannot be found
120 | The value to retrieve
121 | To provide a default value if the key is not found
122 | The key to retrieve
123 | """
124 |
125 | # Answer: To provide a default value if the key is not found
126 |
127 |
128 |
--------------------------------------------------------------------------------