Every problem in the chapter beside the book’s answer, a chapter at a time as you scroll.

Chapter 6: Functions

49 problems · 0 figures

Concepts in Practice 6.1.1 §6.1 source ↗

Which line has a function call?
1  input_num = 14
2  offset_num = input_num - 10
3  print(offset_num)
  1. a.
    line 1
  2. b.
    line 2
  3. c.
    line 3

Answer

C. line 3
The print() function is called to output the variable, offset_num.

Concepts in Practice 6.1.2 §6.1 source ↗

How many times is print() called?
print("Please log in")
username = input("Username:")
password = input("Password:")
print("Login successful")
print("Welcome,", username)
  1. a.
    1
  2. b.
    3
  3. c.
    5

Answer

B. 3
Lines 1, 4, and 5 each call print() once. Lines 2 and 3 call a different function, input().

Concepts in Practice 6.1.3 §6.1 source ↗

How many function calls are there?
# Use float() to convert input for area calculation
width = float(input("Enter width:"))
height = float(input("Enter height:"))
print("Area is", width*height)
  1. a.
    3
  2. b.
    5
  3. c.
    6

Answer

B. 5
Line 1 is a comment that is not executed. Lines 2 and 3 each call float() and input(). Line 3 calls print() for a total of five function calls.

Concepts in Practice 6.1.4 §6.1 source ↗

What's wrong with the first line of the function definition?
def water_plant:
  1. a.
    A docstring should go after the colon.
  2. b.
    Parentheses should go after water_plant.
  3. c.
    def should be define before water_plant.

Answer

B. Parentheses should go after water_plant.
The corrected line is def water_plant(): .

Concepts in Practice 6.1.5 §6.1 source ↗

What is the output?
def print_phone_num():
  print("Phone: (", 864, ")", 555, "-", 0199)

print("User info:")
print_phone_num()
  1. a.
    Phone: ( 864 ) 555 - 1000
    User info:
    Phone: ( 864 ) 555 - 1000
  2. b.
    User info:
  3. c.
    User info:
    Phone: ( 864 ) 555 - 1000

Answer

C. User info:
Phone: ( 864 ) 555 - 1000
The main program outputs "User info:" and then calls print_phone_num(), which outputs the phone number.

Concepts in Practice 6.1.6 §6.1 source ↗

Which statement calls a function named print_pc_specs()?
  1. a.
    print_pc_specs
  2. b.
    print_pc_specs()
  3. c.
    print_pc_specs():

Answer

B. print_pc_specs()
A function call includes the function name and parentheses.

Concepts in Practice 6.1.7 §6.1 source ↗

Which is an appropriate name for a function that calculates a user's taxes?
  1. a.
    calc_tax
  2. b.
    calculate user tax
  3. c.
    c_t

Answer

A. calc_tax
calc_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?
  1. a.
    3, 1
  2. b.
    4, 4
  3. c.
    12, 4
Video · Improving a program with a function in the book ↗

Answer

C. 12, 4
Each calculation uses four statements to read in the x,y values of a pair of points. The original program performs three calculations by repeating code for a total of 12 input statements. The revised program performs three calculations by executing the four input statements multiple times with function calls.

Concepts in Practice 6.1.9 §6.1 source ↗

Consider the code above.

How many times can calc_distance() be called?
  1. a.
    1
  2. b.
    3
  3. c.
    many
Video · Improving a program with a function in the book ↗

Answer

C. many
The benefits of a function's reusability is highlighted by many function calls that drastically reduce the amount of cluttered, redundant code. Calling calc_distance() 10 times is equivalent to 60 statements in the original program.

Concepts in Practice 6.2.1 §6.2 source ↗

Which line is executed first?
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
  1. a.
    1
  2. b.
    3
  3. c.
    5

Answer

C. 5
Line 5 is the start of the main program, which is not indented. park_greet() is called on line 6 and executed.

Concepts in Practice 6.2.2 §6.2 source ↗

Control flow moves to line 9, and 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()
  1. a.
    1
  2. b.
    4
  3. c.
    10

Answer

B. 4
Control flow moves to where park_greet() is defined, at line 4.

Concepts in Practice 6.2.3 §6.2 source ↗

Control flow moves to line 12, and 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()
  1. a.
    5
  2. b.
    8
  3. c.
    12

Answer

C. 12
Control flow returns to the line that called the function. Line 12 contains the function call to extra_lot(), so control flow returns to line 12.

Concepts in Practice 6.2.4 §6.2 source ↗

What is the output?
def park_greet():
  """Output greeting."""
  print("Welcome to the park")
print("Open sunrise to sunset")

park_greet()
  1. a.
    Welcome to the park
  2. b.
    Welcome to the park
    Open sunrise to sunset
  3. c.
    Open sunrise to sunset
    Welcome to the park

Answer

C. Open sunrise to sunset
Welcome to the park
The program has an indentation mistake. print("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?
  1. a.
    2
  2. b.
    3
  3. c.
    6
Video · Example: Book club email messages in the book ↗

Answer

C. 6
The 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?
  1. a.
    1
  2. b.
    11
  3. c.
    16
Video · Example: Book club email messages in the book ↗

Answer

B. 11
Control flow returns to line 11, which called 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 ↗

Which variables are global?
num = float(input())
num_sq = num * num
print(num, "squared is", num_sq)
  1. a.
    num only
  2. b.
    num_sq only
  3. c.
    num and num_sq

Answer

C. num and num_sq
Both num and num_sq are created outside of functions and are global variables.

Concepts in Practice 6.3.2 §6.3 source ↗

Which variables have global scope?
def print_square():
  num_sq = num * num
  print(num, "squared is", num_sq)

num = float(input())
print_square()
  1. a.
    num only
  2. b.
    num_sq only
  3. c.
    num and num_sq

Answer

A. num only
num 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 ↗

Which functions can access 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()
  1. a.
    print_double()
  2. b.
    print_square()
  3. c.
    print_double() and print_square()

Answer

C. 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 ↗

Which variables are local?
def print_time():
  out_str = "Time is " + str(hour) + ":" + str(min)
  print(out_str)

hour = int(input())
min = int(input())
print_time()
  1. a.
    hour and min
  2. b.
    out_str
  3. c.
    hour, min, and out_str

Answer

B. out_str
out_str is the only variable declared in print_time() and is a local variable.

Concepts in Practice 6.3.5 §6.3 source ↗

Which variables are local?
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()
  1. a.
    hour and min
  2. b.
    out_str
  3. c.
    none

Answer

C. none
out_str is accessed in print_greeting() but created in statements outside of print_greeting().

Concepts in Practice 6.3.6 §6.3 source ↗

Which functions directly access 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()
  1. a.
    print_greeting()
  2. b.
    print_time()
  3. c.
    print_greeting() and print_time()

Answer

B. 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.

What is the output?
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)
  1. a.
    New hour: 9
  2. b.
    New hour: 10
  3. c.
    Error
Video · Editing global variables in a program with a function in the book ↗

Answer

A. New hour: 9
The global variable hour is not edited in update_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.

What is the output?
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)
  1. a.
    New hour: 9
  2. b.
    New hour: 10
  3. c.
    Error
Video · Editing global variables in a program with a function in the book ↗

Answer

C. Error
new_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.

What is the output?
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)
  1. a.
    New hour: 9
  2. b.
    New hour: 10
  3. c.
    Error
Video · Editing global variables in a program with a function in the book ↗

Answer

B. New hour: 10
The 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?
  1. a.
    name
  2. b.
    username
  3. c.
    name and username

Answer

B. username
username 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?
  1. a.
    name
  2. b.
    username
  3. c.
    name and username

Answer

A. name
name 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?
  1. a.
    print_welcome() only
  2. b.
    whole program

Answer

A. print_welcome() only
name 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?
  1. a.
    same output
  2. b.
    error/wrong output

Answer

A. same output
The program would run correctly. Arguments and parameters can have the same name, and a local variable called 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?
  1. a.
    p1_x
  2. b.
    x1

Answer

A. p1_x
p1_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?
  1. a.
    p1_y
  2. b.
    y1

Answer

B. y1
y1 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)?
  1. a.
    2
  2. b.
    4
  3. c.
    3
  4. d.
    6
  5. e.
    Error

Answer

C. 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 ↗

In convert_temps(), wknd_temps and temps refer to ________ in memory.
  1. a.
    the same object
  2. b.
    different objects

Answer

A. the same object
A list is mutable, so the object referred to by wknd_temps and temps is modified without needing a local copy.

Concepts in Practice 6.4.9 §6.4 source ↗

After unit is assigned with "C", metric and unit refer to ________ in memory.
  1. a.
    the same object
  2. b.
    different objects

Answer

B. different objects
A string is immutable, so 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 ________.
  1. a.
    immutable
  2. b.
    mutable

Answer

A. immutable
An immutable object's value cannot be changed.

Concepts in Practice 6.4.11 §6.4 source ↗

On line 16, unit ________.
  1. a.
    refers to an object with the value "C"
  2. b.
    does not exist

Answer

B. does not exist
unit no longer exists after convert_temps() finishes and returns to line 14.

Concepts in Practice 6.5.1 §6.5 source ↗

What is returned by calc_mpg(miles, gallons)?
def calc_mpg(miles, gallons):
  mpg = miles/gallons
  return mpg
  1. a.
    mpg
  2. b.
    None
  3. c.
    Error

Answer

A. mpg
calc_mpg() specifies mpg to be returned with the return statement.

Concepts in Practice 6.5.2 §6.5 source ↗

What is returned by calc_sqft()?
def calc_sqft(length, width):
  sqft = length * width
  return
  1. a.
    sqft
  2. b.
    None
  3. c.
    Error

Answer

B. 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 ↗

What is the difference between hw_1() and hw_2()?
def hw_1():
  print("Hello world!")
  return

def hw_2():
  print("Hello world!")
  1. a.
    hw_1() returns a string, hw_2() does not
  2. b.
    hw_1() returns None, hw_2() does not
  3. c.
    no difference

Answer

C. no difference
If the return value or return statement is not specified, the function returns None .

Concepts in Practice 6.5.4 §6.5 source ↗

What does 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"
  1. a.
    "lace"
  2. b.
    "dk"
  3. c.
    "super bulky"

Answer

B. "dk"
num == 3 is True , so the return "dk" statement executes.

Concepts in Practice 6.5.5 §6.5 source ↗

What is the output?
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)
  1. a.
    9
    10
  2. b.
    10
    10
  3. c.
    10
    11

Answer

A.
9
10
For inc_volume(9,10), return level returns 9 , and level += 1 is never reached.

Concepts in Practice 6.5.6 §6.5 source ↗

What is the updated value of bill?
def tax(total):
  return .06 * total

def auto_tip(total):
  return .2 * total

bill = 100.0
bill += tax(bill) + auto_tip(bill)
  1. a.
    26.0
  2. b.
    126.0

Answer

B. 126.0
bill += 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 ↗

What is the value of val2?
def sq(num):
  return num * num

def offset(num):
  return num - 2

val = 5
val2 = sq(offset(val))
  1. a.
    9
  2. b.
    23

Answer

A. 9
val2 = 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")?
  1. a.
    count=1
  2. b.
    name="Ash"
  3. c.
    msg="Hiya"
  4. d.
    None

Answer

D. None
The function call uses all keyword arguments to assign values to the named parameters.

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")?
  1. a.
    Ash Hiya
    Ash Hiya
  2. b.
    Hiya Ash
    Hiya Ash

Answer

B. Hiya Ash
Hiya 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")?
  1. a.
    "Welcome"
  2. b.
    count=1
  3. c.
    name="Anita"

Answer

A. "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?
  1. a.
    greeting("Morning", "Morgan", count=3)
  2. b.
    greeting(count=1,"Hi", "Bea")
  3. c.
    greeting("Cheers", "Colleagues", 10)

Answer

B. greeting(count=1,"Hi", "Bea")
The positional arguments, "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?
  1. a.
    msg
  2. b.
    name and count
  3. c.
    all

Answer

B. name and count
name'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?
  1. a.
    greeting()
  2. b.
    greeting(name="Gina")
  3. c.
    greeting("Greetings")

Answer

C. 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")?
  1. a.
    Hello Friend
  2. b.
    nothing
  3. c.
    Error

Answer

B. nothing
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.