Practice: Functions#

In this set of practice problems, it’s all about functions - how to execute them, how to write our own functions, and how to debug functions.

As for all practice sections, each question will include a handful of assert statements. After you write and execute the code to each question, each assert should “pass silently” (meaning: should give no output upon execution) indicating that you are on the right track. After you’ve written your code and run the asserts, you can always check your answers, as the answers to these questions are included in the “Answers” chapter of this book.

Function Execution#

Function Execution Q1. The function convert_temp has been provided for you. After understanding the code in the function, define the function. Then, execute (use) this function to create the following variables under the specified conditions:

  1. tempA | execute the convert_temp function to convert the temperature 95 degrees Fahrenheit into degrees Celsius

  2. tempB | execute convert_temp to convert the temperature 17 degrees Celsius into degrees Fahrenheit

Provided function:

def convert_temp(temp, input_unit='F'):
    
    if input_unit == 'F':
        out_temp = (temp - 32) * 5/9
    elif input_unit == 'C':
        out_temp = (temp * 9/5) + 32
    else:
        print("Please specify either 'F' or 'C' for input_unit")
        
    return out_temp

Checks you can use to see if you’re on the right track:

assert tempA == 35.0
assert tempB == 62.6

Answer →

Function Execution Q2. The function compare_to_threshold has been provided for you. After understanding the code in the function, define the function. Then, execute (use) this function to create the following variables under the specified conditions:

  1. comp_a | execute the compare_to_threshold function using the default threshold to compare the value 250

  2. comp_b | execute compare_to_threshold to compare the value 42 against the threshold 42

  3. comp_c | execute compare_to_threshold using keyword arguments (specifying each parameter’s name during execution) to compare the value 3 against the threshold 7

Provided function:

def compare_to_threshold(value, threshold=100):

    if value > threshold:
        output = 'above'
    elif value < threshold:
        output = 'below'
    else:
        output = 'equal'

    return output

Checks you can use to see if you’re on the right track:

assert comp_a == 'above'
assert comp_b == 'equal'
assert comp_c == 'below'

Answer →

User-Designed Functions (UDFs)#

UDFs Q1 Write a function provide_info that takes three parameters: name, year, and school. Set the default value for school to be ‘UCSD’.

This function should return the string “Hi! I’m name. I am a year at school.” (where the variable names are replaced by the values input to the function upon execution).

For example, one possible execution of this function could return “Hi! I’m Shannon. I am a sophomore at UCSD.”

Note: Be sure punctuation and spacing match that specified in the instructions.

Checks you can use to see if you’re on the right track:

assert provide_info(name='Taylor', year='junior', school='UCLA') == "Hi! I'm Taylor. I am a junior at UCLA." 
assert provide_info(name='Shannon', year='junior') == "Hi! I'm Shannon. I am a junior at UCSD."

Answer →

UDFs Q2. Recently, the company you work at (‘cogs co.’) realized that too many employees have problematic usernames. You’re going to write a function (change_username()) that takes a single parameter username as input.

This function will check if the username meets the following specifications:

  • contains more than four characters

  • includes only letters (A-Z; a-z) and/or numbers (0-9); in other words: is alphanumeric

  • does NOT include the string ‘cogs’

If the username meets the above specifications, the function will return False (indicating the username does not have to be changed. If any one of the above specifications is not met, the function will return True (indicating that the username does not meet at least one of the above specifications).

For example, change_username(username='cogs') would return True because it does not contain more than four letters and because it includes the string 'cogs' in its name, while change_username(username='Shannon') would return False, as this meets all three specifications above.

Checks you can use to see if you’re on the right track:

assert change_username('aaaaa') == False
assert change_username('aaaa') == True
assert change_username('AAAAA') == False
assert change_username('12345') == False
assert change_username('cogs123') == True

Answer →

UDFs Q3 Write a function called exclaim that takes two inputs (we’ll assume each to be a string), concatenates them together with a space between them and an exclamation point at the end and returns the result. Then, execute the function to return the string “Happy Friday!”

Answer →

UDFs Q4 Write a function called return_bigger that will take in two numeric values as inputs and return the larger value from the function. If the numbers are the same value, it will return one of them.

Answer →

UDFs Q5 (Question author: Jonathan Truong) In a popular video game (if you know, you know), the third round of a match’s half is pivotal to setting the economic tone of the match. This is when the two competing teams must make an important decision in order to maintain economic stability throughout the match. This decision is informed by the outcome of the two prior rounds. Write a function called buy_or_save that takes in two strings as parameters, each representing whether that round was won (‘W’) or lost (‘L’). You don’t need to consider the case when either string parameter doesn’t follow the right format.

  1. If the team won both rounds, return a message saying that ‘The team should save’.

  2. If the team lost both rounds, return a message saying that ‘The team should buy!’.

  3. If the team won one round but lost the other, return a message saying that ‘The team should half-buy’.

Answer →

UDFs Q6 (Question author: Pheobe Ng) Write a function matcha that determines whether the matcha is low-grade, high-grade, or ceremonial-grade matcha. The matcha function should take in two strings as parameters: color and texture. If the color is “vibrant green” and the texture is “fine”, return a message indicating that it is ceremonial-grade matcha. If the color is “dull green” and the texture is “fine”, return a message indicating that it is high-grade matcha. If there are any other answer combinations, return a message indicating that it is low-grade matcha.

Answer →

UDFs Q7 (Question author: Emanoel Agbayani) Write a function phone_time that determines whether the amount of time you’ve spent on your phone is reasonable in a day. The function takes in one input screen_time in hours. If screen_time is a negative value or string, return a string containing a message that it is an invalid input. If screen_time is less than 3 hours, return a string that contains positive reinforcement. If screen_time is greater than or equal to 4 hours, return a string that contains some form of encouragement to get off their phone.

Answer →

UDFs Q8 Write a function tip_calculator that takes two parameters: bill (a numeric value) and service (a string). The default value for the service parameter should be ‘good’.

The function should calculate the tip as follows:

  • if service is ‘great’, the tip is 20% of the bill

  • if service is ‘good’, the tip is 15% of the bill

  • for any other service value, the tip is 10% of the bill

The function should return the tip amount (not the total bill).

Checks you can use to see if you’re on the right track:

assert round(tip_calculator(100, 'great'), 2) == 20.0
assert round(tip_calculator(100), 2) == 15.0
assert round(tip_calculator(20, 'meh'), 2) == 2.0

Answer →

UDFs Q9 Write a function weekend_check that takes a single parameter day (a string storing a day of the week, like ‘Monday’). The function should return the boolean True if day is ‘Saturday’ or ‘Sunday’ and should return the boolean False for any other day of the week.

Checks you can use to see if you’re on the right track:

assert weekend_check('Saturday') == True
assert weekend_check('Sunday') == True
assert weekend_check('Wednesday') == False

Answer →

Debugging#

Debugging Q1 The not-totally-functioning growth_rate() function is provided for you. The goal of this function, is given two population inputs: last_year, this_year, the function should return the population growth rate for that country.

For example, in 2020, China’s population was 1439323776. This year, its population is 1444216107.

Population growth rate is calculated by taking the difference between this year’s population minus last year’s population, dividng that difference by last year’s population, and multiplying the entire quantity by 100.

Given China’s numbers above and this calculation, we know that this function should return 0.34…but it’s not at this point.

Consider the function currently and then debug (you can edit the code provided directly or copy and paste below so you still have the original if needed) to accomplish the task specified above.

Note: Do not change the name of the function (growth_rate), and the parameter names provided in the instructions (last_year, this_year) must be used.

Function provided:

def growth_rate(self, this_year, last_year):
    self.this_year - self.last_year/self.last_year * 100
assert 0 < growth_rate(last_year=331002651,
                       this_year=332915073) < 1

Answer →

Debugging Q2 The function fahrenheit_to_kelvin provided below is supposed to convert a temperature in degrees Fahrenheit to Kelvin. To do this, the function should first convert the input temperature to degrees Celsius (by subtracting 32 from the input temperature and then multiplying that quantity by 5/9) and then add 273.15 to the Celsius temperature.

However, as written, the function fails to run and contains a logic error. Debug, edit, and test the function provided so that it accomplishes the intended goal.

Function provided:

def fahrenheit_to_kelvin(temp_f)
    temp_c = temp_f - 32 * 5/9
     kelvin = temp_c + 273.15
    return kelvin

Checks you can use to see if you’re on the right track:

assert fahrenheit_to_kelvin(32) == 273.15
assert fahrenheit_to_kelvin(212) == 373.15

Answer →

Debugging Q3 Write a function safe_convert that takes a single parameter value. The function should try to convert value to an integer using int(), returning the integer from the function. However, if that conversion raises an error, the function should return None instead (rather than allowing the error to be raised).

Checks you can use to see if you’re on the right track:

assert safe_convert('12') == 12
assert safe_convert(3.9) == 3
assert safe_convert('cat') is None

Answer →