+91 88606 33966            edu_sales@siriam.in                   Job Opening : On-site Functional Trainer/Instructor | Supply Chain Management (SCM)

Function is a block of statements that return the specific task. The idea is to put some commonly or repeatedly done tasks together and make a function so that instead of writing the same code again and again for different inputs, we can do the function calls to reuse code contained in it over and over again.

Advantages of Python Functions

  • Once defined, Python functions can be called multiple times and from any location in a program.
  • Our Python program can be broken up into numerous, easy-to-follow functions if it is significant.
  • The ability to return as many outputs as we want using a variety of arguments is one of Python’s most significant achievements.
  • However, Python programs have always incurred overhead when calling functions.

Illustration of a User-Defined Function

We will define a function that returns the argument number’s square when called.

# Example Python Code for User-Defined function  
def square( num ):    
    This function computes the square of the number.  
    return num**2     
object_ = square(6)    
print( "The square of the given number is: ", object_ )    
The square of the given number is:  36

Calling a Function

To define a function, use the def keyword to give it a name, specify the arguments it must receive, and organize the code block.

When the fundamental framework for a function is finished, we can call it from anywhere in the program.

# Example Python Code for calling a function  
# Defining a function    
def a_function( string ):    
    "This prints the value of length of string"    
    return len(string)    
# Calling the function we defined    
print( "Length of the string Functions is: ", a_function( "Functions" ) )    
print( "Length of the string Python is: ", a_function( "Python" ) )
# Output:

Length of the string Functions is:  9
Length of the string Python is:  6

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top