Every problem in the chapter beside the book’s answer, a chapter at a time as you scroll.
Chapter 6: Functions
49 problems · 0 figuresConcepts in Practice 6.1.1 §6.1 source ↗
1 input_num = 14 2 offset_num = input_num - 10 3 print(offset_num)
- a.line 1
- b.line 2
- c.line 3
Answer
print() function is called to output the variable, offset_num.Concepts in Practice 6.1.2 §6.1 source ↗
print("Please log in")
username = input("Username:")
password = input("Password:")
print("Login successful")
print("Welcome,", username)- a.1
- b.3
- c.5
Answer
print() once. Lines 2 and 3 call a different function, input().Concepts in Practice 6.1.3 §6.1 source ↗
# Use float() to convert input for area calculation
width = float(input("Enter width:"))
height = float(input("Enter height:"))
print("Area is", width*height)- a.3
- b.5
- c.6
Answer
float() and input(). Line 3 calls print() for a total of five function calls.Concepts in Practice 6.1.4 §6.1 source ↗
def water_plant:
- a.A docstring should go after the colon.
- b.Parentheses should go after
water_plant. - c.
defshould bedefinebeforewater_plant.
Answer
water_plant. def water_plant(): .Concepts in Practice 6.1.5 §6.1 source ↗
def print_phone_num():
print("Phone: (", 864, ")", 555, "-", 0199)
print("User info:")
print_phone_num()- a.
Phone: ( 864 ) 555 - 1000
User info:
Phone: ( 864 ) 555 - 1000 - b.
User info: - c.
User info:
Phone: ( 864 ) 555 - 1000
Answer
User info: Phone: ( 864 ) 555 - 1000 "User info:" and then calls print_phone_num(), which outputs the phone number.Concepts in Practice 6.1.6 §6.1 source ↗
print_pc_specs()?- a.
print_pc_specs - b.
print_pc_specs() - c.
print_pc_specs():
Answer
print_pc_specs()Concepts in Practice 6.1.7 §6.1 source ↗
- a.
calc_tax - b.
calculate user tax - c.
c_t
Answer
calc_taxcalc_tax is concise, in snake case, and indicates the function's task.Concepts in Practice 6.1.8 §6.1 source ↗
Consider the code above.
If the points were changed from floats to integers, how many statements would need to be changed in the original and revised programs respectively?- a.3, 1
- b.4, 4
- c.12, 4
Answer
Concepts in Practice 6.1.9 §6.1 source ↗
Consider the code above.
How many times cancalc_distance() be called?- a.1
- b.3
- c.many
Answer
calc_distance() 10 times is equivalent to 60 statements in the original program.Concepts in Practice 6.2.1 §6.2 source ↗
1 def park_greet():
2 """Output greeting."""
3 print("Welcome. Open sunrise to sunset.")
4
5 car_count = 1
6 park_greet()
7 if car_count > 50:
8 # Direct to extra parking lot- a.1
- b.3
- c.5
Answer
park_greet() is called on line 6 and executed.Concepts in Practice 6.2.2 §6.2 source ↗
park_greet() is called. Which line does control flow move to next? 1 def extra_lot():
2 # Function definition
3
4 def park_greet():
5 """Output greeting."""
6 print("Welcome. Open sunrise to sunset.")
7
8 car_count = 1
9 park_greet()
10 if car_count > 50:
11 extra_lot()- a.1
- b.4
- c.10
Answer
park_greet() is defined, at line 4.Concepts in Practice 6.2.3 §6.2 source ↗
extra_lot() is called. Which line does control flow move to after line 3 is executed? 1 def extra_lot():
2 """Output extra parking lot info."""
3 print("Take the second right to park.")
4
5 def park_greet():
6 """Output greeting."""
7 print("Welcome. Open sunrise to sunset.")
8
9 car_count = 1
10 park_greet()
11 if car_count > 50:
12 extra_lot()- a.5
- b.8
- c.12
Answer
extra_lot(), so control flow returns to line 12.Concepts in Practice 6.2.4 §6.2 source ↗
def park_greet():
"""Output greeting."""
print("Welcome to the park")
print("Open sunrise to sunset")
park_greet()- a.
Welcome to the park - b.
Welcome to the park
Open sunrise to sunset - c.
Open sunrise to sunset
Welcome to the park
Answer
Open sunrise to sunset Welcome to the parkprint("Open ...") is unindented, so the statement is not a part of park_greet() and is executed first. Then, park_greet() is called, and print("Welcome ...") is executed.Concepts in Practice 6.2.5 §6.2 source ↗
Consider the book club example above.
How many function calls occur during the execution of the program?- a.2
- b.3
- c.6
Answer
for loop has three iterations. Each iteration calls print_book_club(), which calls print_conf(). So the program calls print_book_club() three times and print_conf() three times.Concepts in Practice 6.2.6 §6.2 source ↗
Consider the book club example above.
When line 3 is reached and executed, which line does control flow return to?- a.1
- b.11
- c.16
Answer
print_conf(). Then print_book_club() finishes, and control flow returns to line 16, which called print_book_club().Concepts in Practice 6.3.1 §6.3 source ↗
num = float(input()) num_sq = num * num print(num, "squared is", num_sq)
- a.
numonly - b.
num_sqonly - c.
numandnum_sq
Answer
num and num_sqnum and num_sq are created outside of functions and are global variables.Concepts in Practice 6.3.2 §6.3 source ↗
def print_square(): num_sq = num * num print(num, "squared is", num_sq) num = float(input()) print_square()
- a.
numonly - b.
num_sqonly - c.
numandnum_sq
Answer
num onlynum is created outside of a function and is global. num_sq is created in print_square() and is not global.Concepts in Practice 6.3.3 §6.3 source ↗
num? def print_double(): num_d = num * 2 print(num, "doubled is", num_d) def print_square(): num_sq = num * num print(num, "squared is", num_sq) num = float(input()) print_double() print_square()
- a.
print_double() - b.
print_square() - c.
print_double()andprint_square()
Answer
print_double() and print_square()num is global and can be accessed anywhere in the program, including both print_double() and print_square().Concepts in Practice 6.3.4 §6.3 source ↗
def print_time(): out_str = "Time is " + str(hour) + ":" + str(min) print(out_str) hour = int(input()) min = int(input()) print_time()
- a.
hourandmin - b.
out_str - c.
hour,min, andout_str
Answer
out_strout_str is the only variable declared in print_time() and is a local variable.Concepts in Practice 6.3.5 §6.3 source ↗
def print_greeting(): print(out_str) hour = int(input()) min = int(input()) if hour < 12: out_str = "Good morning" else: out_str = "Good day" print_greeting()
- a.
hourandmin - b.
out_str - c.none
Answer
out_str is accessed in print_greeting() but created in statements outside of print_greeting().Concepts in Practice 6.3.6 §6.3 source ↗
out_str? def print_greeting():
print("Good day,")
print_time()
def print_time():
out_str = "Time is " + str(hour) + ":" + str(min)
print(out_str)
hour = int(input())
min = int(input())
print_greeting()- a.
print_greeting() - b.
print_time() - c.
print_greeting()andprint_time()
Answer
print_time()print_time() creates out_str as a local variable. out_str is only in scope in print_time() and cannot be accessed elsewhere.Concepts in Practice 6.3.7 §6.3 source ↗
Consider the following variations on the example program with the input 9.
def update_hour():
tmp = hour
if is_dst:
tmp += 1
else:
tmp -= 1
is_dst = True
hour = int(input("Enter hour: "))
update_hour()
print("New hour:", hour)- a.
New hour: 9 - b.
New hour: 10 - c.
Error
Answer
New hour: 9update_hour(). tmp is the local variable edited. tmp is discarded after update_hour() finishes.Concepts in Practice 6.3.8 §6.3 source ↗
Consider the following variations on the example program with the input 9.
def update_hour():
new_hour = hour
if is_dst:
new_hour += 1
else:
new_hour -= 1
is_dst = True
hour = int(input("Enter hour: "))
update_hour()
print("New hour:", new_hour)- a.
New hour: 9 - b.
New hour: 10 - c.
Error
Answer
Errornew_hour is a local variable that the print statement tries to access after update_hour() finishes. new_hour is out of scope, so an error is produced.Concepts in Practice 6.3.9 §6.3 source ↗
Consider the following variations on the example program with the input 9.
def update_hour():
global new_hour
new_hour = hour
if is_dst:
new_hour += 1
else:
new_hour -= 1
is_dst = True
hour = int(input("Enter hour: "))
update_hour()
print("New hour:", new_hour)- a.
New hour: 9 - b.
New hour: 10 - c.
Error
Answer
New hour: 10 global keyword can be used to create a global variable from within a function. new_hour has global scope and can be accessed outside update_hour().Concepts in Practice 6.4.1 §6.4 source ↗
Consider the following:
1 def print_welcome(name):
2 print(f"Welcome {name}!")
3
4 username = int(input("Enter new username: "))
5 print_welcome(username) Which is an argument?- a.
name - b.
username - c.
nameandusername
Answer
usernameusername is the argument passed to print_welcome(). name is print_welcome()'s parameter that is assigned with username's value.Concepts in Practice 6.4.2 §6.4 source ↗
Consider the following:
1 def print_welcome(name):
2 print(f"Welcome {name}!")
3
4 username = int(input("Enter new username: "))
5 print_welcome(username) Which is a parameter?- a.
name - b.
username - c.
nameandusername
Answer
namename is the only parameter defined with print_welcome(). username is the argument passed on line 5's function call.Concepts in Practice 6.4.3 §6.4 source ↗
Consider the following:
1 def print_welcome(name):
2 print(f"Welcome {name}!")
3
4 username = int(input("Enter new username: "))
5 print_welcome(username) What is the scope of name?- a.
print_welcome()only - b.whole program
Answer
print_welcome() onlyname is a parameter that exists only within a call to print_welcome().Concepts in Practice 6.4.4 §6.4 source ↗
Consider the following:
1 def print_welcome(name):
2 print(f"Welcome {name}!")
3
4 username = int(input("Enter new username: "))
5 print_welcome(username) What would happen if username was changed to name on lines 4 and 5?- a.same output
- b.error/wrong output
Answer
name would still be created in print_welcome(). Scope can be confusing with variables of the same name.Concepts in Practice 6.4.5 §6.4 source ↗
Consider the following:
def calc_distance(x1, y1, x2, y2):
dist = math.sqrt((x2-x1)**2 + (y2-y1)**2)
print(dist)
p1_x =int(input("Enter point 1's x: "))
p1_y =int(input("Enter point 1's y: "))
p2_x =int(input("Enter point 2's x: "))
p2_y =int(input("Enter point 2's y: "))
calc_distance(p1_x, p1_y, p2_x, p2_y) Which is an argument?- a.
p1_x - b.
x1
Answer
p1_xp1_x is the first argument used in line 9's function call. x1 is defined as the first parameter of calc_distance().Concepts in Practice 6.4.6 §6.4 source ↗
Consider the following:
def calc_distance(x1, y1, x2, y2):
dist = math.sqrt((x2-x1)**2 + (y2-y1)**2)
print(dist)
p1_x =int(input("Enter point 1's x: "))
p1_y =int(input("Enter point 1's y: "))
p2_x =int(input("Enter point 2's x: "))
p2_y =int(input("Enter point 2's y: "))
calc_distance(p1_x, p1_y, p2_x, p2_y) Which is a parameter?- a.
p1_y - b.
y1
Answer
y1y1 is defined as calc_distance()'s second parameter. p1_y is the second argument on line 9's function call.Concepts in Practice 6.4.7 §6.4 source ↗
Consider the following:
def calc_distance(x1, y1, x2, y2):
dist = math.sqrt((x2-x1)**2 + (y2-y1)**2)
print(dist)
p1_x =int(input("Enter point 1's x: "))
p1_y =int(input("Enter point 1's y: "))
p2_x =int(input("Enter point 2's x: "))
p2_y =int(input("Enter point 2's y: "))
calc_distance(p1_x, p1_y, p2_x, p2_y) What would be the value of x2 for the function call, calc_distance(2, 4, 3, 6)?- a.
2 - b.
4 - c.
3 - d.
6 - e.
Error
Answer
3 3 is a literal passed as the third argument, which corresponds to x2, the third parameter.Concepts in Practice 6.4.8 §6.4 source ↗
convert_temps(), wknd_temps and temps refer to ________ in memory.- a.the same object
- b.different objects
Answer
wknd_temps and temps is modified without needing a local copy.Concepts in Practice 6.4.9 §6.4 source ↗
unit is assigned with "C", metric and unit refer to ________ in memory.- a.the same object
- b.different objects
Answer
convert_temps() makes a new object for unit to refer to.Concepts in Practice 6.4.10 §6.4 source ↗
deg_sign is a string whose value cannot change once created. deg_sign is ________.- a.immutable
- b.mutable
Answer
Concepts in Practice 6.4.11 §6.4 source ↗
unit ________.- a.refers to an object with the value
"C" - b.does not exist
Answer
unit no longer exists after convert_temps() finishes and returns to line 14.Concepts in Practice 6.5.1 §6.5 source ↗
calc_mpg(miles, gallons)? def calc_mpg(miles, gallons): mpg = miles/gallons return mpg
- a.
mpg - b.
None - c.
Error
Answer
mpgcalc_mpg() specifies mpg to be returned with the return statement.Concepts in Practice 6.5.2 §6.5 source ↗
calc_sqft()? def calc_sqft(length, width): sqft = length * width return
- a.
sqft - b.
None - c.
Error
Answer
None return is a valid statement to end the function and return to the calling code without a specified value. calc_sqft() should return sqft with the line return sqft.Concepts in Practice 6.5.3 §6.5 source ↗
hw_1() and hw_2()? def hw_1():
print("Hello world!")
return
def hw_2():
print("Hello world!")- a.
hw_1()returns a string,hw_2()does not - b.
hw_1()returnsNone,hw_2()does not - c.no difference
Answer
return statement is not specified, the function returns None .Concepts in Practice 6.5.4 §6.5 source ↗
yarn_weight(3) return? def yarn_weight(num):
if num == 0:
return "lace"
elif num == 1:
return "sock"
elif num == 2:
return "sport"
elif num == 3:
return "dk"
elif num == 4:
return "worsted"
elif num == 5:
return "bulky"
else:
return "super bulky"- a.
"lace" - b.
"dk" - c.
"super bulky"
Answer
"dk"num == 3 is True , so the return "dk" statement executes.Concepts in Practice 6.5.5 §6.5 source ↗
def inc_volume(level, max):
if level < max:
return level
level += 1
else:
return level
vol1 = inc_volume(9, 10)
print(vol1)
vol2 = inc_volume(10, 10)
print(vol2)- a.
9 10
- b.
10 10
- c.
10 11
Answer
9 10
inc_volume(9,10), return level returns 9 , and level += 1 is never reached.Concepts in Practice 6.5.6 §6.5 source ↗
bill? def tax(total): return .06 * total def auto_tip(total): return .2 * total bill = 100.0 bill += tax(bill) + auto_tip(bill)
- a.
26.0 - b.
126.0
Answer
126.0bill += tax(bill) + auto_tip(bill) evaluates to bill += 6.0 + 20.0 to bill = 100.0 + 6.0 + 20.0 to 126.0.Concepts in Practice 6.5.7 §6.5 source ↗
val2? def sq(num): return num * num def offset(num): return num - 2 val = 5 val2 = sq(offset(val))
- a.
9 - b.
23
Answer
9val2 = sq(offset(5)) evaluates to val2 = sq(3) to 9.Concepts in Practice 6.6.1 §6.6 source ↗
Consider the following function:
def greeting(msg, name, count):
i = 0
for i in range(0, count):
print(msg, name) Which is the positional argument in greeting(count=1, name="Ash", msg="Hiya")?- a.
count=1 - b.
name="Ash" - c.
msg="Hiya" - d.None
Answer
Concepts in Practice 6.6.2 §6.6 source ↗
Consider the following function:
def greeting(msg, name, count):
i = 0
for i in range(0, count):
print(msg, name) What is the output of greeting(count=2, name="Ash", msg="Hiya")?- a.
Ash Hiya
Ash Hiya - b.
Hiya Ash
Hiya Ash
Answer
Hiya AshHiya Ash "Hiya" is the value of msg and "Ash" is the value of name in the function.Concepts in Practice 6.6.3 §6.6 source ↗
Consider the following function:
def greeting(msg, name, count):
i = 0
for i in range(0, count):
print(msg, name) Which is the positional argument in greeting("Welcome", count=1, name="Anita")?- a.
"Welcome" - b.
count=1 - c.
name="Anita"
Answer
"Welcome" "Welcome" is unnamed and assigned correctly to count. Positional arguments must come before keyword arguments.Concepts in Practice 6.6.4 §6.6 source ↗
Consider the following function:
def greeting(msg, name, count):
i = 0
for i in range(0, count):
print(msg, name) Which function call would produce an error?- a.
greeting("Morning", "Morgan", count=3) - b.
greeting(count=1,"Hi", "Bea") - c.
greeting("Cheers", "Colleagues", 10)
Answer
greeting(count=1,"Hi", "Bea") "Hi" and "Bea" , follow the keyword argument count=1, which produces an error.Concepts in Practice 6.6.5 §6.6 source ↗
Consider the following updated version of greeting():
def greeting(msg, name="Friend", count=1):
i = 0
for i in range(0, count):
print(msg, name) Which parameters have default values?- a.
msg - b.
nameandcount - c.all
Answer
name and countname's default value is "Friend" , and count's default value is 1 . msg does not have default value.Concepts in Practice 6.6.6 §6.6 source ↗
Consider the following updated version of greeting():
def greeting(msg, name="Friend", count=1):
i = 0
for i in range(0, count):
print(msg, name) Which function call is correct?- a.
greeting() - b.
greeting(name="Gina") - c.
greeting("Greetings")
Answer
greeting("Greetings")msg is a required argument assigned with "Greetings" . name and count use the default values. "Greetings Friend" is printed.Concepts in Practice 6.6.7 §6.6 source ↗
Consider the following updated version of greeting():
def greeting(msg, name="Friend", count=1):
i = 0
for i in range(0, count):
print(msg, name) What is the output of greeting(count=0, msg="Hello")?- a.
Hello Friend - b.nothing
- c.
Error
Answer
msg="Hello", name="Friend", and count=0, so the call is valid. The function executes but doesn't enter the for loop because count=0.Loading chapter 7…
Problems and answers are adapted from Introduction to Python Programming by Udayan Das, Aubrey Lawson, Chris Mayfield and Narges Norouzi, OpenStax, and are used under the CC BY-NC-SA 4.0 licence. Access for free at https://openstax.org/books/introduction-python-programming/pages/1-introduction. Illustrations: Copyright Rice University, OpenStax, under CC BY-NC-SA 4.0 license. This adaptation is released under the same licence, is non-commercial, and is neither affiliated with nor endorsed by OpenStax or Rice University.