Module 3
Functions: Introduction to Functions, inbuilt functions,
user defined functions, passing parameters, return
values, recursion, Lambda functions
Functions
• A function is a block of code which only runs when it is
called.
• You can pass data, known as parameters, into a function.
Types:
• User defined functions
• Built-in-functions
Python built-in-function
• The Python built-in functions are defined as the functions
whose functionality is pre-defined in Python.
• abs() -Returns the absolute value of a number
• all() -Returns True if all items in an iterable object are
true
• any() -Returns True if any item in an iterable object is
true
• ascii() -Returns a readable version of an object. Replaces
none-ascii characters with escape character
User defined functions
• All the functions that are written by any us comes under
the category of user defined functions
• In Python, def keyword is used to declare user defined
functions.
• An indented block of statements follows the function name
and arguments which contains the body of the function.
Advantages for user defined function
• User-defined functions help to decompose a large
program into small segments which makes program easy
to understand, maintain and debug.
• If repeated code occurs in a program. Function can be
used to include those codes and execute when needed by
calling that function.
• Programmars working on large project can divide the
workload by making different functions.
Defining function
• In Python a function is defined using the def keyword:
def my_function():
print("Hello from a function")
Calling a Function
• To call a function, use the function name followed by
parenthesis:
def my_function():
print("Hello from a function")
my_function()
Function arguments
• Information can be passed into functions as arguments.
• Arguments are specified after the function name, inside
the parentheses. You can add as many arguments as you
want, just separate them with a comma.
• Required arguments
• Keyboard arguments
• Default arguments
• Variable-length arguments
Required arguments
• 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.
def printme( str ):
print str
return;
printme()
Keyboard arguments
• You can also send arguments with the key = value syntax.
• This way the order of the arguments does not matter.
def my_function(child3, child2, child1):
print("The youngest child is " + child3)
my_function(child1 = "Emil", child2 = "Tobias", child3
= "Linus")
Default arguments
• Default values indicate that the function argument will take that
value if no argument value is passed during the function call
• The default value is assigned by using the assignment(=)
operator of the form keyword name=value.passed during the
function call.
def student(firstname, lastname ='Mark', standard ='Fifth'):
print(firstname, lastname, 'studies in', standard,
'Standard')
Variable-length arguments
To process a function for more arguments than you
specified while defining the function. These arguments are
called variable-length arguments
def function name([formal_args,] *var_args_tuple ):
"function_docstring"
function_suite
return [expression]
Function parameters
• The terms parameter and argument can be used for the
same thing: information that are passed into a function.
• Name given in the function definition are called
parameters.
• Values supply in the function call are called arguments.
Anonymous function -LAMBDA
• A lambda function is a small anonymous function.
• A lambda function can take any number of arguments, but
can only have one expression.
• lambda arguments : expression
• x = lambda a : a + 10
print(x(5))
Use of Lambda Functions
• lambda is better shown when you use them as an
anonymous function inside another function.
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
print(mydoubler(11))
filter() in python
• The filter() method filters the given sequence with the help of
a function that tests each element in the sequence to be true
or not.
filter(function, sequence)
Parameters:
• function: function that tests if each element of a sequence
true or not.
• sequence: sequence which needs to be filtered, it can be
sets, lists, tuples, or containers of any iterators.
• Returns: returns an iterator that is already filtered.
Map() function
• map() function returns a map object(which is an iterator)
of the results after applying the given function to each
item of a given iterable (list, tuple etc.)
map(fun, iter)
Parameters :
• fun : It is a function to which map passes each element of
given iterable.
iter : It is a iterable which is to be mapped.
Scope of variable
• A variable is only available from inside the region it is created.
This is called scope.
Local Scope
• A variable created inside a function belongs to the local scope
of that function, and can only be used inside that function.
Global Scope
• A variable created in the main body of the Python code is a
global variable and belongs to the global scope.
• Global variables are available from within any scope, global and
local.
Local variable:
def myfunc():
x = 300
print(x)
myfunc()
Global variable:
x = 300
def myfunc():
print(x)
myfunc()
print(x)
Function prototype
• Function without arguments and without return type
• Function with arguments and without return type
• Function without arguments and with return type
• Function with arguments and with return type
Function without arguments and without return type
• In this type no argument is
passed through the
function call and no output
is return to main function
• The sub function will read
the input values perform
the operation and print the
result in the same block
def add():
a=int(input("enter a"))
b=int(input("enter b"))
c=a+b
print(c)
add()
Function with arguments and without return type
• Arguments are passed
through the function call
but output is not return to
the main function
def add(a,b):
c=a+b
print(c)
a=int(input("enter a"))
b=int(input("enter b"))
add(a,b)
Function without arguments and with return
type
• In this type no argument is
passed through the
function call but output is
return to the main function.
def add(a,b):
c=a+b
return c
a=int(input("enter a"))
b=int(input("enter b"))
c=add(a,b)
print(c)
Function with arguments and with return type
• In this type arguments are
passed through the
function call and output is
return to the main function
def add(a,b):
c=a+b
return c
a=int(input("enter a"))
b=int(input("enter b"))
c=add(a,b)
print(c)
Call by value
• It is a way of passing arguments to a function in which the
arguments get copied to the formal parameters of a
function and are stored in different memory locations.
• Any changes made within the function are not reflected in
the actual parameters of the function when called.
Call by Reference
• It is a way of passing arguments to a function call in which
both the actual argument and formal parameters refer to
the same memory locations
• Any changes made within the function are reflected in the
actual parameters of the function when called.
Recursion
• Python also accepts function recursion, which means a defined
function can call itself.
def tri_recursion(k):
if(k>0):
result = k+tri_recursion(k-1)
print(result)
else:
result = 0
return result
print("nnRecursion Example Results")
tri_recursion(6)

Python for Data Science function third module ppt.pptx

  • 1.
    Module 3 Functions: Introductionto Functions, inbuilt functions, user defined functions, passing parameters, return values, recursion, Lambda functions
  • 2.
    Functions • A functionis a block of code which only runs when it is called. • You can pass data, known as parameters, into a function. Types: • User defined functions • Built-in-functions
  • 3.
    Python built-in-function • ThePython built-in functions are defined as the functions whose functionality is pre-defined in Python. • abs() -Returns the absolute value of a number • all() -Returns True if all items in an iterable object are true • any() -Returns True if any item in an iterable object is true • ascii() -Returns a readable version of an object. Replaces none-ascii characters with escape character
  • 4.
    User defined functions •All the functions that are written by any us comes under the category of user defined functions • In Python, def keyword is used to declare user defined functions. • An indented block of statements follows the function name and arguments which contains the body of the function.
  • 5.
    Advantages for userdefined function • User-defined functions help to decompose a large program into small segments which makes program easy to understand, maintain and debug. • If repeated code occurs in a program. Function can be used to include those codes and execute when needed by calling that function. • Programmars working on large project can divide the workload by making different functions.
  • 6.
    Defining function • InPython a function is defined using the def keyword: def my_function(): print("Hello from a function") Calling a Function • To call a function, use the function name followed by parenthesis: def my_function(): print("Hello from a function") my_function()
  • 7.
    Function arguments • Informationcan be passed into functions as arguments. • Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma. • Required arguments • Keyboard arguments • Default arguments • Variable-length arguments
  • 8.
    Required arguments • Argumentspassed to a function in correct positional order. • Here, the number of arguments in the function call should match exactly with the function definition. def printme( str ): print str return; printme()
  • 9.
    Keyboard arguments • Youcan also send arguments with the key = value syntax. • This way the order of the arguments does not matter. def my_function(child3, child2, child1): print("The youngest child is " + child3) my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")
  • 10.
    Default arguments • Defaultvalues indicate that the function argument will take that value if no argument value is passed during the function call • The default value is assigned by using the assignment(=) operator of the form keyword name=value.passed during the function call. def student(firstname, lastname ='Mark', standard ='Fifth'): print(firstname, lastname, 'studies in', standard, 'Standard')
  • 11.
    Variable-length arguments To processa function for more arguments than you specified while defining the function. These arguments are called variable-length arguments def function name([formal_args,] *var_args_tuple ): "function_docstring" function_suite return [expression]
  • 12.
    Function parameters • Theterms parameter and argument can be used for the same thing: information that are passed into a function. • Name given in the function definition are called parameters. • Values supply in the function call are called arguments.
  • 13.
    Anonymous function -LAMBDA •A lambda function is a small anonymous function. • A lambda function can take any number of arguments, but can only have one expression. • lambda arguments : expression • x = lambda a : a + 10 print(x(5))
  • 14.
    Use of LambdaFunctions • lambda is better shown when you use them as an anonymous function inside another function. def myfunc(n): return lambda a : a * n mydoubler = myfunc(2) print(mydoubler(11))
  • 15.
    filter() in python •The filter() method filters the given sequence with the help of a function that tests each element in the sequence to be true or not. filter(function, sequence) Parameters: • function: function that tests if each element of a sequence true or not. • sequence: sequence which needs to be filtered, it can be sets, lists, tuples, or containers of any iterators. • Returns: returns an iterator that is already filtered.
  • 16.
    Map() function • map()function returns a map object(which is an iterator) of the results after applying the given function to each item of a given iterable (list, tuple etc.) map(fun, iter) Parameters : • fun : It is a function to which map passes each element of given iterable. iter : It is a iterable which is to be mapped.
  • 17.
    Scope of variable •A variable is only available from inside the region it is created. This is called scope. Local Scope • A variable created inside a function belongs to the local scope of that function, and can only be used inside that function. Global Scope • A variable created in the main body of the Python code is a global variable and belongs to the global scope. • Global variables are available from within any scope, global and local.
  • 18.
    Local variable: def myfunc(): x= 300 print(x) myfunc() Global variable: x = 300 def myfunc(): print(x) myfunc() print(x)
  • 19.
    Function prototype • Functionwithout arguments and without return type • Function with arguments and without return type • Function without arguments and with return type • Function with arguments and with return type
  • 20.
    Function without argumentsand without return type • In this type no argument is passed through the function call and no output is return to main function • The sub function will read the input values perform the operation and print the result in the same block def add(): a=int(input("enter a")) b=int(input("enter b")) c=a+b print(c) add()
  • 21.
    Function with argumentsand without return type • Arguments are passed through the function call but output is not return to the main function def add(a,b): c=a+b print(c) a=int(input("enter a")) b=int(input("enter b")) add(a,b)
  • 22.
    Function without argumentsand with return type • In this type no argument is passed through the function call but output is return to the main function. def add(a,b): c=a+b return c a=int(input("enter a")) b=int(input("enter b")) c=add(a,b) print(c)
  • 23.
    Function with argumentsand with return type • In this type arguments are passed through the function call and output is return to the main function def add(a,b): c=a+b return c a=int(input("enter a")) b=int(input("enter b")) c=add(a,b) print(c)
  • 24.
    Call by value •It is a way of passing arguments to a function in which the arguments get copied to the formal parameters of a function and are stored in different memory locations. • Any changes made within the function are not reflected in the actual parameters of the function when called.
  • 25.
    Call by Reference •It is a way of passing arguments to a function call in which both the actual argument and formal parameters refer to the same memory locations • Any changes made within the function are reflected in the actual parameters of the function when called.
  • 26.
    Recursion • Python alsoaccepts function recursion, which means a defined function can call itself. def tri_recursion(k): if(k>0): result = k+tri_recursion(k-1) print(result) else: result = 0 return result print("nnRecursion Example Results") tri_recursion(6)