FREE INTERACTIVE ONLINE COURSE

Python 3

FOR BEGINNERS


"The first Python course that simply amazed me. Very well explained and easy to understand." (Alexandru Cosmin)

"The best Python course in Romania." (Iulian Geană)


ALL REVIEWS
LESSON 17
PAGE 4 / 4
Functions in Python (I)
Home >>> Free Online Lessons, Python 3

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:
Editor - lesson_17.py
       
Console/Output done
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.
The lesson is now over.
 home   list  CONTENTS   perm_identity   arrow_upward