Function Reuse and Nested Function Calls

Once we've defined a function, we can call on it again and again. In fact, we can call on one function from the body of another function. We can also pass one function call as an argument to another.

Let's consider this problem. Given a patient's temperature in Fahrenheit and the hour of day when the temperature was taken, return whether the patient has a fever according to Harrison's internal medicine textbook.

Does this sound familiar? Recall our previously defined function:

In [2]:
def check_fever(temp, hour_of_day):
    """ (number, int) -> str
    
    Return 'fever' if the temperature temp in degrees Celsius recorded at hour_of_day
    using the 24 hour clock) meets Harrison's definition of a fever, and 'no fever' otherwise.
    
    >>> check_fever(37.5, 9)
    'fever'
    >>> check_fever(37.5, 14)
    'no fever'
    """
    if 0 <= hour_of_day <= 11 and temp > 37.2:
        return 'fever'
    elif 12 <= hour_of_day <=23 and temp > 37.7:
        return 'fever'
    else:
        return 'no fever'

That code works, but in this situation we have a temperature measured in Fahrenheit, not Celsius. Fortunately, we know how to convert between the two and we've already defined a function:

In [4]:
def fahrenheit_to_celsius(temp):
    """ (number) -> float
    
    Return the temperature temp converted from degrees Fahrenheit to Celsius.
    
    >>> fahrenheit_to_celsius(32)
    0.0
    """
    
    return (temp - 32) * 5 / 9

Now, let's get back to solving the original problem. Much of the work has already been done, so we should take advantage of that.

We will define a new function check_fever_fahrenheit that works the same as check_fever, but the argument to it will be a temperature in degrees Fahrenheit, not Celsius. In the body of the function, we will call on check_fever and fahrenheit_to_celsius, rather than defining the function from scratch.

In [7]:
def check_fever_fahrenheit(temp, hour_of_day):
    """ (number, int) -> str
    
    Return 'fever' if the temperature temp in degrees Fahrenheit recorded at hour_of_day
    using the 24 hour clock) meets Harrison's definition of a fever, and 'no fever' otherwise.
    
    >>> check_fever_fahrenheit(99.5, 9)
    'fever'
    >>> check_fever_fahrenheit(99.5, 14)
    'no fever'
    """
    celsius = fahrenheit_to_celsius(temp)
    return check_fever(celsius, hour_of_day)
    
In [10]:
check_fever_fahrenheit(99.5, 9)
Out[10]:
'fever'
In [11]:
check_fever_fahrenheit(99.5, 14)
Out[11]:
'no fever'

We could also simplify the body of check_fever_fahrenheit even more, by combining the two statments:

return check_fever(fahrenheit_to_celsius(temp), hour_of_day)

Tracing function calls with the Python Visualizer

To see how function calls are executed, we will trace this code using the Python Visualizer. Please note that the docstrings have been omitted due to space constraints.