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
Q

What is the value of my_num after the following statement executes?
my_num = (50 + 2 * 10 - 4) / 2

A

33

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q
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
A

6.5

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

What is the value of number after the following statement executes?
number = (5 ** 2) * ((10 - 4) / 2)

A

75

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

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)

A

error: you cannot use the += operator to add a string variable to an int value

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

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?"”)

A

Welcome!
Now that you have learned about input
and output, you may be wondering, “What
is next?”

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

What will the following print() function display?

print(“lions”, “tigers”, “bears”, sep = ‘ & ‘, end = ‘ oh, my!!’)

A

lions & tigers & bears oh, my!!

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

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, “.”)

A

nothing is wrong with this code

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

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

a string variable is used in an arithmetic expression

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

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, “.”)

A

an undeclared variable name is used in the print() function

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

Which of the following data types would you use to store the number 25.62?

A

float

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

Which of the following doesn’t follow the best naming practices for variables?

A

pRate

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

Which of the following variable names uses camel case?

A

firstName

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

Which of the following will get a floating-point number from the user?

A

my_number = float(input(“Enter a number:”))

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

A for loop that uses a range() function is executed

A

once for each integer in the collection returned by the range() function

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

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?

A

Would you like to buy a widget? (y/n):

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

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?

A

You bought 0 widget(s) today.

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

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?

A
Define widget count variable
Begin infinite loop
     Get user input
     IF user buys widget
      add 1 to widget count
     ELSE
      end loop
Display results
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
42
Q

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)

A

The product is 6

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

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)

A

The product is 24

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

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=”, “)

A

1, 3, 6, 10,

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

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)

A

check_num <= 0 or check_num >= 1000

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

How many times will “Hi again!” be displayed after the following code executes?
for i in range(0, 12, 2):
print(“Hi, again!”)

A

6

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
47
Q
How many times will “Hi there!” be displayed after the following code executes?
num = 2
while num < 12:
    print("Hi, there!")
    num += 2
A

5

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

If you want to code an if clause, but you don’t want to perform any action, you can code

A

a pass statement

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

In a while loop, the Boolean expression is tested

A

before the loop is executed

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

Pseudocode can be used to plan

A

the coding of control structures

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
51
Q
Python will sort the strings that follow in this sequence:
Peach
peach
1peach
10Peaches
A

10Peaches, 1peach, Peach, peach

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

The and operator has

A

higher precedence than the or operator, but lower precedence than the not operator

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

To compare two strings with mixed uppercase and lowercase letters, a programmer can first use the

A

lower() method to convert all characters in each string to lowercase.

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

To jump to the end of the current loop, you can use the

A

break statement

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
55
Q
What will be displayed after the following code executes?
guess = 19
if guess < 19:
    print("Too low")
elif guess > 19:
    print("Too high")
A

nothing will display

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
56
Q
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.")
A

1 3 9

The loop has ended.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
57
Q
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
A

3 * 5 = 15
2 * 5 = 10
1 * 5 = 5

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
58
Q
What will this loop display?
sum = 0
for i in range(0, 25, 5):
    sum += i
print(sum)
A

50

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

When two strings are compared, they are evaluated based on the ___________________ of the characters in the string.

A

sort sequence

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

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

a while statement

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

Which of the following can use the range() function to loop through a block of statements?

A

a for statement

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

Which of the following creates a Boolean variable?

A

flag = True

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

Which of the following in this expression is evaluated first?
age >= 65 and status == “retired” or age < 18

A

age >= 65

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

Which of the following in this expression is evaluated first?
age >= 65 or age <= 18 or status == “retired”

A

age >= 65

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

Which of the following is not an acceptable way to code a nested structure?

A

nest an else clause within an elif clause

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

Which of the following is true for an if statement that has both elif and else clauses?

A

If the condition in the if clause is true, the statements in that clause are executed.

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

Which type of expression has a value of either true or false?

A

Boolean

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

Which of the following is not true of hierarchy charts?

A

Related functions should be combined into a single function.

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

A file that contains reusable code is called a

A

module

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

A global variable

A

is defined outside of all functions

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

A local variable is defined

A

inside a function

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

A return statement

A

can be used to return a local variable to the calling function

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

Assuming the random module has been imported into its default namespace, which of the following could possibly result in a value of 0.94?

A

number = random.random()

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

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?

A

number = random.randint(0, 1)

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

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?

A

number = random.randrange(2, 202, 2)

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

Before you can use a standard module like the random module, you need to

A

import the module

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
77
Q
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?

A

main()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
78
Q
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?

A

first, last

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
79
Q
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?

A

lopez.maria

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
80
Q
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?

A

local

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
81
Q
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?

A

60

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
82
Q
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))

A

40

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

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?

A

The sum is 11

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

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?

A

5, 6

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

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?

A

12, 12

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

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

A

the multiply() function

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

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?

A

The answer is 24

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

If you import two modules into the global namespace and each has a function named get_value(),

A

a name collision occurs

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

The best way to call the main() function of a program is to code

A

an if statement that calls the main() function only if the current module is the main module

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

The default namespace for a module is

A

the same as the name of the module

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

To assign a default value to an argument when you define a function, you

A

code the name of the argument, the assignment operator (=), and the default value

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

To call a function with named arguments, you code the

A

name of each argument, an equals sign, and the value or variable that’s being passed

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

To call a function, you code the function name and

A

a set of parentheses that contains zero or more arguments

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

To define a function, you code the def keyword and the name of the function followed by

A

a set of parentheses that contains zero or more arguments

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

Which of the following statements imports a module into the default namespace?

A

import temperature

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

Which of the following statements imports a module into the global namespace?

A

from temperature import *

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

Which of the following statements is not true about the documentation of a module?

A

You can use regular Python comments to document the functions of the module.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
98
Q
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

a.print_name(name)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
99
Q
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?
A

Programmer didn’t test for a 0 value in the denominator.

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

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?

A

change line 8 to: average_cost = round(item_total / (count - 1))

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

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?

A

The input statement on line 11 gets a variable named grade but sends in an undefined variable named score on line 12

102
Q

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?

A

The variable Lname on line 4 does not exist

103
Q

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?

A

The variable score has been input as a string so it must be converted to an int or float.

104
Q

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?

A

The curve is calculated after the score has been displayed.

105
Q

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?

A

change line 4 to: print(“The discount on this item is $”, round(discount, 2))

106
Q

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?

A

change line 5 to: pay = (40 * rate) + ((hours - 40) * rate * 1.5)

107
Q

The stack is available when an exception occurs. It displays a list of

A

just the functions that were called prior to the exception

108
Q

To test the functions of a module from the IDLE shell, you

A

import the module and then call any function from the IDLE shell

109
Q

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

A

line 1, syntax error

110
Q

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.”)
A

line 4, runtime error

111
Q

When the IDLE debugger reaches a breakpoint, you can do all but one of the following. Which one is it?

A

view the values of all the variables that you’ve stepped through

112
Q

When you plan the test runs for a program, you should do all but one of the following. Which one is it?

A

list the expected exceptions for each test run

113
Q

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?

A

display the values of the global constants used by the function

114
Q

When you use the IDLE debugger, you start by setting a breakpoint

A

on a statement before the statement you think is causing the bug

115
Q

Which of the following is not a common type of syntax error?

A

invalid variable names

116
Q

Which of the following is not true about top-down coding and testing?

A

You should always start by coding and testing the most difficult functions.

117
Q

Which type of error prevents a program from compiling and running?

118
Q

Which type of error throws an exception that stops execution of the program?

119
Q
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?

A

“Mike”, 98, “A”

120
Q

The __________ method adds an item to the end of a list.

121
Q

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)

A

The pet store sells: [‘dog’, ‘cat’, ‘ferret’, ‘hamster’, ‘bunny’, ‘canary’, ‘parrot’, ‘budgie’, ‘hawk’]
These start with the letter c: [‘cat’, ‘canary’]

122
Q

Which of the following is not true about a list of lists?

A

To delete an item in the outer list, you first have to delete the list in the item.

123
Q

Given the tuple that follows, which of the following assigns the values in the tuple to variables?
numbers = (22, 33, 44, 55)

A

w, x, y, z = numbers

124
Q

When you use a multiple assignment statement to unpack a tuple,

A

you assign the tuple to a two or more variable names separated by commas

125
Q

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

A

my_name = “Donny”, names = [“Lizzy”, “Mike”, “Joel”, “Anne”]

126
Q

To remove the item “mangos” from the following list, you would use which of these methods?
fruit = [“apple”, “banana”, “grapes”, “mangos”, “oranges”]

A

fruit.remove(“mangos”) or fruit.pop(3)

127
Q

When a function changes the data in a list, the changed list

A

does not need to be returned because lists are mutable.

128
Q

Which of the following statements about list copies is not true? When you make a

A

deep copy of a list, both variables refer to the same list.

129
Q
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]?

130
Q

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)

A

ghost
witch
ogre

131
Q

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

A

[‘sandwich’, ‘chips’, ‘pickle’, ‘apple pie’]

132
Q

Given the following code, what would the list consist of after the second statement?
ages = [22, 35, 24, 17, 28]
ages.insert(3, 4)

A

ages = [22, 35, 24, 4, 17, 28]

133
Q

Which of the following creates a tuple of six strings?

A

vehicles = (“sedan”,”SUV”,”motorcycle”,”bicycle”,”hatchback”,”truck”)

134
Q

Which of the following functions randomly selects one item in a list?

135
Q

Given the following list, what is the value of ages[5]?

ages = [22, 35, 24, 17, 28]

A

None: Index error

136
Q
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)

A

[[‘Mike’,98,’A’],[‘Lizzy’,73,’C’],[‘Joel’,88,’B+’],[‘Anne’,93,’A

137
Q

Which of the following would create a list named numbers consisting of 3 floating-point items?

A

numbers = [5.3, 4.8, 6.7]

138
Q
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?

A

Lizzy 73 C Mike 98 A Joel 88 B+ Anne 93 A

139
Q
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)
140
Q

Given the following list, what is the value of names[2]?

names = [“Lizzy”, “Mike”, “Joel”, “Anne”, “Donald Duck”]

141
Q

To refer to an item in a list, you code the list name followed by

A

an index number in brackets, starting with the number 0

142
Q

The primary difference between a tuple and a list is that a tuple

A

is immutable

143
Q

To insert the item “melon” after “grapes” in the following list, you would use which of these methods?
fruit = [“apple”, “banana”, “grapes”, “mangos”, “oranges”]

A

fruit.insert(3, “melon”)

144
Q

Which of the following is not true about a CSV file?

A

The csv module is a standard module so you don’t need to import it

145
Q

To read the rows in a CSV file, you need to

A

get a reader object by using the reader() function of the csv module

146
Q
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?

A

causes an exception if the file named classes.bin doesn’t exist

147
Q
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?

A

The list named courses.

148
Q

To work with a file when you’re using Python, you must do all but one of the following. Which one is it?

A

decode the data in the file

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

a new file named courses.csv is created

150
Q
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?

A

Python 3 Physics 4

151
Q
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?

A

Python (3)

Trig (3)

152
Q
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?

A

writes the courses list to a binary file if the file named classes.bin doesn’t exist

153
Q

A binary file is like a text file in all but one of the following ways. Which one is it?

A

A binary file stores numbers with binary notation.

154
Q

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

A
with open("prog.csv", "w", newline ="") as file:
    writer = csv.writer(file)
    writer.writerows(programming)
155
Q

To read a list of lists that’s stored in a binary file, you use

A

the load() method of the pickle module

156
Q

Which one of the following is not a benefit of using a with statement to open a file?

A

You don’t have to specify the path for the file.

157
Q

A Python program should use try statements to handle

A

all exceptions that can’t be prevented by normal coding techniques

158
Q
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?

A

FileNotFoundError

159
Q
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?

160
Q

If a program attempts to read from a file that does not exist, which of the following will catch that error?

A

FileNotFoundError and OSError

161
Q

It’s a common practice to throw your own exceptions to test error handling routines that

A

catch exceptions that are hard to produce otherwise

162
Q

The finally clause of a try statement

A

is executed whether or not an exception has been thrown

163
Q

To cancel the execution of a program in the catch clause of a try statement, you can use the

A

exit() function of the sys module

164
Q

To throw an exception with Python code, you use the

A

raise statement

165
Q

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?

A

the severity of the exception

166
Q

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?

A
try:
    number = float(input("Enter a number: "))
    print("Your number is: ", number)
except:
     print("Invalid number.")
167
Q

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?

A
try:
    number = int(input("Enter a number: "))
    print("Your number is: ", number)
except Exception as e:
    print(type(e), e)
168
Q

Within the try clause of a try statement, you code

A

a block of statements that might cause an exception

169
Q

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

A

is an integer with 5 spaces allowed for its display.

170
Q

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

A

is a floating-point number that should be displayed with 2 decimal places.

171
Q
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?

A

result1, result2, and result3

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

A

round the result of each expression to 2 decimal places

173
Q
Given that the locale module has been imported as lc, which block of code will display the number in this format?
£34,567.89
A

lc.setlocale(lc.LC_ALL, “uk”)

print(lc.currency(34567.89, grouping=True))

174
Q

If number equals .15605, which of the following will display it as:
16%

A

print(““.format(number))

175
Q

If number equals 3,237,945.76, which of the following will display it as:
3,237,945.76

A

print(““.format(number))

176
Q

One of the ways to deal with the inaccuracies that may result from floating-point arithmetic operations is to

A

round the results of those calculations that may lead to more decimal places than you want in the final result

177
Q

One of the ways to deal with the inaccuracies that may result from floating-point arithmetic operations is to

A

do the math with Decimal objects instead of floating-point numbers

178
Q

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?

A

from decimal import Decimal

number = Decimal(123.4567)

179
Q

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?

A

number = number.quantize(Decimal(“1.00”), ROUND_HALF_UP)

180
Q

Using floating-point numbers can lead to arithmetic errors because floating-point numbers

A

are approximate values

181
Q

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

A

Name ID
Liz 234
Mike 23456

182
Q

When you’re using Decimal objects in an arithmetic expression, you cannot use

A

floating-point values as operands

183
Q

Which of the following is not a floating-point number?

184
Q

Which of the following modules lets you work with decimal numbers instead of floating-point numbers?

185
Q

Which of the following modules provides a function for formatting currency in the US, UK, or parts of Europe?

186
Q

Which of the following modules provides a function for getting the square root of a number?

187
Q

Which of the following will produce the same result as this code?
import math as m
area = m.pi * radius**2

A

area = m.pi * m.pow(radius, 2)

188
Q

You can use the format() method of a string to format numbers in all but one of the following ways. Which one is it?

A

apply $ signs

189
Q

A Unicode character is represented by a

A

2-digit code

190
Q

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?

A

The strip() method on line 1 will strip away the extra whitespace.

191
Q

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?

A

The length of the number will be greater than 10 so the else clause will execute.

192
Q

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?

A

Phone number: (555)123-4567

193
Q

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

A

Mervin, you are quite a magician

194
Q
Given the following code, what would display?
car = "PORSCHE"
color = "red"
my_car = car.join(color)
print(my_car)
A

rPORSCHEePORSCHEd

195
Q

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!

A

print((word + “! “) * 2 + “ My kingdom for “ + word + “!”)

196
Q

The isdigit() method of a string returns

A

true if the string contains only digits

197
Q

The join() method of a list can be used to combine

A

the items in the list into a string that’s separated by delimiters

198
Q

To access the first three characters in a string that’s stored in a variable named message, you can use this code:

A

first_three = message[0:3]

199
Q

To determine the length of a string that’s in a variable named city, you can use this code:

200
Q

To retrieve the fourth character in a string that’s stored in a variable named city, you can use this code:

201
Q
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("-", ".")
202
Q
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)
203
Q

What is the value of the variable named result after this code is executed?
email = “marytechknowsolve.com”
result = email.find(“@”)

204
Q

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)

205
Q

What will be displayed after the following code executes?
book_name = “a tale for the knight”
book = book_name.title()
print(book)

A

A Tale For The Knight

206
Q

Which of the Python examples that follow can not be used to create a string named n2?

A
numbers = [8, 17, 54, 22, 35]
n2 = "".join(numbers)
207
Q
Which of the following code snippets will result in this display:
Countdown...
5...
4...
3...
2...
1...
Blastoff!
A
counting = "54321"
print("Countdown...")
for char in counting:
    print(char + "...")
print("Blastoff!")
208
Q

Which of the following statements will modify the string that’s stored in a variable named s?

A

You can’t modify a string.

209
Q

Which of the following will display this result?

B = 66

A

print(“B = “, ord(“B”))

210
Q

You can use the split() method to split a string into a list of strings based on a specified

211
Q

A naive datetime object doesn’t account for

A

time zones and daylight savings time

212
Q
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?

213
Q
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?

A

Time elapsed:

days: 1
hours: 2, minutes: 30

214
Q
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?

215
Q
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?

A

seconds is undefined

216
Q
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:?

A

Time elapsed:

hours: 0, minutes: 0

217
Q

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)

A

Your birthday is: February 08, 1998 (Sunday)

218
Q

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)

A

2017-01-01 00:00:00

New Year’s Day is on a Sunday

219
Q

To compare two datetime objects, you

A

can use any of the comparison operators

220
Q

To create a datetime object by parsing a string, you can use the

A

strptime() method of the datetime class

221
Q

To create a datetime object for the current date and time, you can use the

A

now() method of the datetime class

222
Q

To create a datetime object with a constructor, you have to pass this sequence of arguments to it:

A

year, month, day

223
Q

To format a datetime object for the current date and time, you can use the

A

strftime() method of the datetime object

224
Q

To store just the year, month, and day for a date, you use a

A

date object

225
Q

To work with dates, you need to import

A

the date class from the datetime module

226
Q

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!”)

A

There are 56 days until your birthday!

227
Q

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)

A

ValueError: time data ‘21/11/2018’ does not match format ‘%m/%d/%Y’

228
Q
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)
A

NameError: name ‘date’ is not defined

229
Q
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)
A

Today is: February 08, 2018

230
Q

When you create a datetime object by parsing a string, you pass the parsing method

A

a string that represents the date and a formatting string that determines the parsing

231
Q

When you subtract one datetime object from another, you get

A

a timedelta object

232
Q

You can access the parts of a date/time object by using its

A

attributes

233
Q

A dictionary stores a collection of

A

unordered items

234
Q

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?

235
Q

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?

A

{‘blue’: ‘carnation’, ‘red’: ‘rose’, ‘white’: ‘lily’, ‘yellow’: ‘buttercup’}

236
Q

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?

A

This is a red flower: rose

237
Q

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?

A

This is a white flower: lily

238
Q

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?

A

There is no green flower

239
Q
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?

A

Colors of flowers: blue red white yellow

240
Q
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?

A

Flower name: buttercup

241
Q

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?

A

green parrot

242
Q

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?

A

pet = “cat”

print(pets[pet][“color”], pets[pet][“type”], pet)

243
Q

Each item in a dictionary is

A

a key/value pair

244
Q

How many items does the following dictionary contain?

flowers = {“red”: “rose”, “white”: “lily”, “yellow”: “buttercup”}

245
Q

If each row in a list of lists has exactly two columns, you can convert it to a dictionary by using the

A

dict() constructor

246
Q

The items() method returns a

A

view object containing all of the key/value pairs in a dictionary

247
Q

The keys() method returns a

A

The key in a dictionary can be

248
Q

To avoid a KeyError when using the pop() method of a dictionary, you can

A

use the optional second argument to supply a default value

249
Q

To convert a view object to a list, you can use the

A

list() constructor

250
Q

To delete all items from a dictionary you can

A

use the clear() method