Functions are bits of reusable code meant to comply with a single task, such as calculating the value of “e” for example.

Python already has some built-in functions, such as “print ()”, but it also gives you the possibility to create your own.

In order to define a function you use the command “def”, then you need to name the function and give it a parameter to take in. Some functions can take in no parameters and still work.

After that you tell the function what you want it to do, for example: “x=1, y=2 / c=x+y / return c”, this part here is very important, a function will ALWAYS return something, even if there are no values it will return the value “NONE”, with the return you can specify which value you want to have as a result, but more importantly “return” marks the end of a function, so even if we have a while, but we mess up the indentation of the return and place it inside the while, it will make it so that the while runs only once and then it will kill it, kind of like a break.

Once written function can be reused, or called, any number of times. The way in which you call a function is by writing its name and then fiving it a value for its parameter. For instance let’s say that you have the function “Multisumcation (x, y)”, the way to call this function would be: “Multisumcation (23, 45)”, taking in 23 as the value for x and 45 as the value for y.

You may fill up your function with whatever the hell you want, but be sure that it is properly indented and that you add the return statement at the end of it.

There is another way to define a function, with the “lambda” keyword instead of “def”.

This functions are called “Anonymous functions” and they have the following characteristics:

  • They can take any number of arguments but return just one value in the form of an expression. They cannot contain commands or multiple expressions.

 

  • An anonymous function cannot be a direct call to print because lambda requires an expression

 

  • Lambda functions have their own local namespace and cannot access variables other than those in their parameter list and those in the global namespace.

Since they can only poses a single statement they are written like this, for example:

Sum = lambda x, y: x + y

And it would be caled like this:

Sum (8, 16)

CC BY 4.0 Creating and calling Python functions by juansalvadorfernandez is licensed under a Creative Commons Attribution 4.0 International License.