How to Define and Call a Function in Python
In Python, defining and calling functions is simple and may greatly improve the readability and reusability of our code. In this article, we will explore How we can define and call a function.
Example:
# Defining a function
def fun():
print("Welcome to GFG")
# calling a function
fun()
Let's understand defining and calling a function in detail:
Defining a Function
By using the word def keyword followed by the function's name and parentheses () we can define a function. If the function takes any arguments, they are included inside the parentheses. The code inside a function must be indented after the colon to indicate it belongs to that function.
Syntax of defining a function:
def function_name(parameters):
# Code to be executed
return value
- function_name: The name of your function.
- parameters: Optional. A list of parameters (input values) for the function.
- return: Optional. The return statement is used to send a result back from the function.
Example:
def fun():
print("Welcome to GFG")
# Defining a function with parameters
def greet(name, age):
print(name, age)
Explanation:
- fun(): A simple function that prints "Welcome to GFG" when called, without any parameters.
- greet(name, age): A function with two parameters (name and age) that prints the values passed to it when called.
Calling a Function
To call a function in Python, we definitely type the name of the function observed via parentheses (). If the function takes any arguments, they may be covered within the parentheses . Below is the example for calling def function Python.
Syntax of Calling a function:
function_name(arguments)
Example:
def fun():
print("Welcome to GFG")
#calling a function
fun()
# Defining a function with parameters
def greet(name, age):
print(name, age)
#calling a function by passing arguments
greet("Alice",21)
Output
Welcome to GFG Alice 21
Explanation:
- Calling fun(): The function fun() is called without any arguments, and it prints "Welcome to GFG".
- Calling greet("Alice", 21): The function greet() is called with the arguments "Alice" and 21, which are printed as "Alice 21".