Functions in Python

In Python, a function is a group of related statements that performs a specific task.

Syntax

def function_name(parameters):
      statement(s)

The function has the following components:

Function Call A function call is how you tell Python to execute a function that was previously defined.

When we call a function:

Syntax of Function Call function_name(arguments)

Explanation:

Key Notes

Example: Create a function without Parameter.

Python

# Function definition
def fun_name():
    print("Hello Ashish")
    print("How are you?")

# Function call
fun_name()

The output of the above code is shown below:
Hello Ashish
How are you?

Example: Create a function with Parameter.

Python

# Function definition with a parameter
def fun_name(name):
    print(f"Hello {name}")
    print("How are you?")

# Function call with argument
fun_name("Ashish")

The output of the above code is shown below:
Hello Ashish
How are you?

Note: Here, the name is the parameter and Ashish is the argument.

Example: Create a function with multiple parameters.

Python

# Function definition
def fun_name(name, country):
    print(f"Hello {name}")
    print(f"I am living in {country}.")

# Function call
fun_name(name="Ashish", country="India")

The output of the above code is shown below:
Hello Ashish
I am living in India.