Introduction to Python Functions

What is Python Functions?

  • A function is a block of organized, reusable code that is used to perform a single, related action.
  • Functions help break our program into smaller and modular chunks. As our program grows larger and larger, functions make it more organized and manageable.
  • Functions provide better modularity for your application and a high degree of code reusing.

  • Syntax of Function

    def function_name(parameters):
        statement(s) or coding logic    
        return [expression] - Optional 

    Rules for Creating Functions

  • Function blocks begin with the keyword 'def' followed by the function name, parentheses and colon '():'
  • Any input parameters or arguments should be placed within these parentheses. You can also define parameters inside these parentheses. These are optional
  • Function Doc string describe in brief, what a function does.. This is optional
  • Statement(s) or coding logic - Reusable code needs to mentioned here.
  • All the statements inside the function should be indented using equal spaces.
  • The "return [expression]" statement will return a value from the function. This is optional
  • A return statement with no arguments is the same as return None.

  • Example 1:

    # Function to Welcome User
    def welcomeUser(name):
        This function welcome's the user for python class
        print("Dear "+ str(name) +", Welcome to Python Tutorials")  

    How to call a Function ?

    To call a function we simply type the function name with appropriate parameters

    # Calling the Function
    Dear Kavsik, Welcome to Python Tutorials
    # Reusing the same function with different values
    Dear Abdul, Welcome to Python Tutorials
    Dear Vidya, Welcome to Python Tutorials
    Dear Aravind, Welcome to Python Tutorials

    Note: We can also call from another function, program or even the Python prompt.

    Example 2:

    # Function to check whether a number is even or odd 
    def verifyEvenOdd( num ): 
        if (num % 2 == 0): 
            print("{} is even number".format(num))
            print("{} is odd number".format(num))
    # Calling the Function
    2 is even number
    5 is odd number

    Doc String

  • The first string after the function header is called the docstring and is short for documentation string.
  • Although optional, documentation is a good programming practice, always document your code.
  • Doc string will be written in triple quotes so that docstring can extend up to multiple lines.
  • This string is available to us as __doc__ attribute of the function.
  • # Print doc string of the function
    print(welcomeUser.__doc__)    # Function with Doc String
    print(verifyEvenOdd.__doc__)  # Function without Doc String
        This function welcome's the user for python class

    Function with return value

  • return statement can contain an expression which gets evaluated and the value is returned.
  • if there is no expression in the statement or the return statement itself is not present inside a function, then the function will return None Object.
  • The return statement is used to exit a function and go back to the place from where it was called.
  • Syntax:    
        return [expression]

    Example 3:

    # Function to adds two numbers and returns the output
    def add(x,y):
        return x + y
    # Calling the Function

    Example 4:

    # Function to add the numbers within the mentioned range
    def sum(start,end):
        result = 0
        for i in range(start, end + 1):
            result += i
        return result
    # Calling the function and saving the value to a variable    
    value = sum(8,25)
    print("The Sum of numbers within the mentioned limit is",value)
    The Sum of numbers within the mentioned limit is 297

    Pass by reference vs value

  • All parameters (arguments) in the Python language are passed by "reference".
  • It means if you change what a parameter refers to within a function, the change also reflects back in the calling function.

  • Example 5:

    # Function Using pass by reference
    def updateMe( mylist ):
        mylist = [40,50,60];
        print ("Values inside the function: ", mylist)
    # Calling updateMe function 
    mylist = [10,20,30];
    updateMe( mylist );
    print ("Values outside the function: ", mylist)
    Values inside the function:  [40, 50, 60]
    Values outside the function:  [10, 20, 30]

    Note: When argument is being passed by reference and the reference is being overwritten inside the called function

    Scope and Life Time of Variables

    1. Global variables

  • Variables that are not bound to any function , but can be accessed inside as well as outside the function are called global variables.
  • Lifetime of a variable is the period throughout which the variable exits in the memory.

  • 2. Local variables

  • Variables which are declared inside a function are called local variables.
  • The lifetime of variables inside a function is as long as the function executes. Variables are destroyed once we return from the function.

  • Example 6:

    # Code to verify the scope of global variable
    # Declaring the global variable
    globalVar = "This is global variable"
    def test_life_time():
        print(globalVar)      #Using global variable inside the function
    #calling function
    #print global variable 
    print(globalVar) #Using global variable outside the function
    This is global variable
    This is global variable

    Example 7:

    # Code to verify the scope of local variable
    def test_life_time():
        # Declaring the local variable
        localVar = "This is local variable"
        print(localVar)  #Using local variable inside the function
    #calling function
    #print local variable 
    print(localVar) #Using local variable outside the function
    This is local variable
    NameError: Traceback (most recent call last)
    <ipython-input-25-976ba6276170> in <module>()
         11 #print local variable
    ---> 12 print(localVar) #Using localVar variable outside the function
    NameError: name 'localVar' is not defined