Chapter 06
1) The code that includes the keyword "def" is called a _____.
a. function call
b. function definition
c. function reference
d. function constructor
2) After a function's last statement is executed, the program returns to the next line after the _____.
a. import statement
b. function definition
c. function call
d. start of the program
3) In the following code, the variable size is the function's _____.
def calc_square_area(size):
area = size * size
return area
val = float(input("Enter size of square: "))
square_area = calc_square_area(val)
print(f"A square of size {val} has area {square_area}")
a. parameter
b. argument
c. property
d. value
4) In the following code, the variable val is the function call's _____.
def calc_square_area(size):
area = size * size
return area
val = float(input("Enter size of square: "))
square_area = calc_square_area(val)
print(f"A square of size {val} has area {square_area}")
a. parameter
b. argument
c. property
d. value
5) What is output?
def calc(num1, num2):
return 1 + num1 + num2
print(calc(4, 5), calc(1, 2))
a. 9 3
b. 10 4
c. 145 112
d. 4, 5, 1, 2
6) Which correctly calls the add() function?
def add(a, b, c):
return a + b + c
a. add(2 4 6)
b. add(2 + 4 + 6)
c. add(2; 4; 6)
d. add(2, 4, 6)
7) Which of the following is true?
a. A function must have exactly one return statement, or no return statement at all.
b. A function must always have at least one return statement.
c. A function can only return strings and numbers, not lists or dictionaries.
d. A function can have any number of return statements, or no return statement at all.
8) Which XXX is valid for the following code?
def calc_sum(a, b):
return a + b
XXX
print(y)
a. y = calc_sum()
b. y = calc_sum(4, 5)
c. y = calc_sum(4 + 5)
d. calc_sum(y, 4, 5)
9) Which XXX causes the program to output the message "Hello!"?
def print_message():
print("Hello!")
XXX
a. print_message
b. print_message()
c. def print_message()
d. print_message("Hello!")
10) After the program runs, what is the value of y?
def print_sum(num1, num2)
print(num1 + num2)
y = print_sum(4, 5)
a. 4 5
b. 9
c. 45
d. None
11) Which line in the function print_greeting() must be changed if the user wishes to print the greeting
three times with three different names?
def print_greeting(name):
print("Welcome message:")
print(f"Greetings {name}")
a. def print_greeting()
b. print("Welcome message:")
c. print("Greetings", name)
d. None. To print the greeting with three different names, the main program must call print_greeting()
three times with three different arguments.
12) What is the result when the program is executed?
def add(x, y):
return x + y
print("Begin test")
s = add("hello", 5)
print(s)
print("End test")
a. The program outputs "Begin test", then an error is generated, and the program exits.
b. An error is generated before anything is printed.
c. The program outputs "Begin test", followed by "hello5", followed by "End test"
d. The program outputs "Begin test", followed by "End test", and no other text is printed.
13) Which term describes how Python assigns the type of a variable?
a. dynamic typing
b. static typing
c. quick typing
d. random typing
14) _____ allows a function or operator to perform different tasks depending on the types of the
arguments or operands.
a. Polymorphism
b. Static typing
c. Type declaration
d. Prototyping
15) Which of the following isnota reason to use functions?
a. To avoid writing redundant code
b. To improve code readability
c. To support modular development
d. To make the code run faster
16) Given the following function. To change the function to return the product instead of the sum, how
many lines of code need to be changed?
def calculate(a, b):
return a + b
print(calculate(3, 4))
print(calculate(5, 2))
print(calculate(6, 7))
a. 1
b. 2
c. 3
d. 4
17) How does the given function improve the code versus if no function was present?
def fahrenheit_to_celsius(fahrenheit):
return (fahrenheit - 32.0) * 5.0 / 9.0
fahrenheit = float(input())
c1 = fahrenheit_to_celsius(fahrenheit);
c2 = fahrenheit_to_celsius(32.0);
c3 = fahrenheit_to_celsius(72.0);
a. The use of the function makes the program run faster
b. The use of the function decreases redundant code
c. The use of the function reduces the number of variables in the code
d. The function does not improve the code
18) Which function is most appropriate to improve the given code?
power_consumption_app1 = 600.85
hours_of_use1 = 12.8
energy_per_day1 = (power_consumption_app1 * hours_of_use1) / 1000
power_consumption_app2 = 1800.45
hours_of_use2 = 0.45
energy_per_day2 = (power_consumption_app2 * hours_of_use2) / 1000
power_consumption_app3 = 70
hours_of_use3 = 1.5
energy_per_day3 = (power_consumption_app3 * hours_of_use3) / 1000
total_energy_consumed = energy_per_day1 + energy_per_day2 + energy_per_day3
print(f"The total energy consumed per day is {total_energy_consumed:f}")
a. def compute_total(energy_day1, energy_day2, energy_day3):
return energy_per_day1 + energy_per_day2 + energy_per_day3
b. def input_values(power, hours):
power = float(input())
hours = float(input())
c. def compute_energy_consumed(power, hours):
return (power * hours) / 1000
d. def print_power_consumed(total_energy_consumed):
print(total_energy_consumed)
19) Which variable can be used in place of XXX in the following code?
def fahrenheit_to_celsius(f):
fraction = 5 / 9
c = (f - 32) * fraction
return c
degrees = float(input("Enter degrees in Fahrenheit: "))
print(fahrenheit_to_celsius(XXX))
a. degrees
b. f
c. c
d. fraction
20) Which statement uses the square() function to assign the variable t with 16? Note that 16 = 2⁴ = (2²)²
def calc_square(x):
return x * x
a. t = calc_square(calc_square(2))
b. t = calc_square(2) + calc_square(2)
c. t = calc_square(2), calc_square(2)
d. t = calc_square(4) * calc_square(2)
21) Which of the following lines of code is not valid, given the definitions of the calc_cube() and display()
functions?
def calc_cube(x):
return x * x * x
def display(x):
print(x)
a. y = calc_cube(2.0)
b. calc_cube(x) = 8.0
c. display("Test")
d. display(calc_cube(2.0))
22) Which of the following types of constructs should be called when the programmer wants to stop
program execution?
a. Use a pass statement
b. Raise NotImplementedError
c. Print a "FIXME" message and return -1
d. return None
23) Which of the following is not a valid technique to create a function stub?
a. Use a pass statement
b. Raise NotImplementedError
c. Print a "FIXME" message and return -1
d. Leave the function body empty
24) Which of the following is an advantage of using function stubs?
a. Makes code run faster
b. Requires fewer test cases
c. Removes the need for testing
d. Helps with incremental programming
25) What is the output?
def print_water_temp_for_coffee(temp):
if temp < 195:
print("Too cold.")
elif (temp >= 195) and (temp <= 205):
print("Perfect temperature.")
elif (temp > 205):
print("Too hot.")
print_water_temp_for_coffee(205)
print_water_temp_for_coffee(190)
a. Too cold.
b. Perfect temperature.
c. Perfect temperature.
Too cold.
d. Perfect [Link] cold.
26) What is the output?
def print_fever_check(temperature):
NORMAL_TEMP = 98.6
CUTOFF_TEMP = 95
degrees_of_fever = 0
if (temperature > NORMAL_TEMP):
degrees_of_fever = temperature - NORMAL_TEMP
print(f"You have {degrees_of_fever:f} degrees of fever.")
elif (temperature < CUTOFF_TEMP):
degrees_of_fever = CUTOFF_TEMP - temperature
print(f"Your temperature is {degrees_of_fever:f} below 95.")
body_temperature = 96.0
print("Checking for fever…")
print_fever_check(body_temperature)
a. (Nothing is outputted)
b. Checking for fever...
Your temperature is 2.6 below 95.
c. Checking for fever...Your temperature is 2.6 below 95.
d. Checking for fever...
27) For the given program, how many print statements will execute?
def print_shipping_charge(item_weight):
if (item_weight > 0.0) and (item_weight <= 10.0):
print(item_weight * 0.75)
elif (item_weight > 10.0) and (item_weight <= 15.0):
print(item_weight * 0.85)
elif (item_weight > 15.0) and (item_weight <= 20.0):
print(item_weight * 0.95)
print_shipping_charge(18)
print_shipping_charge(6)
print_shipping_charge(25)
a. 1
b. 2
c. 3
d. 9
28) Which XXX completes the find_smallest() function?
def find_smallest(a, b, c):
if a <= b and a <= c:
smallest = a
elif b <= a and b <= c:
smallest = b
elif c <= a and c <= b:
smallest = c
XXX
result = find_smallest(7, 4, 8)
print(result)
a. return a
b. return b
c. return c
d. return smallest
29) Which XXX will display one more than half of the smallest value of w1, w2, and w3?
def find_min_value(a, b, c):
if a <= b and a <= c:
return a
elif b <= a and b <=c:
return b
else:
return c
w1 = 7
w2 = 3
w3 = 12
y = XXX
print(y)
a. find_min_value(w1, w2, w3)/2 + 1
b. find_min_value(w1+1, w2+1, w3+3)/2
c. find_min_value()/2 + 1, w1, w2, w3
d. find_min_value: w1, w2, w3() /2 + 1
30) Which statement causes the face with "x" characters for eyes to be printed?
def print_x_eyes():
print("x x")
def print_o_eyes():
print("o o")
def face(eyes):
eyes()
print(" > ")
print("----")
a. face(print_x_eyes())
b. face(print_x_eyes)
c. print_x_eyes()
face()
d. face("x")
31) What statement replaces XXX, causing the program to print the word "hello"?
def print_hello():
print("hello")
XXX
alternate()
a. print_hello(alternate)
b. alternate() = print_hello()
c. print_hello = alternate
d. alternate = print_hello
32) What is the output?
def print_message1():
print("Message #1")
def print_message2():
print("Message #2")
print_message1 = print_message2
print_message2 = print_message1
print_message1()
print_message2()
a. Message #1
Message #1
b. Message #1
Message #2
c. Message #2
Message #1
d. Message #2
Message #2
33) What is the output?
def find_sqr(a):
t = a * a
return t
square = find_sqr(10)
print(square)
a. 0
b. 10
c. 100
d. (Nothing is outputted)
34) Function calc_sum() was copied and modified to form the new function calc_product(). Which line of
the new function contains an error?
def calc_sum(a, b):
s = a + b
return s
def calc_product(a, b): # Line 1
p = a * b # Line 2
return s # Line 3
a. Line 1
b. Line 2
c. Line 3
d. None of the lines contains an error
35) Which line of the function has an error?
def compute_sum_of_squares(num1, num2): # Line 1
sum = (num1 * num1) + (num2 * num2) # Line 2
return # Line 3
a. Line 1
b. Line 2
c. Line 3
d. None of the lines contains an error
36) What is the error?
cone_vol = cone_volume(2, 4)
print(cone_vol)
def compute_square(r):
return r * r
def cone_volume(r, h):
return (0.33) * 3.14 * compute_square(r) * h
a. No error, the program executes and outputs the correct value
b. Undefined function compute_square()
c. Undefined variable cone_vol()
d. Undefined function cone_volume()
37) What is the output?
def is_even(num):
if num % 2 == 0:
even = True
else:
even = False
is_even(7)
print(even)
a. False
b. True
c. No output: Call to is_even() fails due to no return value
d. No output: An error occurs due to unknown variable even
38) What is the output?
LB_PER_KG = 2.2
def kgs_to_lbs(kilograms):
pounds = kilograms * LB_PER_KG
return pounds
pounds = kgs_to_lbs(10)
print(pounds)
a. 22
b. No output: LB_PER_KG causes an error due to being outside any function
c. No output: LB_PER_KG must be declared within kgs_to_lbs()
d. No output: Variable pounds declared in two functions causes an error
39) In Python, a namespace is which type of data structure?
a. String
b. Tuple
c. List
d. Dictionary
40) Which of the following isnotone of the main scopes that Python uses to manage namespaces?
a. Namespace scope
b. Built-in scope
c. Global scope
d. Local scope
41) If two variables with the same name exist in the Local scope and the Global scope, which variable
will be used in an assignment statement?
a. The Local scope variable
b. The Global scope variable
c. Neither scope, this situation would cause an error
d. Neither scope, this situation is impossible to create
42) What code replaces XXX to make the program output the number 10?
multiplier = 1
def do_multiplication(x):
return x * multiplier
def set_multiplier(x):
XXX
multiplier = x
user_value = 5
set_multplier(2)
print(do_multiplication(user_value))
a. set_multiplier(2)
b. global multiplier
c. global x
d. do_multiplication(x)
43) The process of searching namespaces for a name is called _____.
a. global search
b. memory check
c. variable lookup
d. scope resolution
44) Standard Python functions such as int(), range() etc. are part of the _____ scope.
a. Local
b. Global
c. Built-in
d. Internal
45) _____ objects have fixed values that can't be changed.
a. Value
b. Class
c. Mutable
d. Immutable
46) A(n) _____ is an example of a mutable object type.
a. list
b. string
c. float
d. int
47) What is the output?
def modify(names, score):
[Link]("Robert")
score = score + 20
players = ["James", "Tanya", "Roxanne"]
score = 150
modify(players, score)
print(players, score)
a. ['James', 'Tanya', 'Roxanne'] 150
b. ['James', 'Tanya', 'Roxanne'] 170
c. ['James', 'Tanya', 'Roxanne', 'Robert'] 150
d. ['James', 'Tanya', 'Roxanne', 'Robert'] 170
48) What is the output?
def reset(data):
data[1] = 34
print(data)
data = [15, 0, 47, 12, 0]
reset(data)
print(data)
a. 34 [15, 0, 47, 12, 0]
b. [15, 34, 47, 12, 0] [15, 34, 47, 12, 0]
c. 34 [15, 34, 47, 12, 0]
d. [15, 0, 47, 12, 0] [15, 0, 47, 12, 0]
49) Which function call would cause a logic error?
def print_product(product_name, product_id, cost):
print(f"{product_name} (id: #{product_id}) - ${cost:.2f}")
a. print_product("Speakers", 21224, 32.99)
b. print_product("Speakers", 32.99, 21224)
c. print_product("Speakers", cost=32.99, product_id=21224)
d. print_product(product_id=21224, product_name="Speakers", cost=32.99)
50) What is the output?
def print_app(app_id, plan="basic", term=30):
print(f"App:{app_id} ({plan} plan, {term} days)")
print_app(10032, term=14)
a. App:10032 (basic plan, 14 days)
b. App:10032 (basic plan, 30 days)
c. App:10032 (plan, 14 days)
d. No output: the function call produces an error
51) What is the output?
def display(product, options=[]):
if "monitor" in product:
[Link]("HDMI")
print(product, options)
display("Acer monitor")
display("Samsung monitor")
a. Acer monitor
Samsung monitor
b. Acer monitor ["HDMI"]
Samsung monitor ["HDMI"]
c. Acer monitor ["HDMI"]
Samsung monitor ["HDMI", "HDMI"]
d. No output: using a list as a default argument is an error
52) Which function call will produce an error?
def purchase(user_name, id_number=-1, item_name="None", quantity=0):
# ... process a user's purchase as required ...
a. purchase(item_name="Orange", user_name="Leia")
b. purchase("Leia")
c. purchase("Leia", 123, "Orange", 10)
d. purchase(item_name="Orange", 10)
53) Which statement istrueabout the *args and **kwargs special arguments?
a. Any single function definition can only define *args or **kwards, but never both.
b. Both may be used in a single function call, but *args must appear before **kwargs in the argument list
c. Both may be used in a single function definition, but **kwargs must appear before *args in the
argument list.
d. Both may be used in a single function definition, and *args and **kwargs may appear in any order in
the argument list.
54) Which uses the concat() function to output: red fish blue fish?
def concat(*args):
s = ""
for item in args:
s += " " + item
return s
a. print(concat(["red, blue"], "fish"))
b. print(concat(red), concat(fish), concat(blue), concat(fish))
c. print(concat("red", "fish", "blue", "fish"))
d. print(concat(red, fish, blue, fish))
55) What is the output?
def gen_command(application, **kwargs):
command = application
for key in kwargs:
value = kwargs[key]
command += f" --{key}={value}"
return command
print(gen_command("ls", color="always", sort="size", format="long"))
a. ls color=always sort=size format=long
b. ls --color=always --sort=size --format=long
c. ls color="always" sort="size" format="long"
d. ls --"color"="always" --"sort"="size" --"format"="long"
56) Which statement would replace XXX so that the output is: 4, 12, 30?
def get_stats(int_list):
result_sum = 0
result_min = int_list[0]
result_max = int_list[0]
for value in int_list:
result_sum += value
if value < result_min:
result_min = value
if value > result_max:
result_max = value
return result_sum, result_min, result_max
values = [ 6, 4, 12, 8 ]
XXX
print(f"{a}, {b}, {c}")
a. a, b, c = get_stats(values)
b. c = get_stats(values)
a = get_stats(value)
b = get_stats(value)
c. result_min, result_max, result_sum = get_stats(values)
d. c, a, b = get_stats(values)
57) Which choice isnota valid call of the get_random_pair() method?
def get_random_pair():
a = [Link](0, 100)
b = [Link](0, 100)
return a, b
a. [x, y] = get_random_pair()
b. (x, y) = get_random_pair()
c. x y = get_random_pair()
d. x, y = get_random_pair()
58) Which symbols are used to start and end a docstring?
a. One quotation mark (")
b. Two quotation marks ("")
c. Three quotation marks (""")
d. Four quotation marks ("""")
59) Which is the correct location to place a docstring for a function?
a. The first line of the file
b. The first line in the function body
c. The last line in the function body
d. The first line before the function definition
60) Which function gives the change in temperature for an object, given the heat transfer, mass and
specific heat capacity? Note that Q=mcΔT , where Q is heat transfer, m is mass, c is specific heat
capacity, and ΔT is the change in temperature.
a. def temperature_change(q, m, c):
return q / (m * c)
b. def heat_transfer(m, c, delta_T):
return m * c * delta_T
c. def heat_transfer(m, c, delta_T):
return q / (m * c)
d. def temperature_change(q, m, c):
return (m * c) / q
61) Which X and Y cause the program to print the final velocity in feet per second? Note that the distance
and initial_velocity are given using meters instead of feet.
def final_velocity(initial_velocity, distance, time):
return 2 * distance / time - initial_velocity
def meters_to_feet(distance_in_meters):
return 3.28084 * distance_in_meters
# display final velocity in feet per second
t = 35 # seconds
d = 7.2 # meters
v_i = 4.6 # meters / second
print(f"Final velocity: {final_velocity(X, Y, t):f} feet/s")
a. X = meters_to_feet(v_i), Y = meters_to_feet(d)
b. X = v_i, Y = meters_to_feet(d)
c. X = meters_to_feet(v_i), Y = d
d. X = v_i, Y = d