Python – Functions

Course Curriculum

Python – Functions

A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing.
As you already know, Python gives you many built-in functions like print(), etc. but you can also create your own functions. These functions are called user-defined functions.

Creating a Function

You can create functions to provide the required functionality. Here are simple rules to define a function in Python.

  • Function blocks begin with the keyword def followed by the function name and parentheses ( ( ) ).
  • Any input parameters or arguments should be placed within these parentheses. You can also define parameters inside these parentheses.
  • The first statement of a function can be an optional statement - the documentation string of the function or docstring.
  • The code block within every function starts with a colon (:) and is indented.
  • The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None.

    Syntax

    def functionname( parameters ):
    "function_docstring"
    function_suite
    return [expression]

    By default, parameters have a positional behavior and you need to inform them in the same order that they were defined.

    Example

    The following function takes a string as input parameter and prints it on standard screen.

    def my_demo_function():
    print("this is example of creating function")
    my_demo_function()
  • Output
    this is example of creating function

    Calling a Function

    Defining a function only gives it a name, specifies the parameters that are to be included in the function and structures the blocks of code.
    Once the basic structure of a function is finalized, you can execute it by calling it from another function or directly from the Python prompt. Following is the example to call my_demo_function() function −

    Function definition is here

    def my_demo_function():
    print("this is example of creating function")

    Now you can call printme function

    my_demo_function()

    When the above code is executed, it produces the following result −

    this is example of creating function

    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. For example −

    # Function definition is here
    def append_emplpyee_names(name):
    name.append(['dev','mice','riki'])
    return name
    # function call
    name=["Sara","Ahmad","Dima","Raed","Wael"]
    print('values inside function',append_emplpyee_names(name))
    print('values outside function',name)

    Here, we are maintaining reference of the passed object and appending values in the same object. So, this would produce the following result −

    values inside function ['Sara', 'Ahmad', 'Dima', 'Raed', 'Wael', ['dev', 'mice', 'riki']]
    values outside function ['Sara', 'Ahmad', 'Dima', 'Raed', 'Wael', ['dev', 'mice', 'riki']]

    There is one more example where argument is being passed by reference and the reference is being overwritten inside the called function.

    # Function definition is here
    def change_emplpyee_names(name):
    name = ['dev','mice','riki']
    return name
    # Now you can call changeme function
    name=["Sara","Ahmad","Dima","Raed","Wael"]
    print('values inside function',change_emplpyee_names(name))
    print('values outside function',name)

    The parameter mylist is local to the function changeme. Changing mylist within the function does not affect mylist. The function accomplishes nothing and finally this would produce the following result −

    values inside function ['dev', 'mice', 'riki']
    values outside function ['Sara', 'Ahmad', 'Dima', 'Raed', 'Wael']

    Function Arguments

  • You can call a function by using the following types of formal arguments:
  • Required arguments
  • Keyword arguments
  • Default arguments
  • Variable-length arguments

    Required arguments

    Required arguments are the arguments passed to a function in correct positional order. Here, the number of arguments in the function call should match exactly with the function definition.

    # Function definition is here
    def greet(name):
    return 'Hello, ' + name
    # Now you can call printme function
    print(greet())

    When the above code is executed, it produces the following result −

    Traceback (most recent call last):
    File "demo.py", line 320, in <module>
    print(greet())
    TypeError: greet() missing 1 required positional argument: 'name'

    Keyword arguments

    Keyword arguments are related to the function calls. When you use keyword arguments in a function call, the caller identifies the arguments by the parameter name.
    This allows you to skip arguments or place them out of order because the Python interpreter is able to use the keywords provided to match the values with parameters. You can also make keyword calls to the printme() function in the following ways −

    # Function definition is here
    def greet(name):
    return 'Hello, ' + name
    # Now you can call function
    print(greet(name ='prutor'))

    When the above code is executed, it produces the following result −

    Hello, prutor

    The following example gives more clear picture. Note that the order of parameters does not matter.

    # Function definition is here
    def stuDetails(name,roll_no):
    print("student name : ",name)
    print("student roll no : ",roll_no)
    return
    # Now you can call printinfo function
    stuDetails(roll_no=56 , name='john')

    When the above code is executed, it produces the following result −

    student name :  john
    student roll no :  56

    Default arguments

    A default argument is an argument that assumes a default value if a value is not provided in the function call for that argument. The following example gives an idea on default arguments, it prints default age if it is not passed −

    # Function definition is here
    def stuDetails(name,roll_no,stu_class=12):
    print("student name : ",name)
    print("student roll no : ",roll_no)
    print("student class : ",stu_class)
    return
    # Now you can call function
    stuDetails('john',56,10)
    stuDetails('Smith',46)

    When the above code is executed, it produces the following result −

    student name :  john
    student roll no :  56
    student class :  12
    student name :  Smith
    student roll no :  46
    student class :  12

    Variable-length arguments

    You may need to process a function for more arguments than you specified while defining the function. These arguments are called variable-length arguments and are not named in the function definition, unlike required and default arguments.
    Syntax for a function with non-keyword variable arguments is this −

    def functionname([formal_args,] *var_args_tuple ):
    "function_docstring"
    function_suite
    return [expression]

    An asterisk (*) is placed before the variable name that holds the values of all nonkeyword variable arguments. This tuple remains empty if no additional arguments are specified during the function call. Following is a simple example −

    # Function definition is here
    def stuDetails(name,roll_no,stu_class,*marks):
    print("student name : ",name)
    print("student roll no : ",roll_no)
    print("student class : ",stu_class)
    for m in marks:
    print(m)
    return
    # Now you can call printinfo function
    stuDetails('John',47,12,80,90)
    stuDetails('Smith',46,12,80,90,95,100)

    When the above code is executed, it produces the following result −

    student name :  John
    student roll no :  47
    student class :  12
    80
    90
    student name :  Smith
    student roll no :  46
    student class :  12
    80
    90
    95
    100

    The Anonymous Functions

    These functions are called anonymous because they are not declared in the standard manner by using the def keyword. You can use the lambda keyword to create small anonymous functions.

  • Lambda forms can take any number of arguments but return just one value in the form of an expression. They cannot contain commands or multiple expressions.
  • An anonymous function cannot be a direct call to print because lambda requires an expression
  • Lambda functions have their own local namespace and cannot access variables other than those in their parameter list and those in the global namespace.
  • Although it appears that lambda's are a one-line version of a function, they are not equivalent to inline statements in C or C++, whose purpose is by passing function stack allocation during invocation for performance reasons.

    Syntax

    Small anonymous functions can be created with the lambda keyword. Lambda functions can be used
    wherever function objects are required. They are syntactically restricted to a single expression.
    Semantically, they are just syntactic sugar for a normal function definition. Like nested function
    definitions, lambda functions can reference variables from the containing scope.

    lambda [arg1 [,arg2,.....argn]]:expression

    Following is the example to show how lambda form of function works −

    # Function definition is here
    incrementByFive = lambda number: number + 5
    # Now you can call incrementByFive as a function
    print(incrementByFive(50))

    When the above code is executed, it produces the following result −

    55

    The return Statement

    The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None.
    All the above examples are not returning any value. You can return a value from a function as follows −

    # Function definition is here
    def areaOfCircle(radius):
    return 3.14*(radius*radius)
    # Now you can call sum function
    print("Area of Circle : " , areaOfCircle(5))

    When the above code is executed, it produces the following result −

    Area of Circle :  78.5

    Scope of Variables

    All variables in a program may not be accessible at all locations in that program. This depends on where you have declared a variable.
    The scope of a variable determines the portion of the program where you can access a particular identifier. There are two basic scopes of variables in Python −

  • Global variables
  • Local variables

    Global vs. Local variables

    Variables that are defined inside a function body have a local scope, and those defined outside have a global scope.
    This means that local variables can be accessed only inside the function in which they are declared, whereas global variables can be accessed throughout the program body by all functions. When you call a function, the variables declared inside it are brought into scope. Following is a simple example −

    print "Outside the function global total : ", total
    name = 'john' # This is global variable.
    # Function definition is here
    def findName(name):
    name = "prutor"
    print("Name inside function : " , name)
    return
    findName(name)
    print("name outside function : ",name)

    When the above code is executed, it produces the following result −

    Name inside function :  prutor
    name outside function :  john
Python – Tuples (Prev Lesson)
(Next Lesson) Python – Modules
', { 'anonymize_ip': true });