How to Define Functions in Python?

In this python tutorial, I am going to show how to define functions in Python with code snippets. 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 and save lots of time in coding.

 



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 function, we just have to call it as you can see below:

func_name()

Calling our function will output:

From my function

 

Python functions with parameters

We can also create our functions with parameters. You can take one or multiple parameters inside the function.

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 code, we will see the output:

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 we can set the default value to the parameter when we create a function with a parameter. 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 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 above.

Here, you can see that we haven’t passed the parameter value while calling our function. But it still takes the default parameter. 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

 

I hope, you have understood about functions and learned how to define functions in Python.

Also, read:

 

Leave a Reply

Your email address will not be published. Required fields are marked *