How to Define Functions in Python?
In this Python tutorial, you will learn how to define functions in Python with the help of examples.
Before we create our function, let’s understand what are Python functions and what it does in brief.
What are Python Functions?
Python Functions are a convenient way to divide our code into useful blocks that can be reused in order to save lots of time in coding and developing tasks.
How to define functions in Python?
Creating a function in Python is a simple and easy task. To define a Python function, the
def block keyword used. Using the
def block keyword we can create our functions just like we can see in the code snippet below:
def func_name(): print("From my function")
To use our created Python function, we just have to call it like you can see below:
Calling our function will output:
From my function
Python functions with parameters
We can also create our functions with parameters. You can create one or multiple parameters for a function during its creation.
Below is an example:
def func_name(firstname, lastname): print("My name is "+firstname+" "+lastname) #Call our function func_name("John","Carter")
Now if we run the above program, you will see the output given below:
My name is John Carter
So we have learned how we can create simple functions in PHP with parameters. We are going to learn more about it. So let’s continue…
Set default value to our function
Another interesting fact about functions is that you can set the default value to the parameter when creating the function with one or multiple parameters.
If we call the above function without one or both of two parameters, then it will return an error. In that case, passing parameters is mandatory.
But, we can set the default parameter value and then when we call our function without giving any parameter value, it will not show any error and take the default parameter values.
See the example below:
def func_name(firstname="John", lastname="Carter"): print("My name is "+firstname+" "+lastname) # Call our function func_name()
In the above code, we will get the same output as we can see in our previous example.
Here, you can see that we haven’t passed the parameter value while calling our function. But it still takes the default parameter and uses it when we call the function. Now see what happens if we pass values in parameters when we call it:
# Call our function func_name("Taylor", "Morgan")
It will output:
My name is Taylor Morgan
As you can see above, taking a parameter value replaces the default value of the parameter.
I hope, you have understood functions and learned how to define functions in Python.