Multiple Formal Parameters
So far, we have used only one or ... none. Let's say we want to create a function that adds the values held by three variables.
We know that the addition operator can be used for the
int /
float and
str classes (concatenates two strings),
so we can generalize it:
DETAILS
Above, we read three input values from the keyboard for each of the two calls, stored in the variables
a,
b, and
c.
To perform the addition correctly, we explicitly converted the data type of the variables after reading them.
We then passed these as actual parameters to our function named
add3, which performed the operation, and the result was displayed using
print.
However... we mentioned
generalization. Wouldn't it be nice if the function decided how?
We know that the
input function always returns the read data as a string.
We also know the
if statement. So, we modify the previously created function:
We added an additional formal parameter (named
tip) to specify how we want to perform the addition operation.
Clearly, we could also include the
list data type, for example.
Exercise!
We then used the
if statement to decide the explicit conversion method for each of the three values.