2. Introduction
A function is a block of organized and reusable program
code that performs a single, specific and well defined task.
A function is a block of code which only runs when it is
called.
You can pass data, known as parameters, into a function.
A function can return data as a result.
3. Defining a function
When a function is defined space is allocated for that function in the
memory.
A function definition comprises of two parts.
1. Function Header
2. Function Body
In Python a function is defined using the def keyword:
Give the function name after def keyword followed by parentheses in which arguments are
given
End with colon (:)
Inside the function add the program statements to be executed
End with or without return statement
4. Contd…
The general format is given:
function header
def function_name(var1, var2, ….):
documentation string
statement block function body
return[expression]
Example:
def my_function():
print("Hello from function")
my_function()
The indented statements from body of the function
5. Function Call
The function call statement invokes the function.
When a function is invoked the program control jumps to the called function
to execute the statements that are a part of that function.
Once the called function is executed the program control passes back to the
calling function.
The syntax of calling a function that does not accept parameters is simply
the name of the function followed by parenthesis, which is given as,
function_name()
6. Contd…
Function call statement has the following syntax when it accepts parameters:
function_name(var1, var2,….)
When the function is called the interpreter checks that the correct number
and type of arguments are used in the function call.
It also checks the type of the returned value
Note:-
-> List of variables used in function call is known as the actual parameter
list.
-> The actual parameter list may be variable names, expressions or
constants.
7. Function Parameters
A function can take parameters which are nothing but some values that are
passes to it so that the function can manipulate them to produce the desired
result.
These parameters are normal variables with a small difference that the values
of these variables are defined when we call the function and are then passed
to the function.
Parameters are specified within the pair of parenthesis in the function
definition and are separated by commas.
Key points to remember while calling the function:
-> The function name and the number of arguments in the function call
must be same as that given in the function definition.
8. -> If by mistake the parameters passed to a function are more than that it is
specified to accept, then an error will be returned.
Example:-
def funct(i, j):
print(“Hello World”,i,j)
funct(5)
Output:-
Type Error
-> If by mistake the parameters passed to a function are less than that it is
specified to accept, then an error will be returned.
9. Example:-
def funct(i):
print(“Hello World”,i)
funct(5, 5)
Output:-
Type Error
-> Names of variables in function call and header of function definition may
vary.
Example:-
def funct(i):
print(“Hello World”,i)
j = 10
funct(j)
Output:-
Hello World 10
11. Introduction
A fruitful function is one in which there is a return statement with an
expression.
This means that a fruitful function returns a value that can be utilized by
the calling function for further processing.
12. The Return Statement
To let a function return a value, use the return statement:
Every function has an implicit return statement as the last instruction in
the function body.
This implicit return statement returns nothing to its caller, so it is said
to return none.
But you can change this default behaviour by explicitly using the
return statement to return some value back to the caller.
The syntax of return statement is
return(expression)
13. Note:-
-> A function may or may not return a value.
The return statement is used for two things:
1. Return a value to the caller
2. To end and exit a function and go back to its caller.
Example:-
def cube(x):
return(x*x*x)
num = 10
result = cube(3)
print(“Cube = ”, result)
Output:-
Cube = 27
14. Key points to remember:
The return statement must appear within the function
Once you return a value from a function it immediately exits that function.
Therefore, any code written after the return statement is never executed.
15. Parameters
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.
The following example has a function with one argument (fname). When
the function is called, we pass along a first name, which is used inside
the function to print the full name:
16. Example:-
def my_function(fname):
print(fname + “Mr.")
my_function("Emil")
my_function("Tobias")
my_function("Linus")
Parameters or Arguments?
The terms parameter and argument can be used for the same thing: information
that are passed into a function.
18. Required Arguments
In the required arguments the arguments are passed to a function in correct
positional order.
Also the number of arguments in the function call should exactly match with the
number of arguments specified in the function definition.
Example:-
def display(str):
print(str)
str =“Hello”
display(str)
Output:-
Hello
19. Keyword Arguments
You can also send arguments with the key = value syntax.
Python allows functions to be called using keyword arguments in which the
order of the arguments can be changed.
The values are not assigned to arguments according to their position but
based on their name.
Example:-
def my_function(child3, child2, child1):
print("The youngest child is " + child3)
my_function(child1 = "Emil",child2="Tobias",child3 = "Linus")
Output:-
The youngest child is Linus
20. Key points to remember:
All the keyword arguments passed should match one of the arguments
accepted by the function.
The order of keyword arguments is not important.
In no case an argument should receive a value more than once.
21. Default Arguments
Python allows function arguments to have default values. If the
function is called without the argument, the argument gets its
default value.
The following example shows how to use a default parameter value.
If we call the function without argument, it uses the default value:
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
22. Key Points to remember
You can specify any number of default arguments in your function.
If you have default arguments Then they must be written after the
non-default arguments. This means that non-default arguments
cannot follow default arguments.
Example:-
def display(name, course =“MCA”, marks)
print(name, course, marks)
display(name = “Riya”,85)
Output:-
Syntax error
23. Variable – Length Arguments
Python allows programmers to make function calls with arbitrary(or any)
number of arguments.
When we use arbitrary arguments or variable length arguments then the
function definition uses an asterisk(*) before the parameter name.
The syntax is given:
def function_name([arg1,arg2,…], *var_args_tuple):
function_statements
return [expression]
24. Example:-
def funct(name, *subjects):
print(name,”likes to read”)
for s in subjects:
print(s,”t”)
funct(“Abinesh”,”Maths”,”Science”)
funct(“Riya”,”C”,”C++”,”Pascal”,”Java”,”Python”)
funct(“Abi”)
Output:-
Abinesh likes to read Maths Science
Riya likes to read C C++ Pascal Java Python
Abi likes to read
26. Introduction
A lambda function is a small anonymous function.
A lambda function can take any number of arguments, but can only have
one expression.
They are not declared as other functions using the def keyword.
Lambda functions contain only a single line.
Syntax is given:
lambda arguments:expression
The arguments contain a comma separated list of arguments and the
expression in an arithmetic expression that uses these arguments.
27. Example:-
Add 10 to argument a, and return the result:
x = lambda a : a + 10
print(x(5))
Lambda functions can take any number of arguments:
Multiply argument a with argument b and return the result:
x = lambda a, b : a * b
print(x(5, 6))
Summarize argument a, b, and c and return the result:
x = lambda a, b, c : a + b + c
print(x(5, 6, 2))
28. Key Points to Remember:
1. Lambda functions have no name.
2. Lambda functions can take any number of arguments.
3. Lambda functions can return just one value in the form of an expression.
4. Lambda function definition does not have an explicit return statement
but it always contain an expression which is returned.
5. They are a one line version of a function and hence cannot contain
multiple expressions.
6. They cannot access variables other than those in their parameter list.
7. Lambda functions cannot even access global variables.
8. You can pass lambda functions as arguments in other functions.
29. Program that passes lambda function as an argument to a function.
def func(f, n):
print(n)
twice = lambda x: x *2
thrice = lambda x:x * 3
func(twice, 4)
func(thrice, 3)
31. Introduction
A recursive function is defined as a function that calls itself to solve a
smaller version of its task until a final call is made which does not require a
call to itself.
Every recursive solution has two major cases.
1. Base case – in which the problem is simple enough to be solved
directly without making any further calls to the same function.
2. Recursive case – in which first the problem at hand is divided into
simpler sub parts. Second the function calls itself but with sub parts of the
problem obtained in the first step. Third, the result is obtained by combining
the solutions of simpler sub-parts.
32. To calculate the factorial of a number
def fact(n):
if(n==1 or n==0):
return 1
else:
return n * fact(n-1)
n = int(input(“Enter n:”))
print(“Factorial = ”, fact(n))
Output:-
Enter n:5
Factorial = 120
33. Recursion with Iteration
Recursion is more of a top-down approach to problem solving in which
the original problem is divided into smaller sub-problems.
Iteration follows a bottom-up approach that begins with what is known
and then constructing the solution step-by-step.
Benefits:-
Recursive solutions often tend to be shorter and simpler than non-recursive
ones.
Code is clearer and easier to use.
Recursion uses the original formula to solve a problem.
It follows a divide and conquer technique to solve a problems.
In some instances, recursion may be more efficient.
34. Limitations:-
For some programmers and readers recursion is a difficult concept.
Recursion is implemented using system stack.
Using a recursive function takes more memory and time to execute as
compared to its non-recursive counterpart.
It is difficult to find bugs, particularly when using global variables.