0% found this document useful (0 votes)
14 views

Module 2 - 2

J Lllll

Uploaded by

abinkchacko2005
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Module 2 - 2

J Lllll

Uploaded by

abinkchacko2005
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

Shiney Thomas

Dept. of CSE
Function
• A block of organized, reusable code that is
used to perform a single, related action
• Provide better modularity for your application
• High degree of code reusing
Function
• Functions are not necessary
• If no function -
- Difficult to verify
- Impossible to maintain
• Humans can remember only 3 - 7 things
• Abstraction
Use of functions
• Functions Eliminate Redundancy
• Functions Hide Complexity
Use of functions
• Functions support general methods with
systematic variations
• Functions support the division of labour
Function Syntax
def FunctionName (parameters):
statement(s)
return [expression]
Defining a function
• Keyword def marks the start of function header
• Function name - to uniquely identify it
• Parameters (arguments) through which we pass
values to a function (optional)
• A colon (:) to mark the end of function header
• One or more valid python statements that make
up the function body (must have same
indentation level)
• An optional return statement to return a value
from the function
Example
Calling a Function
• Execute it by calling it from another function
or directly from the Python prompt
return Statement
• Used to exit a function and go back to the place
from where it was called
• Syntax of return
return [expression_list]
• Expression
- gets evaluated and the value is returned
• If no expression or the return statement itself is
not present
- function will return the None object
Example
Scope of variables
• Scope of a variable - the portion of a program
where the variable is recognized
• Parameters and variables defined inside a
function is not visible from outside
• Local scope
Scope of variables
• Namespace is the complete list of names, including
all objects, functions, etc. that exist in a given
context.
• The scope of an object is the namespace within
which the object is available.
• A variable/object created in the main program is
available all through the program i.e., global
namespace
• A variable/object created within a function is only
available within that function i.e, local namespace
• When a variable name is used the Python
interpreter looks for that variable within the
relevant scope first.
Scope of variables
Scope of variables
Lifetime of a variable
• Period throughout which the variable exits in
the memory
• Lifetime of variables inside a function is as
long as the function executes
• Destroyed once the function is returned
• Function does not remember the value of a
variable from its previous calls
Lifetime of a variable
Examples with function
• Add two numbers
• Without arg,
• With arg
• With arg and return value
• Find all Prime factors of a no
• Calculator
Function Arguments, Higher order
functions and lambda function
Passing Arguments
• The objects sent to a function are called its
arguments. Arguments are sometimes also
called parameters.
• Passing an object as a argument to a
function passes a reference to that object.
• Argument names in the def line of the
function becomes new, local names.
• Arguments are passed in two ways:
• ‘Immutables’ are passed by value eg., String,
Integer, Tuple
• ‘Mutables’ are passed by reference eg., Lists
Function Arguments
• Call a function by using the following types of
formal arguments
- Required arguments
- Keyword arguments(Named arguments)
- Default arguments
- Variable-length arguments
Required arguments
• Arguments passed to a function in correct
positional order
• Number of arguments in the function call
should match exactly with the function
definition
Example - required arguments
Keyword arguments(Named arguments)
• So far we looked at positional parameters
• Caller identifies the arguments by the
parameter name
• Place them out of order- provide parameters in
any order and sequence
Example - Keyword
Default arguments
• An argument that assumes a default value
• Allows to skip arguments- supply none, some or
all
Default arguments
• Any no. of arguments in a function can have
default value. But once you have a default arg., all
the arguments to its right should also have
default values.
• Otherwise error will be shown:
Variable-length arguments
• To process a function for more arguments
than specified
• Called variable-length arguments
• Not named in the function definition, unlike
required and default arguments
Variable length syntax
def functionname([formal_args,] *var_args_tuple ):
statement(s)
return [expression]
• An asterisk (*) - placed before the variable name
that holds the values of all non keyword variable
arguments
• Tuple remains empty if no additional arguments
are specified during the function call
Variable length Example
lambda Function
• Anonymous - because they are not declared in the
standard manner by using the def keyword
• use the lambda keyword to create small anonymous
functions
• Lambda functions can take any number of arguments
• Return just one value in the form of an expression
• Contain commands or multiple expressions
• Cannot be a direct call to print because lambda
requires an expression
• Lambda functions have their own local namespace
• Cannot access variables other than those in their
parameter list and those in the global namespace
lambda - Syntax
• lambda arguments : expression
• lambda [arg1 [,arg2,.....argn]]:expression
lambda examples
Higher order functions and lambda

• filter function
Higher order functions and lambda
• map function

• reduce function
Recursive Functions
Recursion
• Recursion is a way of programming or coding a
problem
• Function calls itself one or more times in its
body
Recursion Examples
• Example – 1 factorial
• Example – 2 fibonacci
• Example – 3 sum of n nos.

Advantages of Recursion
• Make the code look clean and elegant
• A complex task can be broken down into
simpler sub-problems using recursion
• Sequence generation is easier with recursion
than using some nested iteration
Disadvantages of Recursion
• Sometimes the logic behind recursion is hard
to follow through
• Recursive calls are expensive (inefficient) as
they take up a lot of memory and time.
• Recursive functions are hard to debug
Exercise - 8
1. Write a Python function to check whether a
number is in a given range.
2. Write a Python function that accepts a string
and calculate the number of upper case
letters and lower case letters. (use isupper()
and islower() methods)
3. Write a Python function that takes a number
as a parameter and check the number is
prime or not.
Exercise - 8
4. Write a Python function to check whether a
number is perfect or not.
- In number theory, a perfect number is a positive
integer that is equal to the sum of its proper
positive divisors, that is, the sum of its positive
divisors excluding the number itself. Equivalently, a
perfect number is a number that is half the sum of
all of its positive divisors (including itself).
- 1 + 2 + 3 = 6 and ( 1 + 2 + 3 + 6 ) / 2 = 6
- 28 = 1 + 2 + 4 + 7 + 14 and (1 + 2 + 4 + 7 + 14+28)/2
Exercise - 8
5.Write a Python function that checks whether
a passed string is palindrome or not
6.Write a Python function to calculate the
factorial of a number using recursion
7.Write a Python function to print the fibonacci
series using recursion
References
• PPT adapted from GEC Thrissur
• Textbook- Fundamentals of Python by
Kenneth Lambert,B L Juneja

You might also like