Anyone Can Code.
What is a User Defined Function? Simply put, it is a function created by a user for themselves. Let's see how we can create these.
The syntax for creating a function is as follows:
Important Rules for User Defined Functions
()are known as parameters. Parameters are not always necessary and neither is a return value
To start, lets create a function to add two numbers.
Now that we have created a function, what do we do with it? In order to run the code inside a
function, you must call it.
To call a function, you have to use the following syntax:
name>(<paramaters, in order>)
So lets say we want to execute our
addition function on the numbers 3 and 5. To do
so we would call the function as so:
When you call a function, you tell the interpreter to execute the code inside the function.
What are parameters? Parameters are those placeholders created in the parentheses of a function header which can be used to store values given by a user while calling a function. Now, what are arguements? Arguements are the values given during a function call, which fill the placeholders created by parameters.
In the example above, the parameters are a and b while the arguements are 3 and 5.
Let's look at another example.
Here, the parameters are a and b, and the arguements are num1 and num2, whose
respective values are 2 and 1. As a result
num1 correspond to the same value and hence have the same id. Same applies for
There are two special cases we will look at for parameters:
Here, we gave
b a value of 2 beforehand, soo we only have to
give one parameter while calling the function, since one is already given. However,
we can override the default parameter and add a second arguement:
x+5, in your arguements.The interpreter will evaluate these expressions before calling the function.
To let the function return a value, we use the
This statement returns a value which can be used somewhere else, and can also return a function call, which can be useful for recursion, a topic beyond the syllabus.
In order to call a function, it must be defined before the function call. If we don't define a function before, we get the following error:
Traceback (most recent call last): File "
", line 1, in <module> NameError: name 'function' is not defined
Therefore, you must always define a function before you call it.
That's it for this tutorial! Scroll up and click on Next for the next tutorial!