FUNCTIONS IN PYTHON

                                                 Functions in Python


Functions are an essential part of the Python programming language you might have already encountered and used some of the many fantastic functions that are built-in in the Python language or that come with its library ecosystem. However, as a Data Scientist, you’ll constantly need to write your own functions to solve problems that your data poses to you. 

You use functions in programming to bundle a set of instructions that you want to use repeatedly or that, because of their complexity, are better self-contained in a sub-program and called when needed. 

That means that a function is a piece of code written to carry out a specified task. To carry out that specific task, the function might or might not need multiple inputs.

When the task is carried out, the function can or can not return one or more values.


Types of functions in Python:


                              *Built-in Functions

                              *User-Defined Functions (UDFs)

                               *Anonymous functions



Built-in functions -:


Some examples of built-in functions are as follows :

*help() to ask for help

*min() to get the minimum value,

*print() to print an object 



User-Defined Functions (UDFs) -:


User-Defined Functions which are functions that users create to help them out.


#How To Define A Function: User-Defined Functions (UDFs)


The four steps to defining a function in Python are the following:


*Use the keyword def to declare the function and follow this up with the function name.

*Add parameters to the function: they should be within the parentheses of the function. End your line with a colon.

*Add statements that the functions should execute.

*End your function with a return statement if the function should output something. Without the return statement, your function will return an object None.


Example -:


def hello():

  print("Hello Python") 

  return


Output -:


>>> hello()

Hello Python

>>> 


#How To Call A Function


In the previous sections, you have seen a example already of how you can call a function.

Calling a function means that you execute the function that you have defined-either

directly from the Python prompt or through another function (as you will see in the section “Nested Functions”).

Call your newly defined function hello() by simply executing hello().


Output of calling a function -:


hello()


Function Arguments in Python


Arguments are the things which are given to any function or method call,

while the function or method code refers to the arguments by their parameter names.


There are four types of arguments that Python UDFs can take:


Default arguments

Required arguments

Keyword arguments

Variable number of arguments


Default Arguments -:


Default arguments are those that take a default value if no argument value is passed during the function call.

You can assign this default value by with the assignment operator =,

just like in the following example:

Example -:

# Define `plus()` function


def plus(a, b = 2):

  return a + b


# Call `plus()` with only `a` parameter


# Call `plus()` with `a` and `b` parameters


Output -:


>>> plus(a=1)

3

>>> 

>>> plus(a=1,b=3)

4

>>> 


Required Arguments  -:


As the name kind of gives away, the required arguments of a UDF are those that have to be in there.

These arguments need to be passed during the function call and in precisely the right order, just like in the following example.


Example -:


# Define `plus()` function with required arguments

def plus(a, b):

  return a + b


Output -:


>>> plus()

Traceback (most recent call last):

  File "<pyshell#4>", line 1, in <module>

    plus()

TypeError: plus() missing 2 required positional arguments: 'a' and 'b'

>>> 


You need arguments that map to the a as well as the b parameters to call the function without getting any errors. 

If you switch around a and b, the result won’t be different, but it might be if you change plus() to the following.


Keyword Arguments -:


If you want to make sure that you call all the parameters in the right order,

you can use the keyword arguments in your function call.

You use these to identify the arguments by their parameter name.

Let’s take the example from above to make this a bit more clear.


Example -:


# Define `plus()` function


def plus(a, b):

  return a + b

  # Call `plus()` function with parameters 

# Call `plus()` function with keyword arguments


Output -:


>>> plus(2,3)

5

>>> 

>>> plus(a=1,b=2)

3

>>> 

Note that by using the keyword arguments, you can also switch around the order of the parameters and still get the same result when you execute your function.


Variable Number of Arguments -:


In cases where you don’t know the exact number of arguments that you want to pass to a function, you can use the following syntax with *args.


Example -:


# Define `plus()` function to accept a variable number of arguments


def plus(*args):

  return sum(args)


Output -:


>>> plus(1,4,5)

10

>>> 


The asterisk (*) is placed before the variable name that holds the values of all non keyword variable arguments. 

Note here that you might as well have passed *varint, *var_int_args or any other name to the plus() function.


Global vs Local Variables -:


In general, variables that are defined inside a function body have a local scope,

and those defined outside have a global scope.

That means that local variables are defined within a function block and can only be accessed inside that function, while global variables can be obtained by all functions that might be in your script.


Anonymous functions -:

Anonymous functions, which are also called lambda functions because instead of declaring them with the standard def keyword, you use the lambda keyword.


double

 = lambda x: x*2


Output -:


>>> double(5)

10

>>> 

You use anonymous functions when you require a nameless function for a short period of time, and that is created at runtime. 

Specific contexts in which this would be relevant is when you’re working with filter(), map() and zip().


Some basic functions in python are as follows:


Map Function -:


It is a function to which map passes each element of given iterable. It is a iterable which is to be mapped.

You can pass one or more iterable to the map() function. The returned value from map() (map object) then can be passed to functions like list() (to create a list), set() (to create a set) .


Syntax -: 


map(fun, iter)


Example 1 -:


nums = [1, 2, 3, 4, 5]  


def sq(n):    

    return n*n  


square = list(map(sq, nums))

print(square)


Output -:


[1, 4, 9, 16, 25]


Example 2 -: Using Lambda inside map


nums = [1, 2, 3, 4, 5]

square = list(map(lambda x: x**x, nums))

print(square)


Output -:

[1, 4, 27, 256, 3125]


Filter Function -:

Function that tests if each element of a sequence true or not. Iterable which needs to be filtered.


Syntax -: 

filter(fun, Iter)


Example -:


seq = [0, 1, 2, 3, 4, 5]


# result contains odd numbers of the list


result = filter(lambda x: x % 2, seq)

print(list(result))


# result contains even numbers of the list


result = filter(lambda x: x % 2 == 0, seq)

print(list(result)) 


Output -:


[1, 3, 5]

[0, 2, 4]


Zip Function -:

    

The zip() function take iterables (can be zero or more), makes iterator that

aggregates elements based on the iterables passed, and returns an iterator of tuples.


Syantax -: 


zip(*iterables)


Example -:


name = ["Manjeet", "Nikhil", "Shambhavi"]

roll_no = [4, 1, 3]

marks = [40, 50, 60]

mapped = zip(name, roll_no, marks)

print(list(mapped))


Output -:


[('Manjeet', 4, 40), ('Nikhil', 1, 50), ('Shambhavi', 3, 60)]


Comments

Popular posts from this blog