Creating Functions

Created functions are user-defined functions. Thats means that the user created the function by him self and it is not provided by the program language or the environment.

The syntax to create a functions is the following:

def functionname( parameters ):
"function_docstring"
function_suite1

function_suite2
...
return [expression]

functionname is the name of the function by which it will be called in the program.
parameters are the parameters which the function will expect. Important is the order in with the parameters will be given over. The function expects the parameters in the same order as it is defined.
"funcrtion_docstring" is optional and describes the how the function is supposed to perform. It can be understand like a comment.
function_suite’s are responsible for the task of the function. A function can have more than one function suite.
return [expression] is the last statement in a function. It sends an execution control back to calling the environment. If there is an expression added it will be returned as well.

Take a closer look at the following example. The following function calculates the average mark (from 0 to 100) of a student and tells if he/she passes the semester or not.

The created function studentsfuture takes three marks (math, English and art) and calculates the average (av) of them. If av is bigger or equal 70, the students has passed and gets the appropriated message printed including the average.
If av is smaller than 70, the students has not passed and the program tells him/her this including the average as well.

To call the created function it is needed to write the name of it (line 24). In the brackets are written the variables, in this example the student’s marks.

Since it is defined in the definition line that the order of of the marks is „math,english,art„, this is the exact order the the function expects the variables to be in.

However, it is possible to enter the variables in a different order. Therefore it is needed to clarify the variables and its values in the brackets when calling the function:

Fun fact: if there are two created functions with the same name only the second one is executed and printed.

Hinterlasse einen Kommentar

Erstelle eine Website wie diese mit WordPress.com
Jetzt starten