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:
- The def keyword is used at the start to define the function.
- A colon (:) is used to mark the end of the function header.
- Defining parameters (arguments) in the function through which we pass values is optional.
Function Call A function call is how you tell Python to execute a function that was previously defined.
When we call a function:
- Python jumps to the function definition.
- Executes the statements inside it.
- Then returns back to the place where it was called.
Syntax of Function Call function_name(arguments)
Explanation:
- function_name → the name of the function we defined.
- arguments → values we pass to the function (optional).
Key Notes
- We can call a function many times after defining it.
- Always define a function before calling it.
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.