How to call a function in Python
Last Updated :
26 Jul, 2024
Python is an object-oriented language and it uses functions to reduce the repetition of the code. In this article, we will get to know what are parts, How to Create processes, and how to call them.
In Python, there is a reserved keyword "def" which we use to define a function in Python, and after "def" we give the name of the function which could be anything but we cannot use the reserved keyword of Python.
Create Functions in Python
Defining a Function
Before you can call a function, you need to define it. In Python, you define a function using the def
keyword followed by the function name and parentheses. Here's a simple example:
In this example, greet
is the name of the function, and it doesn't take any parameters.
Python
def greet():
print("Hello, World!")
Calling a Function
To call a function, you simply use the function name followed by parentheses. For the greet
function defined above, you would call it like this:
greet()
When this line of code is executed, the output will be:
Functions with Parameters
Functions can take parameters (or arguments), which are specified within the parentheses in the function definition. Here's an example:
Python
def greet(name):
print(f"Hello, {name}!")
You call this function and pass a value for the name
parameter:
greet("Alice")
The output will be:
Hello, Alice!
Default Parameter Values
You can provide default values for parameters. If a parameter with a default value is not passed when the function is called, the default value is used:
Python
def greet(name="World"):
print(f"Hello, {name}!")
You can call this function with or without an argument:
greet()
greet("Bob")
The output will be:
Hello, World!
Hello, Bob!
Returning Values from Functions
Functions can return values using the return
statement. Here's an example:
Python
def add(a, b):
return a + b
You call this function and use the returned value:
result = add(3, 5)
print(result)
The output will be:
8
Multiple Return Values
A function can return multiple values by separating them with commas. These values are returned as a tuple:
Python
def get_name_and_age():
name = "Alice"
age = 30
return name, age
You can capture these values in separate variables:
name, age = get_name_and_age()
print(name)
print(age)
The output will be:
Alice
30
Keyword Arguments
When calling a function, you can specify arguments by their parameter names. This is useful if you want to pass arguments in a different order or if a function has many parameters:
Python
def describe_person(name, age, city):
print(f"{name} is {age} years old and lives in {city}.")
describe_person(age=25, name="Bob", city="New York")
The output will be:
Bob is 25 years old and lives in New York.
Variable-Length Arguments
Sometimes you may not know in advance how many arguments will be passed to a function. Python allows you to handle this with variable-length arguments using *args
and **kwargs
:
*args
allows you to pass a variable number of non-keyword arguments.**kwargs
allows you to pass a variable number of keyword arguments.
Using *args
Python
def print_numbers(*args):
for number in args:
print(number)
print_numbers(1, 2, 3, 4, 5)
The output will be:
1
2
3
4
5
Using **kwargs
Python
def print_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
print_info(name="Alice", age=30, city="New York")
The output will be:
name: Alice
age: 30
city: New York
Examples - How to call a function in Python
Example: Function with the return statement
Here inside the function, we use the return statement, So whenever we call the function it will return some output, as the function is returning something we can use a variable to assign it. After that, we can check it by printing the variable
Python
def multiply_with_eight(x):
return 8 * x
result = multiply_with_eight(2) #Calling the function
print(result)
Output:
16
Example: Function with the print statement
Here we have the function which prints the output after performing the multiplication operation, so whenever we call the function it prints the multiplied value of the argument passed in it
Python
def multiply_with_eight(x):
print(x*8)
multiply_with_eight(7)
Output:
56
How to call a nested function
Nested functions are those functions that involve one or more functions inside them, we can call the nested function the same way we call a normal function but the key point here to remember is that we must call the function within its scope
Here we called the outer function, so as we call it the code within the function starts executing and it prints "This is outer function" As is done with this we called another function named inner_function which executes its function code and starts executing the print statement it contents. as a result we got to see first the print statement of outer_fucntion and then the print statement in inner_fucntion
Python
def outer_funtion():
print("This is outer function.")
def inner_function():
print("And this is inner function.")
inner_function()
outer_function()
Output:
This is outer function.
And this is inner function.
Similar Reads
How to Call a C function in Python
Have you ever came across the situation where you have to call C function using python? This article is going to help you on a very basic level and if you have not come across any situation like this, you enjoy knowing how it is possible.First, let's write one simple function using C and generate a
2 min read
How to Break a Function in Python?
In Python, breaking a function allows us to exit from loops within the function. With the help of the return statement and the break keyword, we can control the flow of the loop.Using return keywordThis statement immediately terminates a function and optionally returns a value. Once return is execut
2 min read
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:Python# Defining a function def fun(): print("Welcome to GFG") # calling a function fun() Let's unde
3 min read
How to Call Multiple Functions in Python
In Python, calling multiple functions is a common practice, especially when building modular, organized and maintainable code. In this article, weâll explore various ways we can call multiple functions in Python.The most straightforward way to call multiple functions is by executing them one after a
3 min read
How to Add Function in Python Dictionary
Dictionaries in Python are strong, adaptable data structures that support key-value pair storage. Because of this property, dictionaries are a necessary tool for many kinds of programming jobs. Adding functions as values to dictionaries is an intriguing and sophisticated use case. This article looks
4 min read
How to Recall a Function in Python
In Python, functions are reusable blocks of code that we can call multiple times throughout a program. Sometimes, we might need to call a function again either within itself or after it has been previously executed. In this article, we'll explore different scenarios where we can "recall" a function
4 min read
How to use Function Decorators in Python ?
In Python, a function can be passed as a parameter to another function (a function can also return another function). we can define a function inside another function. In this article, you will learn How to use Function Decorators in Python. Passing Function as ParametersIn Python, you can pass a fu
3 min read
Python | How to get function name ?
One of the most prominent styles of coding is following the OOP paradigm. For this, nowadays, stress has been to write code with modularity, increase debugging, and create a more robust, reusable code. This all encouraged the use of different functions for different tasks, and hence we are bound to
3 min read
How to pass an array to a function in Python
In this article, we will discuss how an array or list can be passed to a function as a parameter in Python. Pass an array to a function in Python So for instance, if we have thousands of values stored in an array and we want to perform the manipulation of those values in a specific function, that is
4 min read
Pass a List to a Function in Python
In Python, we can pass a list to a function, allowing to access or update the list's items. This makes the function more versatile and allows us to work with the list in many ways.Passing list by Reference When we pass a list to a function by reference, it refers to the original list. If we make any
2 min read