KEMBAR78
JNTUK python programming python unit 3.pptx
Presented by
V Babu Ravipati
Unit -3
2
Functions
1. Reusability
2. Easy debugging
14. Python - Functions
A function is a block of organized, reusable code that is used to perform a single,
related action. Functions provides better modularity for your application and a high
degree of code reusing.
As you already know, Python gives you many built-in functions like print() etc. but you
can also create your own functions. These functions are called user-defined functions.
Defining a Function
Here are simple rules to define a function in Python:
• Function blocks begin with the keyword def followed by the
function name (shouldnot be keyword) and parentheses ( ) .
• Any input parameters or arguments should be placed within
these parentheses. You can also define parameters or
arguments inside these parentheses.
• The first statement of a function can be an optional statement
- the documentation string of the function or docstring.
• The code block within every function starts with a colon (:) and
is indented.
• The statement return [expression] exits a function, optionally
passing back an expression to the caller. A return statement
with no arguments is the same as return None.
Syntax:
def functionname( parameters ):
"function_docstring“
function_suite
[expression]
return
Example
Def add(a,b):
sum=a+b
return sum
a=int(input(“enter first number”))
b=int(input(“enter second number”))
res=add(a,b)
print(“result = “res)
Function Arguments:
A function by using the following types of formal arguments::
• Required arguments
• Keyword arguments
• Default arguments
• Variable-length arguments
Required arguments:
Required arguments are the arguments passed to a function in correct positional order.
def printme( name, age):
print ("Name: ", name)
print ("Age ", age)
return;
printme(name=“Ramu”, age=29);
This would produce following result:
Name: Ramu
Age 29
Keyword arguments:
• Keyword arguments are related to the function calls.
When you use keyword arguments in a function call,
the caller identifies the arguments by the parameter
name.
• This allows you to skip arguments or place them out
of order because the Python interpreter is able to
use the keywords provided to match the values with
parameters.
Following example gives more clear picture. Note, here order of the parameter
does not matter:
def printinfo( name, age ): "Test function"
print ("Name: ", name)
print ("Age ", age)
return
printinfo(age=50, name="miki" )
This would produce following result:
Name: miki Age 50
Default arguments:
A default argument is an argument that assumes a default value if a value is
not provided in the function call for that argument.
Following example gives idea on default arguments, it would print default age
if it is not passed:
def printinfo( name, age = 35 ): “Test function"
print ("Name: ", name)
print ("Age ", age)
return
printinfo( age=50, name="miki" )
printinfo( name="miki" )
This would produce following result:
Name: miki Age 50 Name: miki Age 35
Variable-length arguments:
You may need to process a function for more arguments than you specified
while defining the function. These arguments are called variable-length
arguments and are not named in the function definition, unlike required and
default arguments.
The general syntax for a function with non-keyword variable arguments is this:
def functionname([formal_args,] *var_args_tuple ):
"function_docstring"
function_suite
return [expression]
An asterisk (*) is placed before the variable name that will hold the values of
all nonkeyword variable arguments. This tuple remains empty if no additional
arguments are specified during the function call. For example:
def printinfo( arg1, *vartuple ):
"This is test"
print ("Output is: “)
print (arg1)
for var in vartuple:
print var
return
printinfo( 10 )
printinfo( 70, 60, 50 )
This would produce following result:
Output is:
10
Output is:
70
60
50
Lambda Function
Lambda functions are also called anonymous
functions. An anonymous function is a
function defined without a name. As we
know to define a normal function in python,
we need to use the def keyword. But in this
case of anonymous functions, we use the
lambda keyword to define the functions.
The characteristics of lambda function
• The lambda function can take many
arguments but can return only one expression.
• Syntactically, lambda functions are restricted
to only a single expression.
• We can use them as an anonymous function
inside other functions.
• Lambda function is reusable.
Why should we use lambda functions?
Lambda functions are used when we
need a function for a short period of
time. This is commonly used when we
want to pass a function as an argument
to higher-order functions, that is,
functions that take other functions as
their arguments
Why should we use lambda functions?
Example
17
Fruitful Functions
Properties of Fruitful functions are
1. Return Value
2. Incremental Development
3. Composition
4. Boolean type
1.Return Value
def sum()
a=10
b=15
c=a+b
print(c)
Sum()
def sum(a,b)
c=a+b
return c
Print(sum(10,15))
def area(radius):
temp = 3.14159 * radius**2
return temp
def area(radius):
return 3.14159 * radius**2
Sometimes it is useful to have multiple return statements, one in each branch of a
conditional.
def absolute_value(x):
if x < 0:
return -x
else:
return x
2.Incremental development
To deal with increasingly complex programs, we are
going to suggest a technique called incremental
development. The goal of incremental development is to
avoid long debugging sessions by adding and testing
only a small amount of code at a time.
As an example, suppose you want to find the distance
between two points, given by the coordinates (x1, y1)
and (x2, y2). By the Pythagorean theorem, the distance
is:
def distance(x1, y1, x2, y2):
"""Return the distance between points
(x1, y1) and (x2, y2) as a float"""
return 0.0
def distance(x1, y1, x2, y2):
"""Return the distance between points
(x1, y1) and (x2, y2) as a float"""
dx = x2 - x1
dy = y2 - y1
print 'dx is ', dx
print 'dy is ', dy
return 0.0
def distance(x1, y1, x2, y2):
"""Return the distance between points
(x1, y1) and (x2, y2) as a float"""
dx, dy = x2 - x1, y2 - y1
result =(dx**2 + dy**2)**0.5
return result
def distance(x1, y1, x2, y2):
"""Return the distance between points
(x1, y1) and (x2, y2) as a float"""
result =((x2-x1)**2 + (y2-y1)**2)**0.5
return result
def distance(x1, y1, x2, y2):
"""Return the distance between points
(x1, y1) and (x2, y2) as a float"""
return((x2-x1)**2 + (y2-y1)**2)**0.5
The key aspects of the process are:
1. Start with a working program and make small
incremental changes. At any point, if there is an error,
you will know exactly where it is.
2. Use temporary variables to hold intermediate values
so you can output and check them.
3. Once the program is working, you might want to
remove some of the scaffolding or consolidate
multiple statements into compound expressions, but
only if it does not make the program difficult to read.
3.Composition
As you should expect by now, you can call one function
from within another. This ability is called composition.
def area2(xc, yc, xp, yp):
radius = distance(xc, yc, xp, yp)
result = area(radius)
return result
def area2(xc, yc, xp, yp):
return area(distance(xc, yc, xp, yp))
4.Creating Boolean functions
Functions that return a Boolean value
(True or False) can be used in
conditional statements (i.e. if…
else…)
05/02/09
Python Mini-Course: Day 2 - Lesson 8
28
is_divisible function
def is_divisible(x, y):
if x % y == 0:
return True
else:
return False
is_divisible(16,4)
is_divisible(16,3)
05/02/09
Python Mini-Course: Day 2 - Lesson 8
29
Scope of Variables:
All variables in a program may not be accessible at all locations in that program. This
depends on where you have declared a variable.
The scope of a variable determines the portion of the program where you can access a
particular identifier. There are two basic scopes of variables in Python:
Global variables
Local variables
Global vs. Local variables:
Variables that are defined inside a function body have a local scope, and those defined
outside have a global scope.
This means that local variables can be accessed only inside the function in which they
are declared whereas global variables can be accessed throughout the program body by
all functions. When you call a function, the variables declared inside it are brought into
scope.
Example:
total = 0; # This is global variable.
def sum( arg1, arg2 ):
"Add both the parameters"
total = arg1 + arg2;
print "Inside the function local total : ", total
return total;
# Now you can call sum function
sum( 10, 20 );
print "Outside the function global total : ", total
This would produce following result:
Inside the function local total : 30
Outside the function global total : 0
There is one more example where argument is being passed by reference but inside the
function, but the reference is being over-written.
def changeme( mylist ): "This changes a passed list"
mylist = [1,2,3,4];
print("Values inside the function: ", mylist)
return
mylist = [10,20,30];
changeme( mylist );
Print("Values outside the function: ", mylist)
The parameter mylist is local to the function changeme. Changing mylist within the function
does not affect mylist. The function accomplishes nothing and finally this would produce
following result:
Values inside the function: [1, 2, 3, 4]
Values outside the function: [10, 20, 30]
Pass by reference vs value
All parameters (arguments) in the Python language are passed by reference. It means if
you change what a parameter refers to within a function, the change also reflects back
in the calling function. For example:
def changeme( mylist ): "This changes a passed list“
mylist.append([1,2,3,4]);
print ("Values inside the function: ", mylist)
return
mylist = [10,20,30];
changeme( mylist );
print ("Values outside the function: ", mylist)
So this would produce following result:
Values inside the function: [10, 20, 30, [1, 2, 3, 4]]
Values outside the function: [10, 20, 30, [1, 2, 3, 4]]
Name space
JNTUK python programming python unit 3.pptx

JNTUK python programming python unit 3.pptx

  • 1.
    Presented by V BabuRavipati Unit -3
  • 2.
  • 3.
    14. Python -Functions A function is a block of organized, reusable code that is used to perform a single, related action. Functions provides better modularity for your application and a high degree of code reusing. As you already know, Python gives you many built-in functions like print() etc. but you can also create your own functions. These functions are called user-defined functions.
  • 4.
    Defining a Function Hereare simple rules to define a function in Python: • Function blocks begin with the keyword def followed by the function name (shouldnot be keyword) and parentheses ( ) . • Any input parameters or arguments should be placed within these parentheses. You can also define parameters or arguments inside these parentheses. • The first statement of a function can be an optional statement - the documentation string of the function or docstring. • The code block within every function starts with a colon (:) and is indented. • The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None.
  • 5.
    Syntax: def functionname( parameters): "function_docstring“ function_suite [expression] return Example Def add(a,b): sum=a+b return sum a=int(input(“enter first number”)) b=int(input(“enter second number”)) res=add(a,b) print(“result = “res)
  • 6.
    Function Arguments: A functionby using the following types of formal arguments:: • Required arguments • Keyword arguments • Default arguments • Variable-length arguments Required arguments: Required arguments are the arguments passed to a function in correct positional order. def printme( name, age): print ("Name: ", name) print ("Age ", age) return; printme(name=“Ramu”, age=29); This would produce following result: Name: Ramu Age 29
  • 7.
    Keyword arguments: • Keywordarguments are related to the function calls. When you use keyword arguments in a function call, the caller identifies the arguments by the parameter name. • This allows you to skip arguments or place them out of order because the Python interpreter is able to use the keywords provided to match the values with parameters.
  • 8.
    Following example givesmore clear picture. Note, here order of the parameter does not matter: def printinfo( name, age ): "Test function" print ("Name: ", name) print ("Age ", age) return printinfo(age=50, name="miki" ) This would produce following result: Name: miki Age 50
  • 9.
    Default arguments: A defaultargument is an argument that assumes a default value if a value is not provided in the function call for that argument. Following example gives idea on default arguments, it would print default age if it is not passed: def printinfo( name, age = 35 ): “Test function" print ("Name: ", name) print ("Age ", age) return printinfo( age=50, name="miki" ) printinfo( name="miki" ) This would produce following result: Name: miki Age 50 Name: miki Age 35
  • 10.
    Variable-length arguments: You mayneed to process a function for more arguments than you specified while defining the function. These arguments are called variable-length arguments and are not named in the function definition, unlike required and default arguments. The general syntax for a function with non-keyword variable arguments is this: def functionname([formal_args,] *var_args_tuple ): "function_docstring" function_suite return [expression]
  • 11.
    An asterisk (*)is placed before the variable name that will hold the values of all nonkeyword variable arguments. This tuple remains empty if no additional arguments are specified during the function call. For example: def printinfo( arg1, *vartuple ): "This is test" print ("Output is: “) print (arg1) for var in vartuple: print var return printinfo( 10 ) printinfo( 70, 60, 50 ) This would produce following result: Output is: 10 Output is: 70 60 50
  • 12.
    Lambda Function Lambda functionsare also called anonymous functions. An anonymous function is a function defined without a name. As we know to define a normal function in python, we need to use the def keyword. But in this case of anonymous functions, we use the lambda keyword to define the functions.
  • 13.
    The characteristics oflambda function • The lambda function can take many arguments but can return only one expression. • Syntactically, lambda functions are restricted to only a single expression. • We can use them as an anonymous function inside other functions. • Lambda function is reusable.
  • 14.
    Why should weuse lambda functions? Lambda functions are used when we need a function for a short period of time. This is commonly used when we want to pass a function as an argument to higher-order functions, that is, functions that take other functions as their arguments
  • 15.
    Why should weuse lambda functions?
  • 16.
  • 17.
    17 Fruitful Functions Properties ofFruitful functions are 1. Return Value 2. Incremental Development 3. Composition 4. Boolean type
  • 18.
    1.Return Value def sum() a=10 b=15 c=a+b print(c) Sum() defsum(a,b) c=a+b return c Print(sum(10,15))
  • 19.
    def area(radius): temp =3.14159 * radius**2 return temp def area(radius): return 3.14159 * radius**2 Sometimes it is useful to have multiple return statements, one in each branch of a conditional. def absolute_value(x): if x < 0: return -x else: return x
  • 20.
    2.Incremental development To dealwith increasingly complex programs, we are going to suggest a technique called incremental development. The goal of incremental development is to avoid long debugging sessions by adding and testing only a small amount of code at a time. As an example, suppose you want to find the distance between two points, given by the coordinates (x1, y1) and (x2, y2). By the Pythagorean theorem, the distance is:
  • 21.
    def distance(x1, y1,x2, y2): """Return the distance between points (x1, y1) and (x2, y2) as a float""" return 0.0
  • 22.
    def distance(x1, y1,x2, y2): """Return the distance between points (x1, y1) and (x2, y2) as a float""" dx = x2 - x1 dy = y2 - y1 print 'dx is ', dx print 'dy is ', dy return 0.0
  • 23.
    def distance(x1, y1,x2, y2): """Return the distance between points (x1, y1) and (x2, y2) as a float""" dx, dy = x2 - x1, y2 - y1 result =(dx**2 + dy**2)**0.5 return result
  • 24.
    def distance(x1, y1,x2, y2): """Return the distance between points (x1, y1) and (x2, y2) as a float""" result =((x2-x1)**2 + (y2-y1)**2)**0.5 return result
  • 25.
    def distance(x1, y1,x2, y2): """Return the distance between points (x1, y1) and (x2, y2) as a float""" return((x2-x1)**2 + (y2-y1)**2)**0.5
  • 26.
    The key aspectsof the process are: 1. Start with a working program and make small incremental changes. At any point, if there is an error, you will know exactly where it is. 2. Use temporary variables to hold intermediate values so you can output and check them. 3. Once the program is working, you might want to remove some of the scaffolding or consolidate multiple statements into compound expressions, but only if it does not make the program difficult to read.
  • 27.
    3.Composition As you shouldexpect by now, you can call one function from within another. This ability is called composition. def area2(xc, yc, xp, yp): radius = distance(xc, yc, xp, yp) result = area(radius) return result def area2(xc, yc, xp, yp): return area(distance(xc, yc, xp, yp))
  • 28.
    4.Creating Boolean functions Functionsthat return a Boolean value (True or False) can be used in conditional statements (i.e. if… else…) 05/02/09 Python Mini-Course: Day 2 - Lesson 8 28
  • 29.
    is_divisible function def is_divisible(x,y): if x % y == 0: return True else: return False is_divisible(16,4) is_divisible(16,3) 05/02/09 Python Mini-Course: Day 2 - Lesson 8 29
  • 30.
    Scope of Variables: Allvariables in a program may not be accessible at all locations in that program. This depends on where you have declared a variable. The scope of a variable determines the portion of the program where you can access a particular identifier. There are two basic scopes of variables in Python: Global variables Local variables Global vs. Local variables: Variables that are defined inside a function body have a local scope, and those defined outside have a global scope. This means that local variables can be accessed only inside the function in which they are declared whereas global variables can be accessed throughout the program body by all functions. When you call a function, the variables declared inside it are brought into scope.
  • 31.
    Example: total = 0;# This is global variable. def sum( arg1, arg2 ): "Add both the parameters" total = arg1 + arg2; print "Inside the function local total : ", total return total; # Now you can call sum function sum( 10, 20 ); print "Outside the function global total : ", total This would produce following result: Inside the function local total : 30 Outside the function global total : 0
  • 32.
    There is onemore example where argument is being passed by reference but inside the function, but the reference is being over-written. def changeme( mylist ): "This changes a passed list" mylist = [1,2,3,4]; print("Values inside the function: ", mylist) return mylist = [10,20,30]; changeme( mylist ); Print("Values outside the function: ", mylist) The parameter mylist is local to the function changeme. Changing mylist within the function does not affect mylist. The function accomplishes nothing and finally this would produce following result: Values inside the function: [1, 2, 3, 4] Values outside the function: [10, 20, 30]
  • 33.
    Pass by referencevs value All parameters (arguments) in the Python language are passed by reference. It means if you change what a parameter refers to within a function, the change also reflects back in the calling function. For example: def changeme( mylist ): "This changes a passed list“ mylist.append([1,2,3,4]); print ("Values inside the function: ", mylist) return mylist = [10,20,30]; changeme( mylist ); print ("Values outside the function: ", mylist) So this would produce following result: Values inside the function: [10, 20, 30, [1, 2, 3, 4]] Values outside the function: [10, 20, 30, [1, 2, 3, 4]]
  • 34.