Multiple Parameters¶
Let’s define a maximum function that determines and returns the largest of three values— the following code segment calls the function three times with integers, floating-point numbers and strings, respectively:
def maximum(value1, value2, value3):
"""Return the maximum of three values."""
max_value = value1
if value2 > max_value:
max_value = value2
if value3 > max_value:
max_value = value3
return max_value
maximum(12, 27, 36)
maximum(12.3, 45.6, 9.7)
maximum('yellow', 'red', 'orange')
The call maximum(13.5, 'hello', 7)
results in TypeError because strings and numbers cannot be compared to one another with the greater-than (>) operator.
Function maximum’s Definition
Function maximum specifies three parameters in a comma-separated list. The arguments 12, 27 and 36 are assigned to the parameters value1, value2 and value3, respectively. To determine the largest value, we process one value at a time: Initially, we assume that value1 contains the largest value, so we assign it to the local variable max_value. Of course, it’s possible that value2 or value3 contains the actual largest value, so we still must compare each of these with max_value. The first if statement then tests value2 > max_value, and if this condition is True assigns value2 to max_value. The second if statement then tests value3 > max_value, and if this condition is True assigns value3 to max_value. Now, max_value contains the largest value, so we return it. When control returns to the caller, the parameters value1, value2 and value3 and the variable max_value in the function’s block—which are all local variables—no longer exist.