2. One of the fundamentals of any programming language is that there are often
repeated elements in your program.
You can cut and paste code from one section to another, but this is messy
What happens when you need to update that particular part of the program?
You would have to modify each duplicated section individually
For very small programs this is unlikely to generate any significant overhead.
But as the size and complexity of the program increases , so does the time
required to modify and update essentially the same piece of code over and over.
3. Duplication also runs the risk of introducing additional syntactic, logical and
typographical errors
Imagine duplicating a sequence that contained a simple typing mistake-You
would have to trace every single instance to isolate the problem
This is where functions solve your problems.
By placing the repeated code into a function, you isolate that code sequence and
provide easier access to improve the code or isolate bugs
4. Python provides one of the best systems for code reuse
Once you have written a python function, it is
immediately available to any other program just by
importing the functions from the source file
There is no need to create a special library and header
file as you need to in C/C++, nor do you need to create a
special “module” as you do in Perl.
With Python code reuse is as simple as knowing which
file the function is stored in.
5. We will now concentrate on the basic mechanics of functions
and how they can be employed within a single python module
file.
6. Function Definition and Execution
The general format for creating a new function is as
follows:
def NAME(ARG1 [,…]):
STATEMENT BLOCK
[return VALUE]
7. The NAME should follow the same rules as object names
1. Functions must begin with an underscore or letter
letter and may contain any combination of letters,
digits or underscores. You cannot use any other
punctuation characters
2. Functions are case sensitive- combine and
Combine are two different function names.
However, you should avoid creating functions of
the same name but different cases
You cannot use a reserved word for a function
name
8. When you define the function , you
must use parentheses, even if you are
not accepting any arguments to the
function
If you are accepting arguments to the
function, the arguments must be
named within the parentheses
9. As with control statements, the statement block for the function
must be preceded by a colon
The closing return statement is optional; if you don’t use it, the
function returns to the caller without returning a value
A python function without a return statement always returns the
special value None
def area (radius):
area = 3.14 * (pow(radius,2))
return area
10. Unlike any other languages, functions within python can be defined
On the fly- you can create a function anywhere within the normal execution of
a program
If (message):
def function ( ):
print “Hellon”;
else:
def function( ):
print “Goodbye!n”
12. Python uses the concept of namespaces in order to store
information about objects and their locations within an
application
Namespaces are specific to a particular level of
abstraction-there are individual namespaces for
functions and modules
And there is a special namespace for the built –in
functions, statements and objects
13. When you access an object or function, Python
searches the namespace tables looking for the
specified name so that it can look up the
reference and decide what to do with the
information stored at that location
14. Scoping within Python follows these basic rules:
1. Each module has its own scope. This means that
multiple modules have their own scope, and therefore
their own namespaces
2. The enclosing module for a function is called global
scope. This is the location of objects created at the top
level of a module file
3.New function definitions create new scope ; the scopes
are unique to the function
4. New objects are assigned to the local scope unless
declared otherwise.
15. Any variable or function that is defined will be a member
of the local scope , unless you declare it global with the
global keyword
5. Arguments to a function are defined within the local
function scope
16. The scoping rules means that objects created within a
function do not interfere with identically named objects
in the module (global) or built in namespaces.
17. Making Objects Global
There are occasions when you want to assign the value of a variable within
a function, but you have to modify the global variable instead of creating a
new one
The traditional method for this is to predeclare the variable before the
function is called
name = ‘unknown’
def set_defaults( ):
name = ‘Martin’
Set-defaults( )
Print name
18. However, in python this doesn’t work, because the moment you assign the
name variable within the function, python creates a new variable within the
local scope
To get around this , you need to use the global keyword to define which
variable you want to use in this way
The global keyword tells python to create a local alias to the global
variable
19. name = ‘unknown’
def set_defaults ( ):
global name
name= ‘Martin’
Set_defaults( )
print name
This function does what you expect; it prints the name ‘Martin’
20. The global keyword also create objects within the global namespace if they
don’t already exist, as in the following example
def set-defaults( ):
global name, address
Name = ‘Martin’
Address = ‘mc@mcwords.com’
set_defaults( )
Print “Name:”,name,”Address:”,address
21. The LGB Rule
The LGB rule is a simple way for remembering how python looks up names
within the scope of
Name references search the three scopes in order: local, then global, the
built –in (LGB)
Name assignments create new objects or update objects in the local
scope. Thus if you want to assign to global objects within a local scope,
you must use the global keyword
Global declarations map assigned names to the scope of the enclosing
module.
22. Import objects from the imported modules or use the fully qualified module/object name
radius = 2
pi = 3.141592654
def area(radius):
area = pi * (pow(radius,2))
Return area
Print area(4)
23. In this example , we have defined two global variables, radius and pi
The area function looks for the name radius when it is executed, and finds it
locally, ignoring the global variable
The pi variable cannot be found locally , so python looks globally and finds the
variable there
24. Scope traps
There is one significant trap that catches many people offguard
The name resolving process only searches the three abstraction layers- local,
global and built-in
It is possible in python to define functions within other functions
This can often be useful when you want to create a group of functions that are
not publicly available to the outside world. The problem is that the scoping
rules still apply
26. The preceding code will fail because funcb is trying to access the variable
value.
However, value does not exist within either the local, global or built-in scope – and it fails the LGB
rule
Functions do not automatically inherit the scope of the parent, nor does the python namespace
manager search the parent scope of a function.
The way to get around this problem is to make value an argument to the embedded function
def funca ( ):
value = 59
funcb ( )
def funcb(value ):
print ( value*2)
27. We can use the same name because value will still be local to
the funcb scope and so it works well with the LGB rule
28. Function parameters
Let us clarify some terminology associated with passing data into functions
This terminology relates to the parameters defined as part of the function
header and the data passed into the function via these parameters
A parameter is a variable defined as part of the function header and is used to make
data available within the function itself.
An argument is the actual value or data passed into the function when it is called.
The data will be held within the parameters.
29. Arguments
The arguments specified in a function definition are taken in the order in
which they are defined, for example
def message (to, text):
print “ This is message for”, to, “:n’, text
message (‘Martin’, ‘Your Dinner is ready!’)
30. Rules for Argument Passing
Arguments are copied by reference into locally scoped objects. This means
that the variables used to access function arguments are not related to the
objects supplied to the function. This also means that changing a local
object does not modify the original arguments
Mutable objects can be changed in place. When you copy a list or
dictionary, you copy a list of object references. If you change the value of a
reference, you modify the original argument
31. The first rule means that you can safely use the local versions of an object
without worrying about modifying the original
def modifier (number, string, list):
number = 5
string = ‘Goodbye’
List = [4,5,6]
print”Inside:”, number,string,list
number = 1
String = “Hello”
List = [1,2,3]
Print “Before:”, number, string, list
Modifier (number,string,list)
Print”After:”, number,string,list
32. Generates the following output
Before: 1 Hello [1,2,3]
Inside: 5 Goodbye [4,5,6]
After: 1 Hello [1,2,3]
The local versions of number, string and list have been modified, but the
original versions still retain their original values
33. The second rule says that any mutable object can
be modified in place. This allows us to change the
information pointed to by a specific element of a
mutable list or dictionary
34. Example
def modifier (list):
list[0:3] = [4,5,6]
Print “inside:”, list
list = [1,2,3]
print “Before:”, list
Modifier(list)
print ”After:”, list
35. This code generates the following output when executed:
Before: [1,2,3]
Inside: [4,5,6]
After: [4,5,6]
36. Arguments are objects
Arguments are just names for objects- the underlying type of the object in
question remains the same
For example
def multiply (x,y):
return x*y
When run on numerical objects, returns a number
Multiply (2,3)
6
37. When run on a string
multiply (‘Ha’, 5)
HaHaHaHaHa
Or it could return a list
Multiply ([1,2,3],5)
[1,2,3,1,2,3,1,2,3,1,2,3,1,2,3]
38. Argument Calling by keywords
Beyond the normal sequence of argument calling, where each argument is
assigned in order to the functions argument definition
Python also supports a number of other function argument calling
formats
The problem with the traditional sequence assignment is that it is limited
to accepting a specific number of arguments in a specific sequence
39. For readability , this technique is not always practical,
and it is useful
To have some flexibilitywhen supplying information to
a function if it can be made to do a number of different
things other than the traditional single purpose
function supported in C/C++
40. The most basic extension beyond sequence assignment is the ability to
specify arguments by keyword assignment
For Example
multiply(x=5,y=10)
Or
multiply (y=10, x=5)
41. Anonymous Functions
Anonymous functions are a vital component of the flexibility offered by
Python
In C/C++, the closest approximation to an anonymous function is the
inline function
You can define a block or expression to be executed just as if it was a real
function call, but without the overhead associated with predeclaring a
typical function
42. The format for creating an anonymous function in Python is to use the
lambda expression
The general format for the lambda expression is
Lambda ARG [ , ARG,….]: EXPR
43. The lambda expression returns a function object without giving it a name
The returned object can then be used just like an indirect function call
The EXPR is a single-line expression that is executed when the function is called
44. When creating and using lambda functions, you need to remember the
following important differences from ordinary functions
Functions created by lambda only accept a single expression – you cannot
have multiline anonymous functions
The result of the lambda function is always returned to the caller
For example you can use the lambda to create an anonymous function that
cubes a number and then assigns the result to a name:
f = lambda x: x*x*x
f(2)
The preceding statement is how a typical def statement works; the difference
is that the assignments to a name is automatic
45. The lambda function is used in a large number of areas such as sorting and as
inline functions when creating user interfaces