• Articles
  • Tutorials
  • Interview Questions

How to Call a Function in Python| Learn Types & Methods

How to Call a Function in Python| Learn Types & Methods

Table of content

Show More

Calling a function in Python involves using a function multiple times in a program to avoid repetition during the code execution. It is done by using the def keyword followed by the function name. In this blog, you will learn how to call a Python function in detail and how to create and build functions.

According to a survey by Stack Overflow, Python is the most used programming language after Javascript. According to LinkedIn, there are more than 15000+ job openings for Python developers in India.

Check out this YouTube video specially designed for Python beginners.

Video Thumbnail

What are Functions in Python?

In Python, functions are like reusable sets of instructions that do a specific job. They can take in some information, work with it, and then give you a result using the “return” statement. Functions are handy because they help organize the code into smaller and logical parts, making it easier to read and maintain. You can use a function in Python over and over with different inputs, making them a key part of building programs and making the code work efficiently.

Syntax:

They are defined using the “def” keyword, followed by a function name and a set of parameters enclosed in parentheses. For example, the below image represents the syntax for a function as def function_name (). The body of the function is indented and contains the instructions to be executed when the function is called. Refer to the below image for better clarity.

Functions in Python

How to Create a Python Function

Creating a function in Python is a fundamental aspect of the language and follows a simple syntax. Here’s a basic explanation of how you can create a function in Python: 

Syntax:

def function_name(parameter1, parameter2, …):

    # Function body – where you write the code that the function executes

    # Use parameters to perform operations

    # Optionally, return a value using the ‘return’ statement

    # Indentation is crucial; it defines the code block within the function

    # Example:

    result = parameter1 + parameter2

    return result  # Optional return statement

Explanation:

  • “def” is the keyword used to define a function in Python.
  • “function_name” is the name you give to your function. It should follow the variable naming rules in Python.
  • “parameter1”, “parameter2”, etc., are optional input values (also called arguments) that the function can accept. If the function doesn’t need any parameters, you can leave the parentheses empty.
  • “return” is used to send a value back as the output of the function. It’s optional; a function can perform operations without returning any value.

Types of Functions in Python

In Python, functions can be categorized into several types based on their characteristics and usage. Some common types of functions include:

Types of Functions in Python
  • Built-In Functions: These are functions that are part of the Python standard library and are available for use without the need for explicit definition. Examples include len(), print(), and max(). Here is a usage of a built-in function in Python:
# Define a string
S = “Intellipaat”
# Using the len() to find the length of the string
length = len(S)
# Printing the output
print(length)
Output:
11
  • User-Defined Functions: These are functions created by the programmer to perform specific tasks. They are defined using the “def” keyword, followed by a function name and a block of code. Parameters can be specified to receive input values. Here is an example of a user-defined function:
def evenOdd(x):
    if(x%2 == 0):
print(“Even”)
    else:
print(“Odd”)
# Calling the function
evenOdd(2)
Output:
Even
  • Lambda Functions: These are small, one-liner, unnamed functions defined using the lambda keyword. They are often used for short-lived operations and are commonly employed with functions like map(), filter(), and sorted(). Here is an example of a lambda function in Python:
# Lambda Function to print square of number
Adder = lambda x:x*x
# Calling the function:
Adder(3)
Output:
9
  • Recursive Functions: Recursive functions are those that call themselves during their execution. They are particularly useful for solving problems that can be broken down into simpler, similar sub-problems. However, recursive functions must have a base case to prevent infinite recursion. Here is an example of a recursive function:
def factorial(x):
    if x == 1:
        return 1
    else:
        return (x * factorial(x-1))
num = 3
print("The factorial of", num, "is", factorial(num))
Output:
The factorial of 3 is 6

How to Call a Function in Python

In Python, calling functions allows us to execute a specific set of instructions or tasks defined within the function. Functions help organize code, promote reusability, and enhance readability by categorizing tasks. They enable efficient code management and execution, making programming more modular and scalable. Detailed steps for calling functions are mentioned below.

Calling Nested Function

In Python, you can define a function within another function, creating what’s called a nested function. Here’s an example:

Example:

def outer_function(x):
    def inner_function(y):
        return y * 2  # Just an example operation
    result = inner_function(x)  # Calling the inner function within the outer function
    return result

Explanation:

  • “outer_function” is the main function that contains the nested function “inner_function”.
  • inner_function is defined inside outer_function and is only accessible within the scope of outer_function.
  • outer_function takes an argument “x”.
  • Inside outer_function, inner_function is called with the argument x, performing some operation (in this case, doubling x).
  • The result of inner_function is stored in “result”, which is then returned by outer_function.

Usage:

When you call outer_function with an argument, it will invoke the nested inner_function:

result = outer_function(5)  # Calling the outer function with argument 5

print(“Result:”, result)  # Output will be: Result: 10

In this example, calling “outer_function(5)” triggers the nested inner_function to double the value passed (5), resulting in “10”. The outer function then returns this result, which is printed to the console.

Check out these Python Interview Questions to ace your interview.

The return statement

In Python, the return statement is used within a function to specify the result that should be returned to the caller once the function has finished executing. It effectively ends the execution of the current function and sends the specified value back to the calling location.

Example: 

def add_numbers(a, b):
    # Perform the addition
    sum = a + b
        # Return the result
    return sum
# Calling the function and storing the result
result = add_numbers(5, 7)
print(result) 
# Output: 12

Returning multiple values using tuples

def add_numbers_and_return(a, b):
    sum = a + b
    return sum, a, b
# Calling the function and unpacking the result
sum_result, num1, num2 = add_numbers_and_return(5, 7)
print(f"Sum: {sum_result}, Numbers: {num1} and {num2}")
  # Output: Sum: 12, Numbers: 5 and 7

Python Function Code Examples 

Let’s create a simple function named “add_numbers” that takes two numbers as parameters and returns their sum:

def add_numbers(a, b):
    sum_result = a + b
    return sum_result

Usage:

Once defined, you can use the function by calling it elsewhere in your code.

result = add_numbers(5, 7)  # Calling the function with arguments 5 and 7

print(“The sum is:”, result)  # Output will be: The sum is: 12

This “add_numbers” function, when called with arguments 5 and 7, will return the sum of those two numbers, which is 12 in this case.

Python Function Arguments and Its Types

When we create a function in Python, we pass some values within the parenthesis. These values are termed arguments or parameters.

Python supports different types of arguments to be passed during the function call. Here are they listed below:

  • Default argument
  • Keyword arguments (named arguments)
  • Positional arguments
  • Arbitrary arguments (variable-length arguments *args and **kwargs)

Let’s understand each of them individually.

Default Argument

This is a type of parameter wherein if the value for an argument is not provided, the default value is taken. Here is an example of a default argument: 

# Python program to demonstrate
# default arguments
def myFun(x, y=10):
    print("x: ", x)
    print("y: ", y)
# Driver code (We call myFun() with only
# argument)
myFun(20)
Output:
x:  20
y:  10

Keyword Arguments (named arguments)

The idea of such types of arguments is to allow a user to specify the argument names along with the values so that there is no need to remember the order of the arguments. Here is an example of the same:

# Python program to demonstrate Keyword Arguments
def student(firstname, lastname):
    print(firstname, lastname)
# Keyword arguments
student(firstname='Intellipaat', lastname='Practice')
student(lastname='Practice', firstname='Intellipaat')
Output:
Intellipaat Practice
Intellipaat Practice

Positional Arguments

This is a type of argument wherein one has to remember the order of the arguments in which they are to be provided. This is one of the most used ones out of all. Here is an example of the same:

def nameAge(name, age):
    print("Hi, I am", name)
    print("My age is ", age)
# You will get correct output because 
# argument is given in order
print("Case-1:")
nameAge("Intellipaat", 13)
# You will get incorrect output because
# argument is not in order
print("\nCase-2:")
nameAge(13, "Intellipaat")

Output:

Case-1:
Hi, I am Intellipaat
My age is  13
Case-2:
Hi, I am 13
My age is  Intellipaat

Arbitrary Arguments (variable-length arguments *args and **kwargs)

In a case where you want to pass n number of arguments to functions, you make use of arbitrary arguments like *args (Non-Keyword Arguments) and **kwargs (Keyword Arguments). Here are the examples for each of them:

# Python program to illustrate
# *args for variable number of arguments
def myFun(*args):
    for arg in args:
        print(arg)
myFun('Hello', 'Welcome', 'to', 'Intellipaat')
Output:
Hello
Welcome
to
Intellipaat
# Python program to illustrate
# *kwargs for variable number of keyword arguments
def myFun(**kwargs):
    for key, value in kwargs.items():
        print("%s == %s" % (key, value))
# Driver code
myFun(first='Welcome', mid='to', last='Intellipaat')
Output:
first == Welcome
mid == to
last == Intellipaat

Conclusion

Understanding how to create functions, call them with arguments, and even nested functions provides flexibility in Python programming. Utilizing these methods enables the development of versatile and adaptable code structures, catering to diverse needs and enhancing the overall functionality and readability of the codebase.

Course Schedule

Name Date Details
Python Course 14 Dec 2024(Sat-Sun) Weekend Batch View Details
21 Dec 2024(Sat-Sun) Weekend Batch
28 Dec 2024(Sat-Sun) Weekend Batch

About the Author

Senior Consultant Analytics & Data Science

Sahil Mattoo, a Senior Software Engineer at Eli Lilly and Company, is an accomplished professional with 14 years of experience in languages such as Java, Python, and JavaScript. Sahil has a strong foundation in system architecture, database management, and API integration.