SlideShare a Scribd company logo
1 of 45
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

More Related Content

Similar to Functions in Python Syntax and working .

04. WORKING WITH FUNCTIONS-2 (1).pptx
04. WORKING WITH FUNCTIONS-2 (1).pptx04. WORKING WITH FUNCTIONS-2 (1).pptx
04. WORKING WITH FUNCTIONS-2 (1).pptxManas40552
 
Functions and Modules.pptx
Functions and Modules.pptxFunctions and Modules.pptx
Functions and Modules.pptxAshwini Raut
 
Python programming variables and comment
Python programming variables and commentPython programming variables and comment
Python programming variables and commentMalligaarjunanN
 
Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdfprasnt1
 
PE1 Module 4.ppt
PE1 Module 4.pptPE1 Module 4.ppt
PE1 Module 4.pptbalewayalew
 
C, C++ Interview Questions Part - 1
C, C++ Interview Questions Part - 1C, C++ Interview Questions Part - 1
C, C++ Interview Questions Part - 1ReKruiTIn.com
 
Introduction to c programming
Introduction to c programmingIntroduction to c programming
Introduction to c programmingAMAN ANAND
 
Python programming - Functions and list and tuples
Python programming - Functions and list and tuplesPython programming - Functions and list and tuples
Python programming - Functions and list and tuplesMalligaarjunanN
 
pythontraining-201jn026043638.pptx
pythontraining-201jn026043638.pptxpythontraining-201jn026043638.pptx
pythontraining-201jn026043638.pptxRohitKumar639388
 
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...Maulik Borsaniya
 
Arrays & functions in php
Arrays & functions in phpArrays & functions in php
Arrays & functions in phpAshish Chamoli
 

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

04. WORKING WITH FUNCTIONS-2 (1).pptx
04. WORKING WITH FUNCTIONS-2 (1).pptx04. WORKING WITH FUNCTIONS-2 (1).pptx
04. WORKING WITH FUNCTIONS-2 (1).pptx
 
Functions and Modules.pptx
Functions and Modules.pptxFunctions and Modules.pptx
Functions and Modules.pptx
 
functions.pptx
functions.pptxfunctions.pptx
functions.pptx
 
Php, mysq lpart3
Php, mysq lpart3Php, mysq lpart3
Php, mysq lpart3
 
Python programming variables and comment
Python programming variables and commentPython programming variables and comment
Python programming variables and comment
 
Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdf
 
Python Functions.pptx
Python Functions.pptxPython Functions.pptx
Python Functions.pptx
 
Python Functions.pptx
Python Functions.pptxPython Functions.pptx
Python Functions.pptx
 
PE1 Module 4.ppt
PE1 Module 4.pptPE1 Module 4.ppt
PE1 Module 4.ppt
 
Chapter 05 classes and objects
Chapter 05 classes and objectsChapter 05 classes and objects
Chapter 05 classes and objects
 
C, C++ Interview Questions Part - 1
C, C++ Interview Questions Part - 1C, C++ Interview Questions Part - 1
C, C++ Interview Questions Part - 1
 
Introduction to c programming
Introduction to c programmingIntroduction to c programming
Introduction to c programming
 
Advance python
Advance pythonAdvance python
Advance python
 
Chapter - 4.pptx
Chapter - 4.pptxChapter - 4.pptx
Chapter - 4.pptx
 
Python programming - Functions and list and tuples
Python programming - Functions and list and tuplesPython programming - Functions and list and tuples
Python programming - Functions and list and tuples
 
pythontraining-201jn026043638.pptx
pythontraining-201jn026043638.pptxpythontraining-201jn026043638.pptx
pythontraining-201jn026043638.pptx
 
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
 
Arrays & functions in php
Arrays & functions in phpArrays & functions in php
Arrays & functions in php
 
Technical Interview
Technical InterviewTechnical Interview
Technical Interview
 
My c++
My c++My c++
My c++
 

Recently uploaded

chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningVitsRangannavar
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 

Recently uploaded (20)

chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learning
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 

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 = ‘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
  • 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