Calling Value-Returning Functions

Calls to value-returning functions can be used anywhere that the function’s return value is appropriate. These calls can be embedded in expressions, assigned to variables, used in conditional statements, or passed as arguments to other functions.

Examples:

  1. Basic Usage:

    num_list = [1, 3, 5, 7, 9]
    result = max(num_list) * 100
    print(result) # Output: 900

    The built-in max() function is applied to a list of integers, and its return value is multiplied by 100.

  2. Multiple Function Calls in an Expression:

    result = max(num_list1) * max(num_list2)
  3. Function Call within a Function Call

    result = abs(max(num_list))
  4. Function Call in a Conditional Statement:

    if max(num_list) < 10:
    print("All numbers are less than 10")
  5. Function Call in a Print Statement:

    print('Largest value in num_list is', max(num_list))

Custom Function Returning Multiple Values:

If a function needs to return more than one value, such as returning both the maximum and minimum values of a list, this can be done by returning a tuple.

Example:

# Function definition
def maxmin(num_list):
return (max(num_list), min(num_list))
# Function use
weekly_temps = [45, 30, 52, 58, 62, 48, 49]
# Assigning the returned tuple to a single variable
highlow_temps = maxmin(weekly_temps)
print(highlow_temps) # Output: (62, 30)
# Tuple unpacking to individual variables
high, low = maxmin(weekly_temps)
print(f"High: {high}, Low: {low}") # Output: High: 62, Low: 30

Invalid Usage:

It does not make sense for a call to a value-returning function to be used as a standalone statement:

max(num_list) # This call does not utilize the return value and is effectively "thrown away."

Functions with No Arguments:

Value-returning functions can also be designed without any arguments. Empty parentheses are used in both the function header and the function call to distinguish the identifier as a function name and not a variable.

Example:

def getConvertTo():
return "Celsius"
conversion = getConvertTo()
print(conversion) # Output: Celsius