Friday, 1 December 2017

Python Functions

Functions : In Python, function is a group of related statements that perform a specific task.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 in Python are used to utilize the code in more than one place in a program, sometimes also called method or procedures. Python provides you many inbuilt functions like print(), but it also gives freedom to create your own functions.


How to define and call a function in Python:

function in Python is defined by the "def " statement followed by the function name and parentheses ( () )


def function_name(parameters):

"""docstring"""

statement(s)

Above shown is a function definition which consists of following components.
  1. Keyword def marks the start of function header.
  2. A function name to uniquely identify it. Function naming follows the same rules of writing identifiers in Python.
  3. Parameters (arguments) through which we pass values to a function. They are optional.
  4. A colon (:) to mark the end of function header.
  5. Optional documentation string (docstring) to describe what the function does.
  6. One or more valid python statements that make up the function body. Statements must have same indentation level (usually 4 spaces).
  7. An optional return statement to return a value from the function.
Ex:def greet(name):
"""This function greets to
the person passed in as
parameter"""
print("Hello, " + name + ". Good morning!")

Function Call

Once we have defined a function, we can call it from another function, program or even the Python prompt. To call a function we simply type the function name with appropriate parameters.
Ex : greet('pyhton programming')

Significance of Indentation (Space) in Python

Before we get familiarize with Python functions, it is important that we understand the indentation rule to declare Python functions and these rules are applicable to other elements of Python as well like declaring conditions, loops or variable.
Python follows a particular style of indentation to define the code, since Python functions don't have any explicit begin or end like curly braces to indicate the start and stop for the function, they have to rely on this indentation. Here we take a simple example with "print" command. When we write "print" function right below the def func 1 (): It will show an "indentation error: expected an indented block".
Python Functions Tutorial - Define, Call, Indentation & Arguments
Now, when you add the indent (space) in front of "print" function, it should print as expected.
Python Functions Tutorial - Define, Call, Indentation & Arguments
At least, one indent is enough to make your code work successfully. But as a best practice it is advisable to leave about 3-4 indent to call your function.

The return statement

The return statement is used to exit a function and go back to the place from where it was called.
syntax: return expression
This statement can contain 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 the None object.
Ex:print(greet("May"))
Hello, May. Good morning!
output:None

Arguments in Functions

The argument is a value that is passed to the function when it's called.In other words on the calling side, it is an argument and on the function side it is a parameter.
Step 1) Arguments are declared in the function definition. While calling the function, you can pass the values for that args as shown below
Python Functions Tutorial - Define, Call, Indentation & Arguments
Step 2) To declare a default value of an argument, assign it a value at function definition.
Python Functions Tutorial - Define, Call, Indentation & Arguments
Example: x has no default values. Default values of y=0. When we supply only one argument while calling multiply function, Python assigns the supplied value to x while keeping the value of y=0. Hence the multiply of x*y=0
Python Functions Tutorial - Define, Call, Indentation & Arguments
Step 3) This time we will change the value to y=2 instead of the default value y=0, and it will return the output as (4x2)=8.
Python Functions Tutorial - Define, Call, Indentation & Arguments
Step 4) You can also change the order in which the arguments can be passed in Python. Here we have reversed the order of the value x and y to x=4 and y=2.
Python Functions Tutorial - Define, Call, Indentation & Arguments
Step 5) Multiple Arguments can also be passed as an array. Here in the example we call the multiple args (1,2,3,4,5) by calling the (*args) function.
Example: We declared multiple args as number (1,2,3,4,5) when we call the (*args) function; it prints out the output as (1,2,3,4,5)
Python Functions Tutorial - Define, Call, Indentation & Arguments

Scope and Lifetime of variables

Scope of a variable is the portion of a program where the variable is recognized. Parameters and variables defined inside a function is not visible from outside. Hence, they have a local scope.Lifetime of a variable is the period throughout which the variable exits in the memory. The lifetime of variables inside a function is as long as the function executes.
They are destroyed once we return from the function. Hence, a function does not remember the value of a variable from its previous calls.
Ex:def my_func():
x = 10
print("Value inside function:",x)
x = 20
my_func()
print("Value outside function:",x)

Variable Function Arguments::

Python Default Arguments
Function arguments can have default values in Python.

We can provide a default value to an argument by using the assignment operator (=).
def greet(name, msg = "Good morning!"):
   """
   This function greets to
   the person with the
   provided message.

   If message is not provided,
   it defaults to "Good
   morning!"
   """

   print("Hello",name + ', ' + msg)

greet("Kate")
greet("Bruce","How do you do?")

Note:: Any number of arguments in a function can have a default value. But once we have a default argument, all the arguments to its right must also have default values.

Python keyword arguments:

Python allows functions to be called using keyword arguments. When we call functions in this way, the order (position) of the arguments can be changed. Following calls to the above function are all valid and produce the same result.

Python recursion:

Recursion is the process of defining something in terms of itself.A physical world example would be to place two parallel mirrors facing each other. Any object in between them would be reflected recursively.
Ex: def factorial(n):
    if n == 1:
        return 1
    else:
        return n * factorial(n-1)
print factorial(3)

Limitations of recursions::


Everytime a function calls itself and stores some memory. Thus, a recursive function could hold much more memory than a traditional function. Python stops the function calls after a depth of 1000 calls. If you run this example:
def factorial(n):
    if n == 1:
        return 1
    else:
        return n * factorial(n-1)


print factorial(3000)

you will get error: RuntimeError: maximum recursion depth exceeded.


In other programming languages, your program could simply crash. You can resolve this by modifying the number of recursion calls such as:

import sys

sys.setrecursionlimit(5000)

def factorial(n):
    if n == 1:
        return 1
    else:
        return n * factorial(n-1)


print factorial(3000)

Anonymous/Lambda functions:
In Python, anonymous function is a function that is defined without a name.While normal functions are defined using the def keyword, in Python anonymous functions are defined using the lambda keyword.
anonymous functions are also called lambda functions.

Lambda Functions ::A lambda function has the following syntax.

Syntax of Lambda Function ::
lambda arguments: expression

Lambda functions can have any number of arguments but only one expression. The expression is evaluated and returned. Lambda functions can be used wherever function objects are required.

The lambda's general form is :

lambda arg1, arg2, ...argN : expression using arguments

Function objects returned by running lambda expressions work exactly the same as those created and assigned by defs. However, there are a few differences that make lambda useful in specialized roles:

lambda is an expression, not a statement.
Because of this, a lambda can appear in places a def is not allowed. For example, places like inside a list literal, or a function call's arguments. As an expression, lambda returns a value that can optionally be assigned a name. In contrast, the def statement always assigns the new function to the name in the header, instead of returning is as a result.
lambda's body is a single expression, not a block of statements.

The lambda's body is similar to what we'd put in a def body's return statement. We simply type the result as an expression instead of explicitly returning it. Because it is limited to an expression, a lambda is less general that a def. We can only squeeze design, to limit program nesting. lambda is designed for coding simple functions, and def handles larger tasks.

double = lambda x: x * 2

# Output: 10

print(double(5))

2) my_list = [1, 5, 4, 6, 8, 11, 3, 12]


new_list = list(filter(lambda x: (x%2 == 0) , my_list))


# Output: [4, 6, 8, 12]


print(new_list)

3) f = lambda x, y, z: x + y + z
 f(2, 30, 400)
output:432

4) mz = (lambda a = 'Wolfgangus', b = ' Theophilus', c = ' Mozart' : a + b + c)
 mz('Wolfgang', ' Amadeus')
'Wolfgang Amadeus Mozart'


5)L = [lambda x: x ** 2,
         lambda x: x ** 3,
         lambda x: x ** 4]
for f in L:
print(f(3))

output:9
27
81

*args: In Python, the single-asterisk form of *args can be used as a parameter to send a non-keyworded variable-length argument list to functions. It is worth noting that the asterisk (*) is the important element here, as the word args is the established conventional idiom, though it is not enforced by the language.

We may want to use *args when we're not sure how many arguments might be passed to our function, i.e. it allows us to pass an arbitrary number of arguments to our function.


**kwargs  ::The double asterisk form of **kwargs is used to pass a keyworded, variable-length argument dictionary to a function. Again, the two asterisks (**) are the important element here, as the word kwargs is conventionally used, though not enforced by the language.

The ** is similar but it only works for keyword arguments. In other words, it collects them into a new dictionary. Actually, ** allows us to convert from keywords to dictionaries.


ike *args**kwargs can take however many arguments you would like to supply to it. However, **kwargs differs from *args in that you will need to assign keywords.

Ordering Arguments:
When ordering arguments within a function or function call, arguments need to occur in a particular order:

1)Formal positional arguments
2)*args
3)Keyword arguments
4) **kwargs
when working with explicit positional parameters along with *args and **kwargs, your function would look like this:
def example(arg_1, arg_2, *args, **kwargs):
And, when working with positional parameters along with named keyword parameters in addition to *args and **kwargs, your function would look like this:

def example2(arg_1, arg_2, *args, kw_1="shark", kw_2="blobfish", **kwargs):


No comments:

Post a Comment