Calling a Function in Python with Example

In the previous tutorial, we have studied that a function ‘object’ is a block of code that performs a specific and well-defined task.

It is a useful way to divide the code into manageable segments. Function makes the program code more readable, reusable, and saves time.

Furthermore, a function executes when we call it.

Basically, a function call is a statement that executes the function object. When we call a user defined function, the program control jumps to the function definition and executes statements present in the function’s body.

Once all the statements inside the function’s body get executed, the program control goes back to the calling function. This process is called calling a function in Python.

We can call a user defined function in different ways. They are:

  • inside another function
  • through the main segment of the program
  • directly from the Python prompt.

Syntax for Calling a function in Python


The general syntax for calling a function in Python is the same as for built-in function. We just need to type the name of function, followed by parentheses. The syntax is as:

function_name() # function call.

In the above function call, we are not sending any argument values to the function because the function definition does not have any parameter list. This kind of function is called non-parametrized function. In the calling a non-parameterized function, we do not send any argument values to the function.

However, sometimes there may be some parameters in the function definition. This kind of function is called parameterized function.

When we call it by passing some argument values, the parameterized function receives argument values from the calling function. The general syntax for calling a parameterized function in Python is as:

function_name(argument1, argument2)

In the above function calling, the argument is a value that is passed to the function when it is called. On the calling side, we call it as argument and on the function side, we call it as parameter.

Execution Style of Calling a Function in Python


Let’s take some example program in which we will understand the execution style of calling a function in Python with the help of diagram.

Example 1:

# Function definition.
def funct_name(): # function header.
    print('This function does not contain any parameter.')
# Main program execution started from here.
funct_name() # function calling.
Output:
      This function does not contain any parameter.

In this example, we have created a function named funct_name that does not contain any parameter. When we called it, the program control goes to the function and executes the statement inside it and print the message.


Example 2:

# Function definition.
def calcSum(x, y): # Here, x and y are local variables.
    z = x + y # Here, z is a local variable.
    print("Sum of two numbers = ",z)
# Main program.
# Calling a function by passing two argument values.
calcSum(20, 30)
Output:
      Sum of two numbers =  50

In this example, when the Python interpreter executes calcSum(20, 30), the function calcSum() is called by passing two argument values.


Then, the program control goes to the calcSum() function and statements inside this function execute with using both values. Finally, the function prints the sum of two numbers as a result.

Look at the execution style of function in the below figure to understand more clearly.

Example of calling a function in Python

Calling a Function from another Function in Python


We can also call a function from another function in Python. Let’s write a program in which we will calculate the sum of two numbers by taking numbers as input from the user.

Program code:

# Function1 to take inputs from the user.
def funct_in():
    num1 = int(input('Enter your first number: '))
    num2 = int(input('Enter your second number: '))
    calcSum(num1, num2) # Calling function2 from function1.

# Function2 to calculate the sum of two numbers.
def calcSum(num1, num2):
    sum = num1 + num2
    print("Sum of two numbers = ",sum)

# Main part of the program.
funct_in() # calling function1.
Output:
      Enter your first number: 10
      Enter your second number: 50
      Sum of two numbers =  60

In this example program, we have created two functions; one is parameterized function calcSum(num1, num2) and another is non-parameterized function funct_in().

After taking the input from the user, we have invoked the function calcSum() from the funct_in() function. In this way, we can easily call one function from another function.

Examples based on Function Call


Example 1:

Let’s write a program in Python to calculate the perimeter and area of the rectangle using functions.

# Function1 to take the input from the user.
def funct_in():
    length = int(input('Enter the length of rectangle: '))
    breadth = int(input('Enter the breadth of rectangle: '))
    calcPer(length, breadth) # Calling function2 from function1.
    calcArea(length, breadth) # Calling function3 from the function1.

# Function2 to calculate the perimeter of rectangle.
def calcPer(l, b):
    per = 2 * (l + b)
    print("Perimeter of the rectangle = ",per)

# Function3 to calculate the area of the rectangle.
def calcArea(l, b):
    area = l * b
    print('Area of the rectangle =',area)

# Main part of the program.
funct_in() # calling function1.
Output:
      Enter the length of rectangle: 20
      Enter the breadth of rectangle: 30
      Perimeter of the rectangle =  100
      Area of the rectangle = 600

When the Python interpreter executes the funct_in(), then the program control goes to the function funct_in(). Inside the function, Python takes the length of rectangle in string from the user, cast into the integer, and then store it into a variable length. Similarly, for breadth.


When Python executes calcPer() function with passing arguments, the program control goes to function2 calcPer() and executes all statements by using argument values inside it.

After the complete execution of this function, the control goes back to the executing the function calcArea() inside the funct_in() function.

When the Python executes the function calcArea() with passing arguments, the control goes to the function calcArea() and executes all statements by using arguments inside it.


Example 2:

Let’s write a program in Python to calculate the addition, subtraction, multiplication, and division of two numbers taken from the user.

# Function1 to calculate addition of two numbers.
def add(x, y):
    z = x + y
    print("Addition:",z)
# Function2 to calculate the subtraction.
def sub(p, q):
    r = p - q
    print("Subtraction:",r)
# Function3 to calculate the multiplication.
def multiply(a, b):
    c = a * b
    print('Multiplication:',c)

# Function4 to calculate the division.
def div(n, m):
    d = n / m
    print('Division:',d)
# Function5 to take inputs from the user and calling.
def main_funct():
    n1 = int(input('Enter your first number: '))
    n2 = int(input('Enter your second number: '))
    add(n1, n2)
    sub(n1, n2)
    multiply(n1, n2)
    div(n1, n2)
# Main program.
main_funct() # calling function5.
Output:
      Enter your first number: 25
      Enter your second number: 5
      Addition: 30
      Subtraction: 20
      Multiplication: 125
      Division: 5.0

Example 3:

Let’s write a Python program to calculate the square of a given number.

def square(num):
    result = num * num
    print("Square of",num,"=",result)
square(5)
Output:
      Square of 5 = 25

Example 4:

Let’s write a program in Python to swap two numbers.

# Python program to swap two numbers.
def swap(x, y):
    print('Before swapping: ')
    print('x:',x)
    print('y:',y)
    temp = x
    x = y
    y = temp
    print('After swapping: ')
    print('x:',x)
    print('y:',y)
# Calling function with passing two arguments.
swap(20, 10)
Output:
      Before swapping: 
      x: 20
      y: 10
      After swapping: 
      x: 10
      y: 20

Example 5:

Let’s write a Python program to check the given number is even or odd.

# Python program to check a number is even or odd.
num = int(input('Enter your number to check even or odd: '))
# Create a function.
def evenorodd():
    if num % 2 == 0:
        print(num,'is an even number.')
    else:
        print(num,'is an odd number.')
# Calling function.
evenorodd()
Output:
      Enter your number to check even or odd: 20
      20 is an even number.
      Enter your number to check even or odd: 9
      9 is an odd number.

Example 6:

Let’s write a Python program to test whether a year is leap.

# Python program to check a year is leap or not.
year = int(input('Enter a year: '))
def leap():
    if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
        print(year,'is a leap year.')
    else:
        print(year,'is not a leap year.')
# Calling function.
leap()
Output:
      Enter a year: 2024
      2024 is a leap year.
      Enter a year: 2019
      2019 is not a leap year.

In this example program, we have used if statement to check the multiple conditions. We have used logical AND and logical OR operators. If all the conditions within the if statement are true, the year value is a leap year, otherwise not.

Some More Example Program for Practice

Example 7:

Let’s write a Python program to check a number is prime or not, using function calling.

A prime number is a number that is divisible by 1 and the number itself. If a natural number is greater than 1, and having no positive divisors other than 1 and the number itself, then it is a prime number.

For example, the natural numbers 3, 5, 7, 11, etc are prime numbers. Look at the following code to understand the implementation.

# Python program to check a number is prime or not.
# Create a function to check conditions for the prime.
def primeChecker(n):
    # Using if-else statement for checking the number is greater than 1.
    if n > 1:
        # Iterating over the number using for loop.
        for x in range(2, int(n/2) + 1):
            # Check the number is divisible or not.
            if (n % x) == 0:
                print(n, "is not a prime number.")
                break
           # Else part if it is a prime number.
            else:
                print(n, "is a prime number.")
    # Else part if the number is not greater than 1.
    else:
        print(x, "is not a prime number")

# Main part of the program.
# Take a number as input from the user.
n = int(input("Enter a number to check prime or not: "))
# Calling function with passing input number.
primeChecker(n)
Output:
      Enter a number to check prime or not: 5
      5 is a prime number.
      Enter a number to check prime or not: 6
      6 is not a prime number.

In this example, we have used nested if-else statement and for loop to check the conditions for the prime number.

First, we have taken a number as input from the user in the string form. Then, we have converted the entered number into int and stores it into a variable n. We called the function primeChecker() with passing the variable value.

Inside the function primeChecker(), we have used if-else statement to check the number is greater than 1 or not. If the number is not greater than 1, the else part will execute and print ‘not a prime number.’

Inside the outer if statement, we have used for loop to perform the iteration from 2 to number/2. Inside the for loop, we used the if-else statement. If the number is completely divisible by x with the remainder 0, then it is not a prime number; otherwise, the number is a prime number.


Example 8:

Let’s write a program in which we will create a function and print a list of values containing the square of numbers between 1 to 10 (both included).

def sqList():
  # Creating an empty list that will hold values.
    l = list()
    for x in range(1, 11):
        l.append(x ** 2)
    print(l)
# Function call.
sqList()
Output:
      [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

In this example, we have used the for loop for iteration over generated numbers. The numbers will automatically generated using range() function. We have used the append() function to store the result directly into the list.

The statement l = list means that we are creating an empty list that will store values generated while the for loop executes.


Example 9:

Suppose we have a list of five subject marks like [68, 98, 78, 88, 86] and we have to find and print the total marks and percentage of a student. Look at the program code.

def totalMarks():
  # Marks of five subjects for a student.
    marks = [68, 98, 78, 88, 86]
  # Transferring individual marks into independent variable.
    m1 = marks[0]
    m2 = marks[1]
    m3 = marks[2]
    m4 = marks[3]
    m5 = marks[4]
  # Total marks.
    totMarks = m1 + m2 + m3 + m4 + m5
    print('Total marks obtained:',totMarks)
  # Percentage.
    per = totMarks / 5
    print('Percentage:',per)
# Function call.
totalMarks()
Output:
      Total marks obtained: 418
      Percentage: 83.6

In this tutorial, we have learned about calling a function in Python with the help of various example programs. Hope that you will have understood the basic points of calling a function in Python and practiced all example programs.
Thanks for reading!!!

⇐ Prev Next ⇒

Please share your love