CPT 168 Final Review Flashcards
The __________ software for a computer provides the software that’s needed for running applications.
systems
The data in __________ is persistent so it is not lost when an application ends.
disk storage
To create a Python program, you use:
IDLE’s editor
The following is an example of \_\_\_\_\_\_\_\_\_\_. print("Hello out there!") # get input name = input("Who are you?") print("Goodbye, " , name)
source code
A console application runs
via a command prompt
The data in __________ is lost when an application ends.
main memory
Python is considered a good first language to learn because:
all of the above
A runtime error is also known as:
an exception
When an exception occurs while a program is running,
the program crashes and an error message is displayed
To run a Python program from IDLE, you use:
the F5 key
The goal of __________ is to fix all the errors in a program.
debugging
To test a Python statement, you use:
IDLE’s interactive shell
Which of the following translates bytecode into instructions for the computer?
the Python virtual machine
A web application runs
through a browser
The following is an example of \_\_\_\_\_\_\_\_\_\_. #!/usr/bin/env python 3
a shebang line
Which type of errors must be fixed before the program can be compiled?
syntax errors
The goal of __________ is to find all the errors in a program.
testing
Given that pi = 3.1415926535, which of the following print() functions displays:
pi = 3.14
print(“pi = “ + str(round(pi, 2)))
Given: x = 23 , y = 15
What is the value of new_num after the following statement executes?
new_num = x % y
8
Given: x = 23 , y = 15
What is the value of new_num after the following statement executes?
new_num = x // y
1
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
5.0
Python comments
all of the above
Python relies on correct __________ to determine the meaning of a statement.
indentation
What is the argument of the print() function in the following Python statement?
print(“My student ID is “ + str(123456) )
“My student ID is “ + str(123456)
What is the value of my_num after the following statement executes?
my_num = (50 + 2 * 10 - 4) / 2
33
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
What is the value of number after the following statement executes?
number = (5 ** 2) * ((10 - 4) / 2)
75
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
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?”
What will the following print() function display?
print(“lions”, “tigers”, “bears”, sep = ‘ & ‘, end = ‘ oh, my!!’)
lions & tigers & bears oh, my!!
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
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
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
Which of the following data types would you use to store the number 25.62?
float
Which of the following doesn’t follow the best naming practices for variables?
pRate
Which of the following variable names uses camel case?
firstName
Which of the following will get a floating-point number from the user?
my_number = float(input(“Enter a number:”))
A for loop that uses a range() function is executed
once for each integer in the collection returned by the range() function
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):
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.
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
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
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
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,
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
How many times will “Hi again!” be displayed after the following code executes?
for i in range(0, 12, 2):
print(“Hi, again!”)
6
How many times will “Hi there!” be displayed after the following code executes? num = 2 while num < 12: print("Hi, there!") num += 2
5
If you want to code an if clause, but you don’t want to perform any action, you can code
a pass statement
In a while loop, the Boolean expression is tested
before the loop is executed
Pseudocode can be used to plan
the coding of control structures
Python will sort the strings that follow in this sequence: Peach peach 1peach 10Peaches
10Peaches, 1peach, Peach, peach
The and operator has
higher precedence than the or operator, but lower precedence than the not operator
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.
To jump to the end of the current loop, you can use the
break statement
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
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.
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
What will this loop display? sum = 0 for i in range(0, 25, 5): sum += i print(sum)
50
When two strings are compared, they are evaluated based on the ___________________ of the characters in the string.
sort sequence
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
Which of the following can use the range() function to loop through a block of statements?
a for statement
Which of the following creates a Boolean variable?
flag = True
Which of the following in this expression is evaluated first?
age >= 65 and status == “retired” or age < 18
age >= 65
Which of the following in this expression is evaluated first?
age >= 65 or age <= 18 or status == “retired”
age >= 65
Which of the following is not an acceptable way to code a nested structure?
nest an else clause within an elif clause
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.
Which type of expression has a value of either true or false?
Boolean
Which of the following is not true of hierarchy charts?
Related functions should be combined into a single function.
A file that contains reusable code is called a
module
A global variable
is defined outside of all functions
A local variable is defined
inside a function
A return statement
can be used to return a local variable to the calling function
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()
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)
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)
Before you can use a standard module like the random module, you need to
import the module
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()
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
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
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
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
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
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
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
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
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
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
If you import two modules into the global namespace and each has a function named get_value(),
a name collision occurs
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
The default namespace for a module is
the same as the name of the module
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
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
To call a function, you code the function name and
a set of parentheses that contains zero or more arguments
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
Which of the following statements imports a module into the default namespace?
import temperature
Which of the following statements imports a module into the global namespace?
from temperature import *
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.
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)
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.
Code Example 5-1
- count = 1
- item_total = 0
- item = 0
- while count < 4:
- item = int(input(“Enter item cost: “))
- item_total += item
- count += 1
- average_cost = round(item_total / count)
- 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))
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
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
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.
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.
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))
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)
The stack is available when an exception occurs. It displays a list of
just the functions that were called prior to the exception
To test the functions of a module from the IDLE shell, you
import the module and then call any function from the IDLE shell
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
What line number of the following code contains an error and what type of error is it?
- count = 1
- while count <= 4:
- print(count, end=” “)
- i *= 1
- print(“\nThe loop has ended.”)
line 4, runtime error
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
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
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
When you use the IDLE debugger, you start by setting a breakpoint
on a statement before the statement you think is causing the bug
Which of the following is not a common type of syntax error?
invalid variable names
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.
Which type of error prevents a program from compiling and running?
syntax
Which type of error throws an exception that stops execution of the program?
runtime
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”
The __________ method adds an item to the end of a list.
append()
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’]
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.
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
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
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”]
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)
When a function changes the data in a list, the changed list
does not need to be returned because lists are mutable.
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.
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
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
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’]
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]
Which of the following creates a tuple of six strings?
vehicles = (“sedan”,”SUV”,”motorcycle”,”bicycle”,”hatchback”,”truck”)
Which of the following functions randomly selects one item in a list?
choice()
Given the following list, what is the value of ages[5]?
ages = [22, 35, 24, 17, 28]
None: Index error
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
Which of the following would create a list named numbers consisting of 3 floating-point items?
numbers = [5.3, 4.8, 6.7]
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
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
Given the following list, what is the value of names[2]?
names = [“Lizzy”, “Mike”, “Joel”, “Anne”, “Donald Duck”]
Joel
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
The primary difference between a tuple and a list is that a tuple
is immutable
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”)
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
To read the rows in a CSV file, you need to
get a reader object by using the reader() function of the csv module
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
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.
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
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
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
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)
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
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.
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)
To read a list of lists that’s stored in a binary file, you use
the load() method of the pickle module
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.
A Python program should use try statements to handle
all exceptions that can’t be prevented by normal coding techniques
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
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
If a program attempts to read from a file that does not exist, which of the following will catch that error?
FileNotFoundError and OSError
It’s a common practice to throw your own exceptions to test error handling routines that
catch exceptions that are hard to produce otherwise
The finally clause of a try statement
is executed whether or not an exception has been thrown
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
To throw an exception with Python code, you use the
raise statement
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
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.")
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)
Within the try clause of a try statement, you code
a block of statements that might cause an exception
Code Example 9-1
print(“ {:>10} {:>5}”.format(“Item”, “Price”, “Qty”))
print(“ {:10.2f} {:5d}”.format(“laptop”, 499.99, 1))
print(“ {:10.2f} {:5d}”.format(“charger”, 29.95, 3))
print(“ {: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.
Code Example 9-1
print(“ {:>10} {:>5}”.format(“Item”, “Price”, “Qty”))
print(“ {:10.2f} {:5d}”.format(“laptop”, 499.99, 1))
print(“ {:10.2f} {:5d}”.format(“charger”, 29.95, 3))
print(“ {: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.
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
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
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))
If number equals .15605, which of the following will display it as:
16%
print(““.format(number))
If number equals 3,237,945.76, which of the following will display it as:
3,237,945.76
print(““.format(number))
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
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
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)
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)
Using floating-point numbers can lead to arithmetic errors because floating-point numbers
are approximate values
What will be displayed when this code is executed?
name = “Name”
ID = “ID”
print(“ {:>5}”.format(name, ID))
print(“ {:7d}”.format(“Liz”, 234))
print(“ {:7d}”.format(“Mike”, 23456))
Name ID
Liz 234
Mike 23456
When you’re using Decimal objects in an arithmetic expression, you cannot use
floating-point values as operands
Which of the following is not a floating-point number?
-683
Which of the following modules lets you work with decimal numbers instead of floating-point numbers?
decimal
Which of the following modules provides a function for formatting currency in the US, UK, or parts of Europe?
locale
Which of the following modules provides a function for getting the square root of a number?
math
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)
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
A Unicode character is represented by a
2-digit code
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.
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.
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
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
Given the following code, what would display? car = "PORSCHE" color = "red" my_car = car.join(color) print(my_car)
rPORSCHEePORSCHEd
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 + “!”)
The isdigit() method of a string returns
true if the string contains only digits
The join() method of a list can be used to combine
the items in the list into a string that’s separated by delimiters
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]
To determine the length of a string that’s in a variable named city, you can use this code:
len(city)
To retrieve the fourth character in a string that’s stored in a variable named city, you can use this code:
city[3]
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
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
What is the value of the variable named result after this code is executed?
email = “marytechknowsolve.com”
result = email.find(“@”)
-1
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
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
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)
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!")
Which of the following statements will modify the string that’s stored in a variable named s?
You can’t modify a string.
Which of the following will display this result?
B = 66
print(“B = “, ord(“B”))
You can use the split() method to split a string into a list of strings based on a specified
delimiter
A naive datetime object doesn’t account for
time zones and daylight savings time
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
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
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
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
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
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)
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
To compare two datetime objects, you
can use any of the comparison operators
To create a datetime object by parsing a string, you can use the
strptime() method of the datetime class
To create a datetime object for the current date and time, you can use the
now() method of the datetime class
To create a datetime object with a constructor, you have to pass this sequence of arguments to it:
year, month, day
To format a datetime object for the current date and time, you can use the
strftime() method of the datetime object
To store just the year, month, and day for a date, you use a
date object
To work with dates, you need to import
the date class from the datetime module
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!
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’
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
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
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
When you subtract one datetime object from another, you get
a timedelta object
You can access the parts of a date/time object by using its
attributes
A dictionary stores a collection of
unordered items
Code Example 12-1
- flowers = {“red”: “rose”, “white”: “lily”, “yellow”: “buttercup”}
- print(flowers)
- flowers[“blue”] = “carnation”
- print(flowers)
- print(“This is a red flower:”, flowers.get(“red”, “none”))
- key = “white”
- if key in flowers:
- flower = flowers[key]
- print(“This is a”, key, “flower:”, flower)
- key = “green”
- if key in flowers:
- flower = flowers[key]
- del flowers[key]
- print(flower + “ was deleted”)
- else:
- 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
Code Example 12-1
- flowers = {“red”: “rose”, “white”: “lily”, “yellow”: “buttercup”}
- print(flowers)
- flowers[“blue”] = “carnation”
- print(flowers)
- print(“This is a red flower:”, flowers.get(“red”, “none”))
- key = “white”
- if key in flowers:
- flower = flowers[key]
- print(“This is a”, key, “flower:”, flower)
- key = “green”
- if key in flowers:
- flower = flowers[key]
- del flowers[key]
- print(flower + “ was deleted”)
- else:
- 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’}
Code Example 12-1
- flowers = {“red”: “rose”, “white”: “lily”, “yellow”: “buttercup”}
- print(flowers)
- flowers[“blue”] = “carnation”
- print(flowers)
- print(“This is a red flower:”, flowers.get(“red”, “none”))
- key = “white”
- if key in flowers:
- flower = flowers[key]
- print(“This is a”, key, “flower:”, flower)
- key = “green”
- if key in flowers:
- flower = flowers[key]
- del flowers[key]
- print(flower + “ was deleted”)
- else:
- 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
Code Example 12-1
- flowers = {“red”: “rose”, “white”: “lily”, “yellow”: “buttercup”}
- print(flowers)
- flowers[“blue”] = “carnation”
- print(flowers)
- print(“This is a red flower:”, flowers.get(“red”, “none”))
- key = “white”
- if key in flowers:
- flower = flowers[key]
- print(“This is a”, key, “flower:”, flower)
- key = “green”
- if key in flowers:
- flower = flowers[key]
- del flowers[key]
- print(flower + “ was deleted”)
- else:
- 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
Code Example 12-1
- flowers = {“red”: “rose”, “white”: “lily”, “yellow”: “buttercup”}
- print(flowers)
- flowers[“blue”] = “carnation”
- print(flowers)
- print(“This is a red flower:”, flowers.get(“red”, “none”))
- key = “white”
- if key in flowers:
- flower = flowers[key]
- print(“This is a”, key, “flower:”, flower)
- key = “green”
- if key in flowers:
- flower = flowers[key]
- del flowers[key]
- print(flower + “ was deleted”)
- else:
- 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
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
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
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
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)
Each item in a dictionary is
a key/value pair
How many items does the following dictionary contain?
flowers = {“red”: “rose”, “white”: “lily”, “yellow”: “buttercup”}
3
If each row in a list of lists has exactly two columns, you can convert it to a dictionary by using the
dict() constructor
The items() method returns a
view object containing all of the key/value pairs in a dictionary
The keys() method returns a
The key in a dictionary can be
To avoid a KeyError when using the pop() method of a dictionary, you can
use the optional second argument to supply a default value
To convert a view object to a list, you can use the
list() constructor
To delete all items from a dictionary you can
use the clear() method