Table of contents
1.
Introduction
2.
Function Basics
2.1.
Python
3.
Function Arguments
3.1.
Python
4.
Returning Values
4.1.
Python
5.
Default Arguments
5.1.
Python
6.
Variable Number of Arguments:
6.1.
Python
6.2.
Python
7.
Keyword Arguments
7.1.
Python
8.
Calling Functions from Functions
8.1.
Python
9.
Handling Exceptions
10.
Frequently Asked Questions
10.1.
Can a function call itself in Python?
10.2.
How can I pass a variable number of arguments to a function?
10.3.
What happens if I don't provide a return statement in a function?
11.
Conclusion
Last Updated: Jun 29, 2024
Medium

How to Call a Function in Python?

Author Sinki Kumari
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Functions are an essential part of Python programming. They allow you to break down your code into smaller, reusable pieces that can be called whenever needed. Functions help make your code more organized, readable & maintainable. 

How to Call a Function in Python

In this article, we will learn how to call functions in Python, which covers everything from the basics to more advanced concepts like keyword arguments & handling exceptions.

Function Basics

In Python, a function is defined using the "def" keyword, followed by the function name & parentheses (). The code inside the function is indented & executed when the function is called. To call a function, you simply write its name followed by parentheses.

Here's a simple example:

  • Python

Python

def greet():

print("Hello, World!")

greet() 
You can also try this code with Online Python Compiler
Run Code

 

Output: 

Hello, World!

 

In this code, we define a function named "greet" that prints "Hello, World!" when called. To call the function, we write its name followed by parentheses: greet().

Function Arguments

Functions can also accept arguments, which are values passed to the function when it is called. Arguments allow you to provide input to a function, making it more flexible & reusable. To define a function with arguments, you specify the argument names inside the parentheses when defining the function.

Example : 

  • Python

Python

def greet(name):

print("Hello, " + name + "!")

greet("Rinki") 

greet("Gaurav") 
You can also try this code with Online Python Compiler
Run Code

 

Output: 

Hello, Rinki!
Hello, Gaurav!


In this code, the "greet" function accepts a single argument named "name". When calling the function, you provide a value for the argument inside the parentheses. The function then uses the provided value to print a personalized greeting.

Returning Values

Functions can also return values using the "return" statement. When a function encounters a return statement, it immediately exits the function & returns the specified value to the caller. This allows you to use the result of a function in other parts of your code.

Example : 

  • Python

Python

def add_numbers(a, b):

return a + b

result = add_numbers(5, 3)

print(result) 
You can also try this code with Online Python Compiler
Run Code

 

Output: 

8


In this code, the "add_numbers" function takes two arguments, "a" & "b", & returns their sum using the return statement. When the function is called with the values 5 & 3, it returns the value 8, which is then assigned to the variable "result" & printed.

Default Arguments

Python allows you to specify default values for function arguments. If a value is not provided for an argument when the function is called, the default value is used instead. This can be useful when you want to provide a default behavior for a function while still allowing flexibility.

Example : 

  • Python

Python

def greet(name, greeting="Hello"):

print(greeting + ", " + name + "!")

greet("Sinki") 

greet("Sanjana", greeting="Hi")
You can also try this code with Online Python Compiler
Run Code


Output: 

Hello, Sinki!
Hi, Sanjana!


In this code, the "greet" function has two arguments: "name" & "greeting". The "greeting" argument has a default value of "Hello". If a value is not provided for "greeting" when calling the function, the default value is used. However, you can still provide a different value for "greeting" if needed, as shown in the second function call.

Variable Number of Arguments:

Python allows you to define functions that accept a variable number of arguments. This is useful when you don't know in advance how many arguments will be passed to the function. There are two ways to handle variable arguments:

a. *args: You can use the "*args" syntax to pass a variable number of non-keyword arguments to a function. The arguments are passed as a tuple.

  • Python

Python

def sum_numbers(*args):

total = 0

for num in args:

total += num

return total

result = sum_numbers(1, 2, 3, 4, 5)

print(result) 
You can also try this code with Online Python Compiler
Run Code


Output

15


b. **kwargs: You can use the "**kwargs" syntax to pass a variable number of keyword arguments to a function. The arguments are passed as a dictionary.

  • Python

Python

def print_info(**kwargs):

for key, value in kwargs.items():

print(key + ": " + str(value))

print_info(name="Ravi", age=25, city="New Delhi")
You can also try this code with Online Python Compiler
Run Code


Output

name: Ravi
age: 25
city: New Delhi


Using "*args" & "**kwargs", you can create flexible functions that can handle different numbers of arguments.

Keyword Arguments

When calling a function, you can use keyword arguments to specify the values for specific parameters by their name. This allows you to provide arguments in any order, as long as you use the correct parameter names.

Example 

  • Python

Python

def greet(name, greeting):

print(greeting + ", " + name + "!")

greet(name="Rekha", greeting="Hello") 

greet(greeting="Hi", name="Lekhika") 
You can also try this code with Online Python Compiler
Run Code


Output: 

Hello, Rekha!
Hi, Lekhika!


In this code, the "greet" function expects two arguments: "name" & "greeting". When calling the function, you can use the parameter names to specify the values, regardless of the order. This makes the function call more readable & helps avoid confusion when there are multiple arguments.

Calling Functions from Functions

In Python, you can call a function from within another function. This allows you to break down complex tasks into smaller, more manageable pieces and reuse code effectively.

Example : 

  • Python

Python

def calculate_area(length, width):

return length * width

def calculate_perimeter(length, width):

return 2 * (length + width)

def print_rectangle_info(length, width):

area = calculate_area(length, width)

perimeter = calculate_perimeter(length, width)

print("Area:", area)

print("Perimeter:", perimeter)

print_rectangle_info(5, 3)
You can also try this code with Online Python Compiler
Run Code


Output

Area: 15
Perimeter: 16


In this code, we have three functions: calculate_area, calculate_perimeter, and print_rectangle_info. The print_rectangle_info function calls both calculate_area and calculate_perimeter to compute the area and perimeter of a rectangle, respectively. It then prints the results.

Handling Exceptions

When calling functions, it's important to handle potential exceptions that may occur. Exceptions are errors that happen during the execution of a program. Python provides a mechanism to handle exceptions using the try and except statements.

Example : 

def divide_numbers(a, b):
try:
result = a / b
print("Result:", result)
except ZeroDivisionError:
print("Error: Division by zero!")
divide_numbers(10, 2)  # Output: Result: 5.0
divide_numbers(10, 0)  # Output: Error: Division by zero!


In this code, the divide_numbers function attempts to divide the first argument a by the second argument b. However, if b is zero, a ZeroDivisionError exception will occur. 

To handle this exception, we wrap the division operation inside a try block. If an exception occurs, the program will jump to the corresponding except block and execute the code inside it.

Frequently Asked Questions

Can a function call itself in Python?

Yes, a function can call itself. This is known as recursion. However, it's important to define a base case to avoid infinite recursion.

How can I pass a variable number of arguments to a function?

You can use the *args syntax to pass a variable number of non-keyword arguments and the **kwargs syntax to pass a variable number of keyword arguments.

What happens if I don't provide a return statement in a function?

If you don't provide a return statement, the function will implicitly return None by default.

Conclusion

In this article, we have learned the fundamentals of calling functions in Python. We explained how to define functions, pass arguments, return values, use default arguments, handle variable numbers of arguments, use keyword arguments, call functions from within other functions, and handle exceptions. 

You can also practice coding questions commonly asked in interviews on Coding Ninjas Code360

Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Live masterclass