SlideShare a Scribd company logo
Python functions
 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.
 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
 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.
 We will now concentrate on the basic mechanics of functions
and how they can be employed within a single python module
file.
Function Definition and Execution
 The general format for creating a new function is as
follows:
 def NAME(ARG1 [,…]):
 STATEMENT BLOCK
 [return VALUE]
 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
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
 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
 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”
Scoping
 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
 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
 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.
 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
 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.
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
 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
 name = ‘unknown’
 def set_defaults ( ):
 global name
 name= ‘Martin’
 Set_defaults( )
 print name
 This function does what you expect; it prints the name ‘Martin’
 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
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.
 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)
 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
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
Example
 def funca ( ):
 value = 59
 funcb ( )
 def funcb ( ):
 print (value*2)
 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)
 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
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.
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!’)
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
 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
 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
 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
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
 This code generates the following output when executed:
 Before: [1,2,3]
 Inside: [4,5,6]
 After: [4,5,6]
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
 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]
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
 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++
 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)
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
 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
 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
 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
 The lambda function is used in a large number of areas such as sorting and as
inline functions when creating user interfaces
Ad

Recommended

UNIT 3 python.pptx
UNIT 3 python.pptx
TKSanthoshRao
 
Functions2.pdf
Functions2.pdf
prasnt1
 
3-Python Functions.pdf in simple.........
3-Python Functions.pdf in simple.........
mxdsnaps
 
functions- best.pdf
functions- best.pdf
MikialeTesfamariam
 
Python Functions.pptx
Python Functions.pptx
AnuragBharti27
 
cbse class 12 Python Functions2 for class 12 .pptx
cbse class 12 Python Functions2 for class 12 .pptx
tcsonline1222
 
functions modules and exceptions handlings.ppt
functions modules and exceptions handlings.ppt
Rajasekhar364622
 
Function
Function
GauravGautam224100
 
2 Functions2.pptx
2 Functions2.pptx
RohitYadav830391
 
CHAPTER 01 FUNCTION in python class 12th.pptx
CHAPTER 01 FUNCTION in python class 12th.pptx
PreeTVithule1
 
CLASS-11 & 12 ICT PPT Functions in Python.pptx
CLASS-11 & 12 ICT PPT Functions in Python.pptx
seccoordpal
 
Functions_in_Python.pptx
Functions_in_Python.pptx
krushnaraj1
 
Powerpoint presentation for Python Functions
Powerpoint presentation for Python Functions
BalaSubramanian376976
 
Functions_in_Python.pdf text CBSE class 12
Functions_in_Python.pdf text CBSE class 12
JAYASURYANSHUPEDDAPA
 
Functions and Modules.pptx
Functions and Modules.pptx
Ashwini Raut
 
JNTUK python programming python unit 3.pptx
JNTUK python programming python unit 3.pptx
Venkateswara Babu Ravipati
 
python slides introduction interrupt.ppt
python slides introduction interrupt.ppt
Vinod Deenathayalan
 
Python programming variables and comment
Python programming variables and comment
MalligaarjunanN
 
functions notes.pdf python functions and opp
functions notes.pdf python functions and opp
KirtiGarg71
 
Learn more about the concepts Functions of Python
Learn more about the concepts Functions of Python
PrathamKandari
 
Functions in python
Functions in python
colorsof
 
Python functions
Python functions
Prof. Dr. K. Adisesha
 
FUNCTIONS.pptx
FUNCTIONS.pptx
KalashJain27
 
Python_Functions_Unit1.pptx
Python_Functions_Unit1.pptx
Koteswari Kasireddy
 
Functions_new.pptx
Functions_new.pptx
Yagna15
 
Py-Slides-3 difficultpythoncoursefforbeginners.ppt
Py-Slides-3 difficultpythoncoursefforbeginners.ppt
mohamedsamydeveloper
 
FUNCTIONINPYTHON.pptx
FUNCTIONINPYTHON.pptx
SheetalMavi2
 
Chapter - 4.pptx
Chapter - 4.pptx
MikialeTesfamariam
 
Advanced Token Development - Decentralized Innovation
Advanced Token Development - Decentralized Innovation
arohisinghas720
 
Step by step guide to install Flutter and Dart
Step by step guide to install Flutter and Dart
S Pranav (Deepu)
 

More Related Content

Similar to Functions in Python Syntax and working . (20)

2 Functions2.pptx
2 Functions2.pptx
RohitYadav830391
 
CHAPTER 01 FUNCTION in python class 12th.pptx
CHAPTER 01 FUNCTION in python class 12th.pptx
PreeTVithule1
 
CLASS-11 & 12 ICT PPT Functions in Python.pptx
CLASS-11 & 12 ICT PPT Functions in Python.pptx
seccoordpal
 
Functions_in_Python.pptx
Functions_in_Python.pptx
krushnaraj1
 
Powerpoint presentation for Python Functions
Powerpoint presentation for Python Functions
BalaSubramanian376976
 
Functions_in_Python.pdf text CBSE class 12
Functions_in_Python.pdf text CBSE class 12
JAYASURYANSHUPEDDAPA
 
Functions and Modules.pptx
Functions and Modules.pptx
Ashwini Raut
 
JNTUK python programming python unit 3.pptx
JNTUK python programming python unit 3.pptx
Venkateswara Babu Ravipati
 
python slides introduction interrupt.ppt
python slides introduction interrupt.ppt
Vinod Deenathayalan
 
Python programming variables and comment
Python programming variables and comment
MalligaarjunanN
 
functions notes.pdf python functions and opp
functions notes.pdf python functions and opp
KirtiGarg71
 
Learn more about the concepts Functions of Python
Learn more about the concepts Functions of Python
PrathamKandari
 
Functions in python
Functions in python
colorsof
 
Python functions
Python functions
Prof. Dr. K. Adisesha
 
FUNCTIONS.pptx
FUNCTIONS.pptx
KalashJain27
 
Python_Functions_Unit1.pptx
Python_Functions_Unit1.pptx
Koteswari Kasireddy
 
Functions_new.pptx
Functions_new.pptx
Yagna15
 
Py-Slides-3 difficultpythoncoursefforbeginners.ppt
Py-Slides-3 difficultpythoncoursefforbeginners.ppt
mohamedsamydeveloper
 
FUNCTIONINPYTHON.pptx
FUNCTIONINPYTHON.pptx
SheetalMavi2
 
Chapter - 4.pptx
Chapter - 4.pptx
MikialeTesfamariam
 
CHAPTER 01 FUNCTION in python class 12th.pptx
CHAPTER 01 FUNCTION in python class 12th.pptx
PreeTVithule1
 
CLASS-11 & 12 ICT PPT Functions in Python.pptx
CLASS-11 & 12 ICT PPT Functions in Python.pptx
seccoordpal
 
Functions_in_Python.pptx
Functions_in_Python.pptx
krushnaraj1
 
Powerpoint presentation for Python Functions
Powerpoint presentation for Python Functions
BalaSubramanian376976
 
Functions_in_Python.pdf text CBSE class 12
Functions_in_Python.pdf text CBSE class 12
JAYASURYANSHUPEDDAPA
 
Functions and Modules.pptx
Functions and Modules.pptx
Ashwini Raut
 
python slides introduction interrupt.ppt
python slides introduction interrupt.ppt
Vinod Deenathayalan
 
Python programming variables and comment
Python programming variables and comment
MalligaarjunanN
 
functions notes.pdf python functions and opp
functions notes.pdf python functions and opp
KirtiGarg71
 
Learn more about the concepts Functions of Python
Learn more about the concepts Functions of Python
PrathamKandari
 
Functions in python
Functions in python
colorsof
 
Functions_new.pptx
Functions_new.pptx
Yagna15
 
Py-Slides-3 difficultpythoncoursefforbeginners.ppt
Py-Slides-3 difficultpythoncoursefforbeginners.ppt
mohamedsamydeveloper
 
FUNCTIONINPYTHON.pptx
FUNCTIONINPYTHON.pptx
SheetalMavi2
 

Recently uploaded (20)

Advanced Token Development - Decentralized Innovation
Advanced Token Development - Decentralized Innovation
arohisinghas720
 
Step by step guide to install Flutter and Dart
Step by step guide to install Flutter and Dart
S Pranav (Deepu)
 
Software Testing & it’s types (DevOps)
Software Testing & it’s types (DevOps)
S Pranav (Deepu)
 
FME as an Orchestration Tool - Peak of Data & AI 2025
FME as an Orchestration Tool - Peak of Data & AI 2025
Safe Software
 
DevOps for AI: running LLMs in production with Kubernetes and KubeFlow
DevOps for AI: running LLMs in production with Kubernetes and KubeFlow
Aarno Aukia
 
Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...
Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...
Natan Silnitsky
 
Artificial Intelligence Workloads and Data Center Management
Artificial Intelligence Workloads and Data Center Management
SandeepKS52
 
OpenTelemetry 101 Cloud Native Barcelona
OpenTelemetry 101 Cloud Native Barcelona
Imma Valls Bernaus
 
Who will create the languages of the future?
Who will create the languages of the future?
Jordi Cabot
 
Shell Skill Tree - LabEx Certification (LabEx)
Shell Skill Tree - LabEx Certification (LabEx)
VICTOR MAESTRE RAMIREZ
 
Porting Qt 5 QML Modules to Qt 6 Webinar
Porting Qt 5 QML Modules to Qt 6 Webinar
ICS
 
GDG Douglas - Google AI Agents: Your Next Intern?
GDG Douglas - Google AI Agents: Your Next Intern?
felipeceotto
 
Download Adobe Illustrator Crack free for Windows 2025?
Download Adobe Illustrator Crack free for Windows 2025?
grete1122g
 
Milwaukee Marketo User Group June 2025 - Optimize and Enhance Efficiency - Sm...
Milwaukee Marketo User Group June 2025 - Optimize and Enhance Efficiency - Sm...
BradBedford3
 
About Certivo | Intelligent Compliance Solutions for Global Regulatory Needs
About Certivo | Intelligent Compliance Solutions for Global Regulatory Needs
certivoai
 
dp-700 exam questions sample docume .pdf
dp-700 exam questions sample docume .pdf
pravkumarbiz
 
On-Device AI: Is It Time to Go All-In, or Do We Still Need the Cloud?
On-Device AI: Is It Time to Go All-In, or Do We Still Need the Cloud?
Hassan Abid
 
Decipher SEO Solutions for your startup needs.
Decipher SEO Solutions for your startup needs.
mathai2
 
What is data visualization and how data visualization tool can help.pptx
What is data visualization and how data visualization tool can help.pptx
Varsha Nayak
 
Code and No-Code Journeys: The Coverage Overlook
Code and No-Code Journeys: The Coverage Overlook
Applitools
 
Advanced Token Development - Decentralized Innovation
Advanced Token Development - Decentralized Innovation
arohisinghas720
 
Step by step guide to install Flutter and Dart
Step by step guide to install Flutter and Dart
S Pranav (Deepu)
 
Software Testing & it’s types (DevOps)
Software Testing & it’s types (DevOps)
S Pranav (Deepu)
 
FME as an Orchestration Tool - Peak of Data & AI 2025
FME as an Orchestration Tool - Peak of Data & AI 2025
Safe Software
 
DevOps for AI: running LLMs in production with Kubernetes and KubeFlow
DevOps for AI: running LLMs in production with Kubernetes and KubeFlow
Aarno Aukia
 
Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...
Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...
Natan Silnitsky
 
Artificial Intelligence Workloads and Data Center Management
Artificial Intelligence Workloads and Data Center Management
SandeepKS52
 
OpenTelemetry 101 Cloud Native Barcelona
OpenTelemetry 101 Cloud Native Barcelona
Imma Valls Bernaus
 
Who will create the languages of the future?
Who will create the languages of the future?
Jordi Cabot
 
Shell Skill Tree - LabEx Certification (LabEx)
Shell Skill Tree - LabEx Certification (LabEx)
VICTOR MAESTRE RAMIREZ
 
Porting Qt 5 QML Modules to Qt 6 Webinar
Porting Qt 5 QML Modules to Qt 6 Webinar
ICS
 
GDG Douglas - Google AI Agents: Your Next Intern?
GDG Douglas - Google AI Agents: Your Next Intern?
felipeceotto
 
Download Adobe Illustrator Crack free for Windows 2025?
Download Adobe Illustrator Crack free for Windows 2025?
grete1122g
 
Milwaukee Marketo User Group June 2025 - Optimize and Enhance Efficiency - Sm...
Milwaukee Marketo User Group June 2025 - Optimize and Enhance Efficiency - Sm...
BradBedford3
 
About Certivo | Intelligent Compliance Solutions for Global Regulatory Needs
About Certivo | Intelligent Compliance Solutions for Global Regulatory Needs
certivoai
 
dp-700 exam questions sample docume .pdf
dp-700 exam questions sample docume .pdf
pravkumarbiz
 
On-Device AI: Is It Time to Go All-In, or Do We Still Need the Cloud?
On-Device AI: Is It Time to Go All-In, or Do We Still Need the Cloud?
Hassan Abid
 
Decipher SEO Solutions for your startup needs.
Decipher SEO Solutions for your startup needs.
mathai2
 
What is data visualization and how data visualization tool can help.pptx
What is data visualization and how data visualization tool can help.pptx
Varsha Nayak
 
Code and No-Code Journeys: The Coverage Overlook
Code and No-Code Journeys: The Coverage Overlook
Applitools
 
Ad

Functions in Python Syntax and working .

  • 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 = ‘[email protected]’  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
  • 25. Example  def funca ( ):  value = 59  funcb ( )  def funcb ( ):  print (value*2)
  • 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