CPT 168 Final Review Flashcards

1
Q

The __________ software for a computer provides the software that’s needed for running applications.

A

systems

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

The data in __________ is persistent so it is not lost when an application ends.

A

disk storage

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

To create a Python program, you use:

A

IDLE’s editor

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q
The following is an example of \_\_\_\_\_\_\_\_\_\_.
print("Hello out there!")
# get input
name = input("Who are you?")
print("Goodbye, " , name)
A

source code

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

A console application runs

A

via a command prompt

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

The data in __________ is lost when an application ends.

A

main memory

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Python is considered a good first language to learn because:

A

all of the above

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

A runtime error is also known as:

A

an exception

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

When an exception occurs while a program is running,

A

the program crashes and an error message is displayed

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

To run a Python program from IDLE, you use:

A

the F5 key

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

The goal of __________ is to fix all the errors in a program.

A

debugging

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

To test a Python statement, you use:

A

IDLE’s interactive shell

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Which of the following translates bytecode into instructions for the computer?

A

the Python virtual machine

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

A web application runs

A

through a browser

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q
The following is an example of \_\_\_\_\_\_\_\_\_\_.
     #!/usr/bin/env python 3
A

a shebang line

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Which type of errors must be fixed before the program can be compiled?

A

syntax errors

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

The goal of __________ is to find all the errors in a program.

A

testing

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Given that pi = 3.1415926535, which of the following print() functions displays:
pi = 3.14

A

print(“pi = “ + str(round(pi, 2)))

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Given: x = 23 , y = 15
What is the value of new_num after the following statement executes?
new_num = x % y

A

8

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

Given: x = 23 , y = 15
What is the value of new_num after the following statement executes?
new_num = x // y

A

1

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

Given: x = 7 , y = 2 , z = 1.5
What is the value of new_num after the following statement executes?
new_num = x / y + z

A

5.0

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

Python comments

A

all of the above

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

Python relies on correct __________ to determine the meaning of a statement.

A

indentation

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

What is the argument of the print() function in the following Python statement?
print(“My student ID is “ + str(123456) )

A

“My student ID is “ + str(123456)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
What is the value of my_num after the following statement executes? my_num = (50 + 2 * 10 - 4) / 2
33
26
``` What is the value of my_num after the following statements execute? my_num = 5 my_num += 20 my_num -= 12 my_num *= 0.5 ```
6.5
27
What is the value of number after the following statement executes? number = (5 ** 2) * ((10 - 4) / 2)
75
28
What will be the result of the following code if the user enters 81 at the prompt? score_curve = 7 score = input("Enter your score on the exam: ") score_curve += score print(score_curve)
error: you cannot use the += operator to add a string variable to an int value
29
What will display after the following print() function is executed? print("Welcome!\nNow that you have learned about", "input\nand output, you may be wondering,\"What\nis", "next?\"")
Welcome! Now that you have learned about input and output, you may be wondering, "What is next?"
30
What will the following print() function display? | print("lions", "tigers", "bears", sep = ' & ', end = ' oh, my!!')
lions & tigers & bears oh, my!!
31
What, if anything, is wrong with this code? my_age = input("Enter your age: ") myNewAge = int(my_age) + 5 print("In 5 years you will be", myNewAge, ".")
nothing is wrong with this code
32
What, if anything, is wrong with this code? rating = input("Enter the rating for this product: ") rating = rating + 2 print("The adjusted rating is " + rating + ".")
a string variable is used in an arithmetic expression
33
What, if anything, is wrong with this code? student_score = int(input("Enter this student's score: ")) score = student_score + 5 print("With the 5-point curve, the student’s score is ", scores, ".")
an undeclared variable name is used in the print() function
34
Which of the following data types would you use to store the number 25.62?
float
35
Which of the following doesn’t follow the best naming practices for variables?
pRate
36
Which of the following variable names uses camel case?
firstName
37
Which of the following will get a floating-point number from the user?
my_number = float(input("Enter a number:"))
38
A for loop that uses a range() function is executed
once for each integer in the collection returned by the range() function
39
Code Example 3-1 ``` num_widgets = 0 while True: choice = input("Would you like to buy a widget? (y/n): ") if choice.lower() == "y": num_widgets += 1 else: break print("You bought", num_widgets , "widget(s)." ``` Refer to Code Example 3-1. If the user enters “Y” at the prompt, what does the program print to the console?
Would you like to buy a widget? (y/n):
40
Code Example 3-1 ``` num_widgets = 0 while True: choice = input("Would you like to buy a widget? (y/n): ") if choice.lower() == "y": num_widgets += 1 else: break print("You bought", num_widgets , "widget(s).") ``` Refer to Code Example 3-1. If the user enters “no” at the prompt, what does the program print to the console?
You bought 0 widget(s) today.
41
Code Example 3-1 ``` num_widgets = 0 while True: choice = input("Would you like to buy a widget? (y/n): ") if choice.lower() == "y": num_widgets += 1 else: break print("You bought", num_widgets , "widget(s).") ``` Refer to Code Example 3-1. Which of the following could be a pseudocode plan for the program?
``` Define widget count variable Begin infinite loop Get user input IF user buys widget add 1 to widget count ELSE end loop Display results ```
42
For the following code, what will the result be if the user enters 4 at the prompt? product = 1 end_value = int(input("Enter a number: ")) for i in range(1, end_value): product = product * i i += 1 print("The product is ", product)
The product is 6
43
For the following code, what will the result be if the user enters 4 at the prompt? product = 1 end_value = int(input("Enter a number: ")) for i in range(1, end_value+1): product = product * i i += 1 print("The product is ", product)
The product is 24
44
For the following code, what will the result be if the user enters 5 at the prompt? sum = 0 end_value = int(input("Enter a number: ")) for i in range(1, end_value): sum = sum + i print(sum, end=", ")
1, 3, 6, 10,
45
Given the following code, select the compound condition that makes sure that the input is an integer greater than 0 and less than 1,000. my_num = input("Enter a number between 1 and 999:") check_num = int(my_num) while _________________________: my_num = input("Try again. The number must be between 1 and 999") check_num = int(my_num)
check_num <= 0 or check_num >= 1000
46
How many times will “Hi again!” be displayed after the following code executes? for i in range(0, 12, 2): print("Hi, again!")
6
47
``` How many times will “Hi there!” be displayed after the following code executes? num = 2 while num < 12: print("Hi, there!") num += 2 ```
5
48
If you want to code an if clause, but you don’t want to perform any action, you can code
a pass statement
49
In a while loop, the Boolean expression is tested
before the loop is executed
50
Pseudocode can be used to plan
the coding of control structures
51
``` Python will sort the strings that follow in this sequence: Peach peach 1peach 10Peaches ```
10Peaches, 1peach, Peach, peach
52
The and operator has
higher precedence than the or operator, but lower precedence than the not operator
53
To compare two strings with mixed uppercase and lowercase letters, a programmer can first use the
lower() method to convert all characters in each string to lowercase.
54
To jump to the end of the current loop, you can use the
break statement
55
``` What will be displayed after the following code executes? guess = 19 if guess < 19: print("Too low") elif guess > 19: print("Too high") ```
nothing will display
56
``` What will be displayed after the following code is executed? counter = 1 while counter <= 20: print(counter, end=" ") counter *= 3 print("\nThe loop has ended.") ```
1 3 9 | The loop has ended.
57
``` What will the output of the following code be if the user enters 3 at the prompt? your_num = int(input("Enter a number:")) while (your_num > 0): product = your_num * 5 print(your_num, " * 5 = ", product) your_num -= 1 ```
3 * 5 = 15 2 * 5 = 10 1 * 5 = 5
58
``` What will this loop display? sum = 0 for i in range(0, 25, 5): sum += i print(sum) ```
50
59
When two strings are compared, they are evaluated based on the ___________________ of the characters in the string.
sort sequence
60
Which of the following begins by testing a condition defined by a Boolean expression and then executes a block of statements if the condition is true?
a while statement
61
Which of the following can use the range() function to loop through a block of statements?
a for statement
62
Which of the following creates a Boolean variable?
flag = True
63
Which of the following in this expression is evaluated first? age >= 65 and status == "retired" or age < 18
age >= 65
64
Which of the following in this expression is evaluated first? age >= 65 or age <= 18 or status == "retired"
age >= 65
65
Which of the following is not an acceptable way to code a nested structure?
nest an else clause within an elif clause
66
Which of the following is true for an if statement that has both elif and else clauses?
If the condition in the if clause is true, the statements in that clause are executed.
67
Which type of expression has a value of either true or false?
Boolean
68
Which of the following is not true of hierarchy charts?
Related functions should be combined into a single function.
69
A file that contains reusable code is called a
module
70
A global variable
is defined outside of all functions
71
A local variable is defined
inside a function
72
A return statement
can be used to return a local variable to the calling function
73
Assuming the random module has been imported into its default namespace, which of the following could possibly result in a value of 0.94?
number = random.random()
74
Assuming the random module has been imported into its default namespace, which of the following could be used to simulate a coin toss where 0 = heads and 1 = tails?
number = random.randint(0, 1)
75
Assuming the random module has been imported into its default namespace, which of the following could be used to generate a random even integer from 2 through 200?
number = random.randrange(2, 202, 2)
76
Before you can use a standard module like the random module, you need to
import the module
77
``` Code Example 4-1 def get_username(first, last): s = first + "." + last return s.lower() ``` ``` def main(): first_name = input("Enter your first name: ") last_name = input("Enter your last name: ") username = get_username(first_name, last_name) print("Your username is: " + username) ``` if __name__ == "__main__": main() Refer to Code Example 4-1: What function is called first when the program runs?
main()
78
``` Code Example 4-1 def get_username(first, last): s = first + "." + last return s.lower() ``` ``` def main(): first_name = input("Enter your first name: ") last_name = input("Enter your last name: ") username = get_username(first_name, last_name) print("Your username is: " + username) ``` if __name__ == "__main__": main() Refer to Code Example 4-1: What arguments are defined by the get_username() function?
first, last
79
``` Code Example 4-1 def get_username(first, last): s = first + "." + last return s.lower() ``` ``` def main(): first_name = input("Enter your first name: ") last_name = input("Enter your last name: ") username = get_username(first_name, last_name) print("Your username is: " + username) ``` if __name__ == "__main__": main() Refer to Code Example 4-1: If the user enters ‘Lopez’ for the first prompt in main() and ‘Maria’ for the second prompt, what will display?
lopez.maria
80
``` Code Example 4-1 def get_username(first, last): s = first + "." + last return s.lower() ``` ``` def main(): first_name = input("Enter your first name: ") last_name = input("Enter your last name: ") username = get_username(first_name, last_name) print("Your username is: " + username) ``` if __name__ == "__main__": main() Refer to Code Example 4-1: What is the scope of the variable named s?
local
81
``` Code Example 4-2 def get_volume(width, height, length=2): volume = width * height * length return volume ``` ``` def main(): l = 3 w = 4 h = 5 v = get_volume(l, w, h) print(v) ``` if __name__ == "__main__": main() Refer to Code Example 4-2: When this program runs, what does it print to the console?
60
82
``` Code Example 4-2 def get_volume(width, height, length=2): volume = width * height * length return volume ``` ``` def main(): l = 3 w = 4 h = 5 v = get_volume(l, w, h) print(v) ``` if __name__ == "__main__": main() Refer to Code Example 4-2: If you add the following code to the end of the main() method, what does it print to the console? print(get_volume(10, 2))
40
83
Code Example 4-3 main program: import arithmetic as a ``` def main(): num1 = 5 num2 = 6 result = a.add(num1, num2) print("The sum is", result) ``` if __name__ == "__main__": main() ``` arithmetic module: def add(x = 4, y = 2): z = x + y return z ``` Refer to Code Example 4-3: What will be displayed after the code runs?
The sum is 11
84
Code Example 4-3 main program: import arithmetic as a ``` def main(): num1 = 5 num2 = 6 result = a.add(num1, num2) print("The sum is", result) ``` if __name__ == "__main__": main() ``` arithmetic module: def add(x = 4, y = 2): z = x + y return z ``` Refer to Code Example 4-3: What values are in x and y after the code runs?
5, 6
85
Code Example 4-4 main program: import arithmetic as a ``` def multiply(num1, num2): product = num1 * num2 result = a.add(product, product) return result ``` ``` def main(): num1 = 4 num2 = 3 answer = multiply(num1, num2) print("The answer is", answer) ``` if __name__ == "__main__": main() ``` arithmetic module: def add(x, y): z = x + y return z ``` Refer to Code Example 4-4: What values are in x and y after the code runs?
12, 12
86
Code Example 4-4 main program: import arithmetic as a ``` def multiply(num1, num2): product = num1 * num2 result = a.add(product, product) return result ``` ``` def main(): num1 = 4 num2 = 3 answer = multiply(num1, num2) print("The answer is", answer) ``` if __name__ == "__main__": main() ``` arithmetic module: def add(x, y): z = x + y return z ``` Refer to Code Example 4-4: The add() function is called by
the multiply() function
87
Code Example 4-4 main program: import arithmetic as a ``` def multiply(num1, num2): product = num1 * num2 result = a.add(product, product) return result ``` ``` def main(): num1 = 4 num2 = 3 answer = multiply(num1, num2) print("The answer is", answer) ``` if __name__ == "__main__": main() ``` arithmetic module: def add(x, y): z = x + y return z ``` Refer to Code Example 4-4: When this code runs, what does it print to the console?
The answer is 24
88
If you import two modules into the global namespace and each has a function named get_value(),
a name collision occurs
89
The best way to call the main() function of a program is to code
an if statement that calls the main() function only if the current module is the main module
90
The default namespace for a module is
the same as the name of the module
91
To assign a default value to an argument when you define a function, you
code the name of the argument, the assignment operator (=), and the default value
92
To call a function with named arguments, you code the
name of each argument, an equals sign, and the value or variable that’s being passed
93
To call a function, you code the function name and
a set of parentheses that contains zero or more arguments
94
To define a function, you code the def keyword and the name of the function followed by
a set of parentheses that contains zero or more arguments
95
Which of the following statements imports a module into the default namespace?
import temperature
96
Which of the following statements imports a module into the global namespace?
from temperature import *
97
Which of the following statements is not true about the documentation of a module?
You can use regular Python comments to document the functions of the module.
98
``` Which statement would you use to call the print_name() function from a module named address that has been imported with this statement? import address as a ```
a.print_name(name)
99
``` A programmer created this code for a client: def divide(numerator, denominator): quotient = numerator / denominator return quotient ``` ``` def main(): numerator = int(input("Enter the numerator: ")) denominator = int(input("Enter the denominator: ")) quotient = divide(numerator, denominator) print("The quotient is ", quotient) ``` ``` if __name__ == "__main__": main() The programmer tested this code with the following three sets of data: 1. numerator = 9, denominator = 3 2. numerator = -50, denominator = 5 3. numerator = 389, denominator = -26 The results were: 1. The quotient is 3.0 2. The quotient is -10.0 3. The quotient is -14.961538461538462 However, once the program was in use, the client reported that sometimes the program crashed. Can you explain why? ```
Programmer didn’t test for a 0 value in the denominator.
100
Code Example 5-1 1. count = 1 2. item_total = 0 3. item = 0 4. while count < 4: 5. item = int(input("Enter item cost: ")) 6. item_total += item 7. count += 1 8. average_cost = round(item_total / count) 9. print("Total cost:", item_total, "\nAverage cost:", average_cost) Refer to Code Example 5-1: If the user enters 5, 10, and 15 at the prompts, the output is: Total cost: 30 Average cost: 8 Which line should be changed to fix this logic error?
change line 8 to: average_cost = round(item_total / (count - 1))
101
Code Example 5-2 1. # This application displays a student's score after a 5-point curve 2. 3. def display_info(fname, lname, score): 4. print("Hello, " , fname, " " , Lname) 5. print("Your score on this exam is ", score) 6. score = score + 5 7. 8. def main(): 9. first = input("first name: ") 10. last = input("last name: ") 11. grade = input("exam score: ") 12. display_info(last, first, score) 13. 14. # if started as the main module, call the main function 15. if __name__ == "__main__": 16. main() Refer to Code Example 5-2: What is the error in the main() function?
The input statement on line 11 gets a variable named grade but sends in an undefined variable named score on line 12
102
Code Example 5-2 1. # This application displays a student's score after a 5-point curve 2. 3. def display_info(fname, lname, score): 4. print("Hello, " , fname, " " , Lname) 5. print("Your score on this exam is ", score) 6. score = score + 5 7. 8. def main(): 9. first = input("first name: ") 10. last = input("last name: ") 11. grade = input("exam score: ") 12. display_info(last, first, score) 13. 14. # if started as the main module, call the main function 15. if __name__ == "__main__": 16. main() Refer to Code Example 5-2: What is the first error in the display_info() function?
The variable Lname on line 4 does not exist
103
Code Example 5-2 1. # This application displays a student's score after a 5-point curve 2. 3. def display_info(fname, lname, score): 4. print("Hello, " , fname, " " , Lname) 5. print("Your score on this exam is ", score) 6. score = score + 5 7. 8. def main(): 9. first = input("first name: ") 10. last = input("last name: ") 11. grade = input("exam score: ") 12. display_info(last, first, score) 13. 14. # if started as the main module, call the main function 15. if __name__ == "__main__": 16. main() Refer to Code Example 5-2: What is the error on line 6?
The variable score has been input as a string so it must be converted to an int or float.
104
Code Example 5-2 1. # This application displays a student's score after a 5-point curve 2. 3. def display_info(fname, lname, score): 4. print("Hello, " , fname, " " , Lname) 5. print("Your score on this exam is ", score) 6. score = score + 5 7. 8. def main(): 9. first = input("first name: ") 10. last = input("last name: ") 11. grade = input("exam score: ") 12. display_info(last, first, score) 13. 14. # if started as the main module, call the main function 15. if __name__ == "__main__": 16. main() Refer to Code Example 5-2: Assuming the coding errors have been fixed, what is the logic error in this program?
The curve is calculated after the score has been displayed.
105
Given the following code and its output: 1. discount_rate = .1 2. item = 89.95 3. discount = item * discount_rate 4. print("The discount on this item is $", discount)) Output: The discount on this item is $ 8.995000000000001 Which of the following would produce a user-friendly correct result?
change line 4 to: print("The discount on this item is $", round(discount, 2))
106
Given the following code, if the user worked 45 hours at $10.00/hour, the output is as shown below. 1. def main(): 2. hours = float(input("How many hours did you work? ")) 3. rate = float(input("What is your hourly rate? ")) 4. if (hours > 40) and (rate < 15): 5. pay = (hours * rate) + (hours - 40 * rate * 1.5) 6. else: 7. pay = hours * rate 8. print("Your pay is: $ ", round(pay, 2)) Output: Your pay is: $ -105.0 Which line should be changed to fix this logic error?
change line 5 to: pay = (40 * rate) + ((hours - 40) * rate * 1.5)
107
The stack is available when an exception occurs. It displays a list of
just the functions that were called prior to the exception
108
To test the functions of a module from the IDLE shell, you
import the module and then call any function from the IDLE shell
109
What line number of the following code contains an error and what type of error is it? 1. def sales_tax(amt) 2. sale = amt + (amt * .06) 3. return sale 4. 5. def main(): 6. print("Welcome to the 6% tax calculator!\n") 7. total = int(input("Please enter the total amount: ")) 8. print("The total amount after tax is: ", sales_tax(total))
line 1, syntax error
110
What line number of the following code contains an error and what type of error is it? 1. count = 1 2. while count <= 4: 3. print(count, end=" ") 4. i *= 1 5. print("\nThe loop has ended.")
line 4, runtime error
111
When the IDLE debugger reaches a breakpoint, you can do all but one of the following. Which one is it?
view the values of all the variables that you’ve stepped through
112
When you plan the test runs for a program, you should do all but one of the following. Which one is it?
list the expected exceptions for each test run
113
When you trace the execution of a program, you insert print() functions at key points in the program. It makes sense for these functions to do all but one of the following. Which one is it?
display the values of the global constants used by the function
114
When you use the IDLE debugger, you start by setting a breakpoint
on a statement before the statement you think is causing the bug
115
Which of the following is not a common type of syntax error?
invalid variable names
116
Which of the following is not true about top-down coding and testing?
You should always start by coding and testing the most difficult functions.
117
Which type of error prevents a program from compiling and running?
syntax
118
Which type of error throws an exception that stops execution of the program?
runtime
119
``` Code Example 6-1 def main(): students = [["Lizzy", 73, "C"], ["Mike", 98, "A"], ["Joel", 88, "B+"], ["Anne", 93, "A"]] ``` for student in students: for item in student: print(item, end=" ") if __name__ == "__main__": main() Refer to Code Example 6-1: What is in the second row of the students list?
"Mike", 98, "A"
120
The __________ method adds an item to the end of a list.
append()
121
Given the following code, what would be displayed after the code executes? def main(): furry_pets = ["dog", "cat", "ferret", "hamster", "bunny"] feathered_pets = ["canary", "parrot", "budgie", "hawk"] all_pets = furry_pets + feathered_pets new_pets =[] i = 0 for item in all_pets: if item[i][0] == "c": new_pets.append(item) print("The pet store sells:", all_pets) print("These start with the letter c:", new_pets)
The pet store sells: ['dog', 'cat', 'ferret', 'hamster', 'bunny', 'canary', 'parrot', 'budgie', 'hawk'] These start with the letter c: ['cat', 'canary']
122
Which of the following is not true about a list of lists?
To delete an item in the outer list, you first have to delete the list in the item.
123
Given the tuple that follows, which of the following assigns the values in the tuple to variables? numbers = (22, 33, 44, 55)
w, x, y, z = numbers
124
When you use a multiple assignment statement to unpack a tuple,
you assign the tuple to a two or more variable names separated by commas
125
Given the following code, what is the value of my_name and what does the list consist of after the second statement is executed? names = ["Lizzy", "Mike", "Joel", "Anne", "Donny"] my_name = name.pop()
my_name = "Donny", names = ["Lizzy", "Mike", "Joel", "Anne"]
126
To remove the item “mangos” from the following list, you would use which of these methods? fruit = ["apple", "banana", "grapes", "mangos", "oranges"]
fruit.remove("mangos") or fruit.pop(3)
127
When a function changes the data in a list, the changed list
does not need to be returned because lists are mutable.
128
Which of the following statements about list copies is not true? When you make a
deep copy of a list, both variables refer to the same list.
129
``` Code Example 6-1 def main(): students = [["Lizzy", 73, "C"], ["Mike", 98, "A"], ["Joel", 88, "B+"], ["Anne", 93, "A"]] ``` for student in students: for item in student: print(item, end=" ") if __name__ == "__main__": main() Refer to Code Example 6-1: What is the value of students[2][1]?
88
130
What would be displayed after the following code snippet executes? costumes = ["ghost", "witch", "elf", "ogre"] name = "elf" if name in costumes: costumes.remove(name) for item in costumes: print(item)
ghost witch ogre
131
What will display after the following code executes? def add_item(list, food): food = "apple pie" list.append(food) ``` def main(): lunch = ["sandwich", "chips", "pickle"] food = "banana" add_item(lunch, food) print(lunch) ``` main()
['sandwich', 'chips', 'pickle', 'apple pie']
132
Given the following code, what would the list consist of after the second statement? ages = [22, 35, 24, 17, 28] ages.insert(3, 4)
ages = [22, 35, 24, 4, 17, 28]
133
Which of the following creates a tuple of six strings?
vehicles = ("sedan","SUV","motorcycle","bicycle","hatchback","truck")
134
Which of the following functions randomly selects one item in a list?
choice()
135
Given the following list, what is the value of ages[5]? | ages = [22, 35, 24, 17, 28]
None: Index error
136
``` Code Example 6-1 def main(): students = [["Lizzy", 73, "C"], ["Mike", 98, "A"], ["Joel", 88, "B+"], ["Anne", 93, "A"]] ``` for student in students: for item in student: print(item, end=" ") if __name__ == "__main__": main() Refer to Code Example 6-1: What would display if the following three lines were added at the end of the main() function? students.sort() students.reverse() print(students)
[['Mike',98,'A'],['Lizzy',73,'C'],['Joel',88,'B+'],['Anne',93,'A
137
Which of the following would create a list named numbers consisting of 3 floating-point items?
numbers = [5.3, 4.8, 6.7]
138
``` Code Example 6-1 def main(): students = [["Lizzy", 73, "C"], ["Mike", 98, "A"], ["Joel", 88, "B+"], ["Anne", 93, "A"]] ``` for student in students: for item in student: print(item, end=" ") if __name__ == "__main__": main() Refer to Code Example 6-1: What will display after the code executes?
Lizzy 73 C Mike 98 A Joel 88 B+ Anne 93 A
139
``` What is the value of the total variable after the following code executes? prices = [10, 15, 12, 8] total = 0 i = 1 while i < len(prices): total += prices[i] i += 1 print(total) ```
35
140
Given the following list, what is the value of names[2]? | names = ["Lizzy", "Mike", "Joel", "Anne", "Donald Duck"]
Joel
141
To refer to an item in a list, you code the list name followed by
an index number in brackets, starting with the number 0
142
The primary difference between a tuple and a list is that a tuple
is immutable
143
To insert the item “melon” after “grapes” in the following list, you would use which of these methods? fruit = ["apple", "banana", "grapes", "mangos", "oranges"]
fruit.insert(3, "melon")
144
Which of the following is not true about a CSV file?
The csv module is a standard module so you don’t need to import it
145
To read the rows in a CSV file, you need to
get a reader object by using the reader() function of the csv module
146
``` Code Example 7-2 import pickle def main(): courses = [["Python", 3], ["Trig", 3], ["Physics", 4], ["Yoga", 2]] with open("classes.bin", "wb") as file: pickle.dump(courses, file) with open("classes.bin", "rb") as file: course_list = pickle.load(file) i = 0 while i < len(course_list): course = course_list[i] print(course[0], str(course[1]), end=" ") i += 2 ``` main() Refer to Code Example 7-2: What does the second with open statement do?
causes an exception if the file named classes.bin doesn’t exist
147
``` Code Example 7-1 import csv def main(): courses = [["Python", 3], ["Trig", 3], ["Physics", 4], ["Yoga", 2]] with open("courses.csv", "w", newline="") as file: writer = csv.writer(file) writer.writerows(courses) course_list = [] with open("courses.csv", newline="") as file: reader = csv.reader(file) for row in reader: course_list.append(row) for i in range(len(course_list) - 2): course = course_list[i] print(course[0] + " (" + str(course[1]) + ")") ``` main() Refer to Code Example 7-1. If the first with open statement works, what is written to the file?
The list named courses.
148
To work with a file when you’re using Python, you must do all but one of the following. Which one is it?
decode the data in the file
149
``` Code Example 7-1 import csv def main(): courses = [["Python", 3], ["Trig", 3], ["Physics", 4], ["Yoga", 2]] with open("courses.csv", "w", newline="") as file: writer = csv.writer(file) writer.writerows(courses) course_list = [] with open("courses.csv", newline="") as file: reader = csv.reader(file) for row in reader: course_list.append(row) for i in range(len(course_list) - 2): course = course_list[i] print(course[0] + " (" + str(course[1]) + ")") ``` main() Refer to Code Example 7-1. What happens if the courses.csv file doesn’t exist when the first with open statement is executed?
a new file named courses.csv is created
150
``` Code Example 7-2 import pickle def main(): courses = [["Python", 3], ["Trig", 3], ["Physics", 4], ["Yoga", 2]] with open("classes.bin", "wb") as file: pickle.dump(courses, file) with open("classes.bin", "rb") as file: course_list = pickle.load(file) i = 0 while i < len(course_list): course = course_list[i] print(course[0], str(course[1]), end=" ") i += 2 ``` main() Refer to Code Example 7-2: What is displayed on the console by the while loop?
Python 3 Physics 4
151
``` Code Example 7-1 import csv def main(): courses = [["Python", 3], ["Trig", 3], ["Physics", 4], ["Yoga", 2]] with open("courses.csv", "w", newline="") as file: writer = csv.writer(file) writer.writerows(courses) course_list = [] with open("courses.csv", newline="") as file: reader = csv.reader(file) for row in reader: course_list.append(row) for i in range(len(course_list) - 2): course = course_list[i] print(course[0] + " (" + str(course[1]) + ")") ``` main() Refer to Code Example 7-1. What will display on the console after the code executes?
Python (3) | Trig (3)
152
``` Code Example 7-2 import pickle def main(): courses = [["Python", 3], ["Trig", 3], ["Physics", 4], ["Yoga", 2]] with open("classes.bin", "wb") as file: pickle.dump(courses, file) with open("classes.bin", "rb") as file: course_list = pickle.load(file) i = 0 while i < len(course_list): course = course_list[i] print(course[0], str(course[1]), end=" ") i += 2 ``` main() Refer to Code Example 7-2: What does the first with open statement do?
writes the courses list to a binary file if the file named classes.bin doesn’t exist
153
A binary file is like a text file in all but one of the following ways. Which one is it?
A binary file stores numbers with binary notation.
154
Given the following 2-dimensional list of 3 rows and 3 columns, how would you write this list to a CSV file named prog.csv? programming = [["Python", "cop1000", 3], ["Java", "cop1020", 3], ["HTML5", "cop1040", 3]]
``` with open("prog.csv", "w", newline ="") as file: writer = csv.writer(file) writer.writerows(programming) ```
155
To read a list of lists that’s stored in a binary file, you use
the load() method of the pickle module
156
Which one of the following is not a benefit of using a with statement to open a file?
You don’t have to specify the path for the file.
157
A Python program should use try statements to handle
all exceptions that can’t be prevented by normal coding techniques
158
``` Code Example 8-1 import csv import sys FILENAME = "names.csv" def main(): try: names = [] with open(FILENAME, newline="") as file: reader = csv.reader(file) for row in reader: names.append(row) except FileNotFoundError as e: print("Could not find " + FILENAME + " file.") sys.exit() except Exception as e: print(type(e), e) sys.exit() print(names) if __name__ == "__main__": main() ``` Refer to Code Example 8-1. If the names.csv file is not in the same directory as the file that contains the Python code, what type of exception will be thrown and caught?
FileNotFoundError
159
``` Code Example 8-1 import csv import sys FILENAME = "names.csv" def main(): try: names = [] with open(FILENAME, newline="") as file: reader = csv.reader(file) for row in reader: names.append(row) except FileNotFoundError as e: print("Could not find " + FILENAME + " file.") sys.exit() except Exception as e: print(type(e), e) sys.exit() print(names) if __name__ == "__main__": main() ``` Refer to Code Example 8-1. If the for statement in the try clause refers to readers instead of reader, what type exception will be thrown and caught?
NameError
160
If a program attempts to read from a file that does not exist, which of the following will catch that error?
FileNotFoundError and OSError
161
It’s a common practice to throw your own exceptions to test error handling routines that
catch exceptions that are hard to produce otherwise
162
The finally clause of a try statement
is executed whether or not an exception has been thrown
163
To cancel the execution of a program in the catch clause of a try statement, you can use the
exit() function of the sys module
164
To throw an exception with Python code, you use the
raise statement
165
When an exception is thrown, Python creates an exception object that contains all but one of the following items of information. Which one is it?
the severity of the exception
166
Which of the following is the correct way to code a try statement that catches any type of exception that can occur in the try clause?
``` try: number = float(input("Enter a number: ")) print("Your number is: ", number) except: print("Invalid number.") ```
167
Which of the following is the correct way to code a try statement that displays the type and message of the exception that’s caught?
``` try: number = int(input("Enter a number: ")) print("Your number is: ", number) except Exception as e: print(type(e), e) ```
168
Within the try clause of a try statement, you code
a block of statements that might cause an exception
169
Code Example 9-1 print("{:12} {:>10} {:>5}".format("Item", "Price", "Qty")) print("{:12} {:10.2f} {:5d}".format("laptop", 499.99, 1)) print("{:12} {:10.2f} {:5d}".format("charger", 29.95, 3)) print("{:12} {:10.2f} {:5d}".format("leather case", 125.00, 1)) Refer to Code Example 9-1. What does :5d specify in the print statements of the last three lines? The value in this column
is an integer with 5 spaces allowed for its display.
170
Code Example 9-1 print("{:12} {:>10} {:>5}".format("Item", "Price", "Qty")) print("{:12} {:10.2f} {:5d}".format("laptop", 499.99, 1)) print("{:12} {:10.2f} {:5d}".format("charger", 29.95, 3)) print("{:12} {:10.2f} {:5d}".format("leather case", 125.00, 1)) Refer to Code Example 9-1. What does the 2f mean in the {:10.2f} specification? The value
is a floating-point number that should be displayed with 2 decimal places.
171
``` Code Example 9-2 number = float(input("Enter a number: ")) result1 = number * .15 result2 = result1 / 3 result3 = result1 + result2 print(result3) ``` Refer to Code Example 9-2. When this code is executed, which of the variables might contain approximate results instead of accurate results?
result1, result2, and result3
172
``` Code Example 9-2 number = float(input("Enter a number: ")) result1 = number * .15 result2 = result1 / 3 result3 = result1 + result2 print(result3) ``` Refer to Code Example 9-2. To be sure that the results are accurate to 2 decimal places, you should
round the result of each expression to 2 decimal places
173
``` Given that the locale module has been imported as lc, which block of code will display the number in this format? £34,567.89 ```
lc.setlocale(lc.LC_ALL, "uk") | print(lc.currency(34567.89, grouping=True))
174
If number equals .15605, which of the following will display it as: 16%
print("{:.0%}".format(number))
175
If number equals 3,237,945.76, which of the following will display it as: 3,237,945.76
print("{:,.2f}".format(number))
176
One of the ways to deal with the inaccuracies that may result from floating-point arithmetic operations is to
round the results of those calculations that may lead to more decimal places than you want in the final result
177
One of the ways to deal with the inaccuracies that may result from floating-point arithmetic operations is to
do the math with Decimal objects instead of floating-point numbers
178
To define a variable named number that contains 123.4567 as a decimal number, not a floating-point number, which block of code would you use?
from decimal import Decimal | number = Decimal(123.4567)
179
To round a decimal number that’s stored in a variable named number to 2 decimal places with normal business rounding, which statement would you use?
number = number.quantize(Decimal("1.00"), ROUND_HALF_UP)
180
Using floating-point numbers can lead to arithmetic errors because floating-point numbers
are approximate values
181
What will be displayed when this code is executed? name = "Name" ID = "ID" print("{:10} {:>5}".format(name, ID)) print("{:10} {:7d}".format("Liz", 234)) print("{:10} {:7d}".format("Mike", 23456))
Name ID Liz 234 Mike 23456
182
When you’re using Decimal objects in an arithmetic expression, you cannot use
floating-point values as operands
183
Which of the following is not a floating-point number?
-683
184
Which of the following modules lets you work with decimal numbers instead of floating-point numbers?
decimal
185
Which of the following modules provides a function for formatting currency in the US, UK, or parts of Europe?
locale
186
Which of the following modules provides a function for getting the square root of a number?
math
187
Which of the following will produce the same result as this code? import math as m area = m.pi * radius**2
area = m.pi * m.pow(radius, 2)
188
You can use the format() method of a string to format numbers in all but one of the following ways. Which one is it?
apply $ signs
189
A Unicode character is represented by a
2-digit code
190
Code Example 10-1 1. phone_number = input("Enter phone number: ").strip() 2. if len(phone_number) == 10: 3. phone_number = "(" + phone_number[:3] + ")" + phone_number[3:6] + "-" + phone_number[6:] 4. print("Phone number: ", phone_number) 5. else: 6. print("Phone number: ", "Phone number must be 10 digits") Refer to Code Example 10-1. If the user enters two extra spaces at the end of a phone number, what will happen?
The strip() method on line 1 will strip away the extra whitespace.
191
Code Example 10-1 1. phone_number = input("Enter phone number: ").strip() 2. if len(phone_number) == 10: 3. phone_number = "(" + phone_number[:3] + ")" + phone_number[3:6] + "-" + phone_number[6:] 4. print("Phone number: ", phone_number) 5. else: 6. print("Phone number: ", "Phone number must be 10 digits") Refer to Code Example 10-1. If the user enters 555-123-4567 at the prompt, what will happen?
The length of the number will be greater than 10 so the else clause will execute.
192
Code Example 10-1 1. phone_number = input("Enter phone number: ").strip() 2. if len(phone_number) == 10: 3. phone_number = "(" + phone_number[:3] + ")" + phone_number[3:6] + "-" + phone_number[6:] 4. print("Phone number: ", phone_number) 5. else: 6. print("Phone number: ", "Phone number must be 10 digits") Refer to Code Example 10-1. If the user enters 5551234567 at the prompt, what will be displayed?
Phone number: (555)123-4567
193
Given the following code, what will be displayed after the code executes? name = "Mervin the Magician" words = name.split() print(words[0] + ", you are quite a " + words[2].lower())
Mervin, you are quite a magician
194
``` Given the following code, what would display? car = "PORSCHE" color = "red" my_car = car.join(color) print(my_car) ```
rPORSCHEePORSCHEd
195
If word = "a horse", which of the following snippets of Python code will display this result? a horse! a horse! My kingdom for a horse!
print((word + "! ") * 2 + " My kingdom for " + word + "!")
196
The isdigit() method of a string returns
true if the string contains only digits
197
The join() method of a list can be used to combine
the items in the list into a string that’s separated by delimiters
198
To access the first three characters in a string that’s stored in a variable named message, you can use this code:
first_three = message[0:3]
199
To determine the length of a string that’s in a variable named city, you can use this code:
len(city)
200
To retrieve the fourth character in a string that’s stored in a variable named city, you can use this code:
city[3]
201
``` What is the value of s2 after the code that follows is executed? s1 = "118-45-9271" s2 = "" for i in s1: if i != '-': s2 += i s1.replace("-", ".") ```
118459271
202
``` What is the value of s3 after the code that follows is executed? s1 = "abc def ghi"; s2 = s1[1:5] s3 = s2.replace('b', 'z') print(s3) ```
zc d
203
What is the value of the variable named result after this code is executed? email = "marytechknowsolve.com" result = email.find("@")
-1
204
What is the value of the variable named result after this code is executed? email = "joel.murach@com" result = email.find("@") - email.find(".") print(result)
7
205
What will be displayed after the following code executes? book_name = "a tale for the knight" book = book_name.title() print(book)
A Tale For The Knight
206
Which of the Python examples that follow can not be used to create a string named n2?
``` numbers = [8, 17, 54, 22, 35] n2 = "".join(numbers) ```
207
``` Which of the following code snippets will result in this display: Countdown... 5... 4... 3... 2... 1... Blastoff! ```
``` counting = "54321" print("Countdown...") for char in counting: print(char + "...") print("Blastoff!") ```
208
Which of the following statements will modify the string that’s stored in a variable named s?
You can’t modify a string.
209
Which of the following will display this result? | B = 66
print("B = ", ord("B"))
210
You can use the split() method to split a string into a list of strings based on a specified
delimiter
211
A naive datetime object doesn’t account for
time zones and daylight savings time
212
``` Code Example 11-1 from datetime import datetime, time def main(): input("Press Enter to start...") start = datetime.now() month = start.strftime("%B") day = start.strftime("%d") hours = start.strftime("%I") minutes = start.strftime("%M") am_pm = start.strftime("%p") print("Start time:",month,day,"at",hours,":",minutes,am_pm) input("Press Enter to stop...") stop = datetime.now() month = stop.strftime("%B") day = stop.strftime("%d") hours = stop.strftime("%I") minutes = stop.strftime("%M") am_pm = stop.strftime("%p") print("Stop time: ",month,day,"at",hours,":",minutes,am_pm) elapsed_time = stop - start new_days = elapsed_time.days new_minutes = elapsed_time.seconds // 60 new_hours = new_minutes // 60 new_minutes = new_minutes % 60 print("Time elapsed: ") if new_days > 0: print("days:",new_days) print("hours:", new_hours, ", minutes:", new_minutes) if __name__ == "__main__": main() ``` Refer to Code Example 11-1: Which variable holds the value of the beginning day?
day
213
``` Code Example 11-1 from datetime import datetime, time def main(): input("Press Enter to start...") start = datetime.now() month = start.strftime("%B") day = start.strftime("%d") hours = start.strftime("%I") minutes = start.strftime("%M") am_pm = start.strftime("%p") print("Start time:",month,day,"at",hours,":",minutes,am_pm) input("Press Enter to stop...") stop = datetime.now() month = stop.strftime("%B") day = stop.strftime("%d") hours = stop.strftime("%I") minutes = stop.strftime("%M") am_pm = stop.strftime("%p") print("Stop time: ",month,day,"at",hours,":",minutes,am_pm) elapsed_time = stop - start new_days = elapsed_time.days new_minutes = elapsed_time.seconds // 60 new_hours = new_minutes // 60 new_minutes = new_minutes % 60 print("Time elapsed: ") if new_days > 0: print("days:",new_days) print("hours:", new_hours, ", minutes:", new_minutes) if __name__ == "__main__": main() ``` Refer to Code Example 11-1: If the timer is started on November 17 at 4:00 pm and stopped on November 18 at 6:30 pm, what will be displayed?
Time elapsed: days: 1 hours: 2, minutes: 30
214
``` Code Example 11-1 from datetime import datetime, time def main(): input("Press Enter to start...") start = datetime.now() month = start.strftime("%B") day = start.strftime("%d") hours = start.strftime("%I") minutes = start.strftime("%M") am_pm = start.strftime("%p") print("Start time:",month,day,"at",hours,":",minutes,am_pm) input("Press Enter to stop...") stop = datetime.now() month = stop.strftime("%B") day = stop.strftime("%d") hours = stop.strftime("%I") minutes = stop.strftime("%M") am_pm = stop.strftime("%p") print("Stop time: ",month,day,"at",hours,":",minutes,am_pm) elapsed_time = stop - start new_days = elapsed_time.days new_minutes = elapsed_time.seconds // 60 new_hours = new_minutes // 60 new_minutes = new_minutes % 60 print("Time elapsed: ") if new_days > 0: print("days:",new_days) print("hours:", new_hours, ", minutes:", new_minutes) if __name__ == "__main__": main() ``` Refer to Code Example 11-1: If the timer is started on November 17 at 4:00 pm and stopped on November 18 at 6:30 pm, what is the value of minutes at the end of the program?
30
215
``` Code Example 11-1 from datetime import datetime, time def main(): input("Press Enter to start...") start = datetime.now() month = start.strftime("%B") day = start.strftime("%d") hours = start.strftime("%I") minutes = start.strftime("%M") am_pm = start.strftime("%p") print("Start time:",month,day,"at",hours,":",minutes,am_pm) input("Press Enter to stop...") stop = datetime.now() month = stop.strftime("%B") day = stop.strftime("%d") hours = stop.strftime("%I") minutes = stop.strftime("%M") am_pm = stop.strftime("%p") print("Stop time: ",month,day,"at",hours,":",minutes,am_pm) elapsed_time = stop - start new_days = elapsed_time.days new_minutes = elapsed_time.seconds // 60 new_hours = new_minutes // 60 new_minutes = new_minutes % 60 print("Time elapsed: ") if new_days > 0: print("days:",new_days) print("hours:", new_hours, ", minutes:", new_minutes) if __name__ == "__main__": main() ``` Refer to Code Example 11-1: If the timer is started on November 17 at 4:00 pm and stopped on November 18 at 6:30 pm, what is the value of seconds at the end of the program?
seconds is undefined
216
``` Code Example 11-1 from datetime import datetime, time def main(): input("Press Enter to start...") start = datetime.now() month = start.strftime("%B") day = start.strftime("%d") hours = start.strftime("%I") minutes = start.strftime("%M") am_pm = start.strftime("%p") print("Start time:",month,day,"at",hours,":",minutes,am_pm) input("Press Enter to stop...") stop = datetime.now() month = stop.strftime("%B") day = stop.strftime("%d") hours = stop.strftime("%I") minutes = stop.strftime("%M") am_pm = stop.strftime("%p") print("Stop time: ",month,day,"at",hours,":",minutes,am_pm) elapsed_time = stop - start new_days = elapsed_time.days new_minutes = elapsed_time.seconds // 60 new_hours = new_minutes // 60 new_minutes = new_minutes % 60 print("Time elapsed: ") if new_days > 0: print("days:",new_days) print("hours:", new_hours, ", minutes:", new_minutes) if __name__ == "__main__": main() ``` Refer to Code Example 11-1: If the timer is started on November 17 at 4:00 pm and stopped three seconds later, what will display under Time elapsed:?
Time elapsed: | hours: 0, minutes: 0
217
February 8, 1998 fell on a Sunday. What would the following code display? from datetime import datetime birthday = datetime(1998, 2, 8) birthday = birthday.strftime("%B %d, %Y (%A)") print("Your birthday is:", birthday)
Your birthday is: February 08, 1998 (Sunday)
218
In 2017 New Year’s Day fell on a Sunday. What would the following code display? from datetime import datetime new_year = datetime(2017, 1, 1) day_of_week = new_year.strftime("New Year's Day is on a %A") print(new_year) print(day_of_week)
2017-01-01 00:00:00 | New Year's Day is on a Sunday
219
To compare two datetime objects, you
can use any of the comparison operators
220
To create a datetime object by parsing a string, you can use the
strptime() method of the datetime class
221
To create a datetime object for the current date and time, you can use the
now() method of the datetime class
222
To create a datetime object with a constructor, you have to pass this sequence of arguments to it:
year, month, day
223
To format a datetime object for the current date and time, you can use the
strftime() method of the datetime object
224
To store just the year, month, and day for a date, you use a
date object
225
To work with dates, you need to import
the date class from the datetime module
226
What will be displayed after the following code executes? from datetime import datetime today = datetime(2018, 4, 26) birthday = datetime(2018, 6, 21) wait_time = birthday - today days = wait_time.days print("There are", days, "days until your birthday!")
There are 56 days until your birthday!
227
What will the following code display if the user enters 21/11/2018 at the prompt? from datetime import datetime today = input("Enter today's date: ") this_day = datetime.strptime(today, "%m/%d/%Y") print(this_day)
ValueError: time data '21/11/2018' does not match format '%m/%d/%Y'
228
``` What will the following code display? from datetime import datetime this_day = date(2018, 2, 8) this_day = this_day.strptime("%B %d, %Y") print(this_day) ```
NameError: name 'date' is not defined
229
``` What would the following code display? from datetime import date this_day = date(2018, 2, 8) this_day = this_day.strftime("%B %d, %Y") print("Today is:", this_day) ```
Today is: February 08, 2018
230
When you create a datetime object by parsing a string, you pass the parsing method
a string that represents the date and a formatting string that determines the parsing
231
When you subtract one datetime object from another, you get
a timedelta object
232
You can access the parts of a date/time object by using its
attributes
233
A dictionary stores a collection of
unordered items
234
Code Example 12-1 1. flowers = {"red": "rose", "white": "lily", "yellow": "buttercup"} 2. print(flowers) 3. flowers["blue"] = "carnation" 4. print(flowers) 5. print("This is a red flower:", flowers.get("red", "none")) 6. key = "white" 7. if key in flowers: 8. flower = flowers[key] 9. print("This is a", key, "flower:", flower) 10. key = "green" 11. if key in flowers: 12. flower = flowers[key] 13. del flowers[key] 14. print(flower + " was deleted") 15. else: 16. print("There is no " + key + " flower") Refer to Code Example 12-1: Which of the following represents a key/value pair for the dictionary named flowers defined on line 1?
red/rose
235
Code Example 12-1 1. flowers = {"red": "rose", "white": "lily", "yellow": "buttercup"} 2. print(flowers) 3. flowers["blue"] = "carnation" 4. print(flowers) 5. print("This is a red flower:", flowers.get("red", "none")) 6. key = "white" 7. if key in flowers: 8. flower = flowers[key] 9. print("This is a", key, "flower:", flower) 10. key = "green" 11. if key in flowers: 12. flower = flowers[key] 13. del flowers[key] 14. print(flower + " was deleted") 15. else: 16. print("There is no " + key + " flower") Refer to Code Example 12-1: Which of the following will be displayed by the print statement on line 4?
{'blue': 'carnation', 'red': 'rose', 'white': 'lily', 'yellow': 'buttercup'}
236
Code Example 12-1 1. flowers = {"red": "rose", "white": "lily", "yellow": "buttercup"} 2. print(flowers) 3. flowers["blue"] = "carnation" 4. print(flowers) 5. print("This is a red flower:", flowers.get("red", "none")) 6. key = "white" 7. if key in flowers: 8. flower = flowers[key] 9. print("This is a", key, "flower:", flower) 10. key = "green" 11. if key in flowers: 12. flower = flowers[key] 13. del flowers[key] 14. print(flower + " was deleted") 15. else: 16. print("There is no " + key + " flower") Refer to Code Example 12-1: What would the print statement on line 5 display?
This is a red flower: rose
237
Code Example 12-1 1. flowers = {"red": "rose", "white": "lily", "yellow": "buttercup"} 2. print(flowers) 3. flowers["blue"] = "carnation" 4. print(flowers) 5. print("This is a red flower:", flowers.get("red", "none")) 6. key = "white" 7. if key in flowers: 8. flower = flowers[key] 9. print("This is a", key, "flower:", flower) 10. key = "green" 11. if key in flowers: 12. flower = flowers[key] 13. del flowers[key] 14. print(flower + " was deleted") 15. else: 16. print("There is no " + key + " flower") Refer to Code Example 12-1: What would the print statement on line 9 display?
This is a white flower: lily
238
Code Example 12-1 1. flowers = {"red": "rose", "white": "lily", "yellow": "buttercup"} 2. print(flowers) 3. flowers["blue"] = "carnation" 4. print(flowers) 5. print("This is a red flower:", flowers.get("red", "none")) 6. key = "white" 7. if key in flowers: 8. flower = flowers[key] 9. print("This is a", key, "flower:", flower) 10. key = "green" 11. if key in flowers: 12. flower = flowers[key] 13. del flowers[key] 14. print(flower + " was deleted") 15. else: 16. print("There is no " + key + " flower") Refer to Code Example 12-1: What is the last line that this code prints to the console?
There is no green flower
239
``` Code Example 12-2 1. flowers = {"white": "lily", "red": "rose", "blue": "carnation", "yellow": "buttercup"} 2. colors = list(flowers.keys()) 3. colors.sort() 4. show_colors = "Colors of flowers: " 5. for color in colors: 6. show_colors += color + " " 7. print(show_colors) 8. pick_color = input("Enter a color: ") 9. pick_color = pick_color.lower() 10. if pick_color in flowers: 11. name = flowers[pick_color] 12. print("Flower name: " + name) 13. else: 14. print("There is no " + pick_color + " flower.") ``` Refer to Code Example 12-2: What will the print statement on line 7 display?
Colors of flowers: blue red white yellow
240
``` Code Example 12-2 1. flowers = {"white": "lily", "red": "rose", "blue": "carnation", "yellow": "buttercup"} 2. colors = list(flowers.keys()) 3. colors.sort() 4. show_colors = "Colors of flowers: " 5. for color in colors: 6. show_colors += color + " " 7. print(show_colors) 8. pick_color = input("Enter a color: ") 9. pick_color = pick_color.lower() 10. if pick_color in flowers: 11. name = flowers[pick_color] 12. print("Flower name: " + name) 13. else: 14. print("There is no " + pick_color + " flower.") ``` Refer to Code Example 12-2: If the user enters “Yellow” at the prompt on line 8, what does this code print to the console?
Flower name: buttercup
241
Code Example 12-3 pets = { "dog": {"type": "poodle", "color": "white"}, "cat": {"type": "Siamese", "color": "black and white"}, "bird": {"type": "parrot", "color": "green"} } pet = pets["dog"] pet = pets["bird"] print(pet["color"], pet["type"]) Refer to Code Example 12-3: What will display after the code executes?
green parrot
242
Code Example 12-3 pets = { "dog": {"type": "poodle", "color": "white"}, "cat": {"type": "Siamese", "color": "black and white"}, "bird": {"type": "parrot", "color": "green"} } pet = pets["dog"] pet = pets["bird"] print(pet["color"], pet["type"]) Refer to Code Example 12-3: Which of the following could you add to the end of this example to print “black and white Siamese cat” to the console?
pet = "cat" | print(pets[pet]["color"], pets[pet]["type"], pet)
243
Each item in a dictionary is
a key/value pair
244
How many items does the following dictionary contain? | flowers = {"red": "rose", "white": "lily", "yellow": "buttercup"}
3
245
If each row in a list of lists has exactly two columns, you can convert it to a dictionary by using the
dict() constructor
246
The items() method returns a
view object containing all of the key/value pairs in a dictionary
247
The keys() method returns a
The key in a dictionary can be
248
To avoid a KeyError when using the pop() method of a dictionary, you can
use the optional second argument to supply a default value
249
To convert a view object to a list, you can use the
list() constructor
250
To delete all items from a dictionary you can
use the clear() method