SlideShare a Scribd company logo
Function in Python
def function_name( parameters ):
‘’’function_docstring’’’
function_suite
return [expression]
def my_func():
x = 10
print("Value inside function:",x)
x = 20
my_func()
print("Value outside function:",x)
Value inside function: 10
Value outside function: 20
Pass by Reference vs Value
def changeme( mylist1 ):
"This changes a passed list into this function"
print ("before change: ", mylist1)
mylist1[2]=50
print ("after change: ", mylist1)
return
# Now you can call changeme function
mylist = [10,20,30]
changeme( mylist )
print ("Values outside the function: ", mylist)
• Here, we are maintaining reference of the passed object and appending values in
the same object.
• Therefore, this would produce the following result-
• before change: [10, 20, 30]
• after change: [10, 20, 50]
• Values outside the function: [10, 20, 50]
def changeme( mylist1 ):
"This changes a passed list into this function"
mylist1 = [1,2,3,4] # This would assign new reference in mylist
print ("Values inside the function: ", mylist1)
return
# Now you can call changeme function
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 the following
result-
Values inside the function: [1, 2, 3, 4]
Values outside the function: [10, 20, 30]
Function Arguments
• You can call a function by using the following types of formal
arguments-
• Required arguments
• Keyword arguments
• Default arguments
• Variable-length arguments
Required Arguments
• the arguments passed to a function in correct positional order.
• the number of arguments in the function call should match exactly with the
function definition.
# Function definition is here
def printme( str ):
"This prints a passed string into this function"
print (str)
return
# Now you can call printme function
printme(‘hello’)
Output: hello
Keyword Arguments
• related to the function calls.
• 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.
def printme( strn ):
"This prints a passed string into this function"
print (strn)
return
# Now you can call printme function
printme( strn = "My string")
# Function definition is here
def printinfo( name, age ):
"This prints a passed info into this function"
print ("Name: ", name)
print ("Age ", age)
return
# Now you can call printinfo function
printinfo( age=50, name="miki" )
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.
def printinfo( name, age = 35 ):
print ("Name: ", name)
print ("Age ", age)
# Now you can call printinfo function
printinfo( age=50, name="miki" )
printinfo( name="miki" )
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.
def function_name([formal_args,] *var_args_tuple ):
function_stmt
return [expression]
• An asterisk (*) is placed before the variable name that holds the
values of all non keyword variable arguments.
• This tuple remains empty if no additional arguments are specified
during the function call.
printinfo( 10 )
printinfo( 70, 60, 50 )
Output is:
10
Output is:
70
60
50
# Function definition is here
def printinfo( arg1, *vartuple ):
print ("Output is: ")
print (arg1)
for var in vartuple:
print (var)
The Anonymous Functions
• These functions are called anonymous because they are not declared in the
standard manner by using the def keyword.
• You can use the lambda keyword to create small anonymous functions.
• lambda operator can have any number of arguments, but it can have only one
expression.
• It cannot contain any statements and
• it returns a function object which can be assigned to any variable.
• An anonymous function cannot be a direct call to print because lambda requires
an expression.
• Lambda functions have their own local namespace and cannot access variables
other than those in their parameter list and those in the global namespace.
• Mostly lambda functions are passed as parameters to a function which expects a
function objects as parameter like map, reduce, filter functions
def add(x, y):
return x + y
# Call the function
add(2, 3)
# Output: 5
add = lambda x, y : x + y
print add(2, 3)
# Output: 5
• In lambda x, y: x + y; x and y are arguments to the function and x +
y is the expression which gets executed and its values is returned as
output.
• lambda x, y: x + y returns a function object which can be assigned to
any variable, in this case function object is assigned to
the add variable.
>>>type (add) # Output: function
• The syntax of lambda function contains only a single statement, which is as
follows-
lambda [arg1 [,arg2,.....argn]]:expression
# Function definition is here
>>>sum = lambda arg1, arg2: arg1 + arg2
# Now you can call sum as a function
>>>print ("Value of total : ", sum( 10, 20 ))
>>>print ("Value of total : ", sum( 20, 20 ))
Use of Lambda Function
• We use lambda functions when we require a nameless function for a short period
of time.
• In Python, we generally use it as an argument to a higher-order function (a
function that takes in other functions as arguments).
• Lambda functions are used along with built-in functions like filter(), map() etc.
filter()
filter(function, iterable)
• creates a new list from the elements for which the function returns True.
# Program to filter out only the even items from a list
my_list = [1, 5, 4, 6, 8, 11, 3, 12]
new_list = list(filter(lambda x: (x%2 == 0) , my_list))
print(new_list)
Output: [4, 6, 8, 12]
map()
map(function, iterable)
• It applies a function to every item in the iterable.
• We can use map() to on a lambda function with a list:
>>>M = [1,2,3,4,5]
>>>squaredList = list(map(lambda x: x*x, M))
>>>print(squaredList)
Reduce function
reduce(function, iterable)
• applies two arguments cumulatively to the items of iterable, from left to right.
>>>from functools import reduce
>>>list = [1,2,3,4,5]
>>>s = reduce(lambda x, y: x+y, list)
>>>print(s)
• In this case the expression is always true, thus it simply sums up the elements of
the list.
>>>def fahrenheit(T):
return ((float(9)/5)*T + 32)
>>>temp = [36.5, 37, 37.5,39]
>>>F = map(fahrenheit, temp)
>>>print(list(F))
[97.7, 98.600, 99.5, 102.2]
>>>temp = [36.5, 37, 37.5,39]
>>>F=map(lambda T:((float(9)/5)*T +32 ), temp)
>>>list(F)
[97.7, 98.600, 99.5, 102.2]
Global Vs Local variable
>>>total = 0 # This is global variable.
>>>def sum( arg1, arg2 ):
total = arg1 + arg2; # Here total is local variable.
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 )
• Inside the function local total : 30
• Outside the function global total : 0
Ad

More Related Content

Similar to Function in Python.pptx by Faculty at gla university in mathura uttar pradesh (20)

Python_Functions_Unit1.pptx
Python_Functions_Unit1.pptxPython_Functions_Unit1.pptx
Python_Functions_Unit1.pptx
Koteswari Kasireddy
 
Python Functions.pptx
Python Functions.pptxPython Functions.pptx
Python Functions.pptx
AnuragBharti27
 
Python Functions.pptx
Python Functions.pptxPython Functions.pptx
Python Functions.pptx
AnuragBharti27
 
python slides introduction interrupt.ppt
python slides introduction interrupt.pptpython slides introduction interrupt.ppt
python slides introduction interrupt.ppt
Vinod Deenathayalan
 
CHAPTER 01 FUNCTION in python class 12th.pptx
CHAPTER 01 FUNCTION in python class 12th.pptxCHAPTER 01 FUNCTION in python class 12th.pptx
CHAPTER 01 FUNCTION in python class 12th.pptx
PreeTVithule1
 
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
MalligaarjunanN
 
Python programming variables and comment
Python programming variables and commentPython programming variables and comment
Python programming variables and comment
MalligaarjunanN
 
ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
prasadmutkule1
 
Chapter Functions for grade 12 computer Science
Chapter Functions for grade 12 computer ScienceChapter Functions for grade 12 computer Science
Chapter Functions for grade 12 computer Science
KrithikaTM
 
Functions2.pptx
Functions2.pptxFunctions2.pptx
Functions2.pptx
AkhilTyagi42
 
Python functions part12
Python functions  part12Python functions  part12
Python functions part12
Vishal Dutt
 
2 Functions2.pptx
2 Functions2.pptx2 Functions2.pptx
2 Functions2.pptx
RohitYadav830391
 
cbse class 12 Python Functions2 for class 12 .pptx
cbse class 12 Python Functions2 for class 12 .pptxcbse class 12 Python Functions2 for class 12 .pptx
cbse class 12 Python Functions2 for class 12 .pptx
tcsonline1222
 
Working with functions.pptx. Hb.
Working with functions.pptx.          Hb.Working with functions.pptx.          Hb.
Working with functions.pptx. Hb.
sabarivelan111007
 
Functions_19_20.pdf
Functions_19_20.pdfFunctions_19_20.pdf
Functions_19_20.pdf
paijitk
 
Functions_21_22.pdf
Functions_21_22.pdfFunctions_21_22.pdf
Functions_21_22.pdf
paijitk
 
Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdf
prasnt1
 
Functions.pdf
Functions.pdfFunctions.pdf
Functions.pdf
kailashGusain3
 
Functionscs12 ppt.pdf
Functionscs12 ppt.pdfFunctionscs12 ppt.pdf
Functionscs12 ppt.pdf
RiteshKumarPradhan1
 
Introduction to Functional Programming
Introduction to Functional ProgrammingIntroduction to Functional Programming
Introduction to Functional Programming
Francesco Bruni
 
python slides introduction interrupt.ppt
python slides introduction interrupt.pptpython slides introduction interrupt.ppt
python slides introduction interrupt.ppt
Vinod Deenathayalan
 
CHAPTER 01 FUNCTION in python class 12th.pptx
CHAPTER 01 FUNCTION in python class 12th.pptxCHAPTER 01 FUNCTION in python class 12th.pptx
CHAPTER 01 FUNCTION in python class 12th.pptx
PreeTVithule1
 
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
MalligaarjunanN
 
Python programming variables and comment
Python programming variables and commentPython programming variables and comment
Python programming variables and comment
MalligaarjunanN
 
ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
prasadmutkule1
 
Chapter Functions for grade 12 computer Science
Chapter Functions for grade 12 computer ScienceChapter Functions for grade 12 computer Science
Chapter Functions for grade 12 computer Science
KrithikaTM
 
Python functions part12
Python functions  part12Python functions  part12
Python functions part12
Vishal Dutt
 
cbse class 12 Python Functions2 for class 12 .pptx
cbse class 12 Python Functions2 for class 12 .pptxcbse class 12 Python Functions2 for class 12 .pptx
cbse class 12 Python Functions2 for class 12 .pptx
tcsonline1222
 
Working with functions.pptx. Hb.
Working with functions.pptx.          Hb.Working with functions.pptx.          Hb.
Working with functions.pptx. Hb.
sabarivelan111007
 
Functions_19_20.pdf
Functions_19_20.pdfFunctions_19_20.pdf
Functions_19_20.pdf
paijitk
 
Functions_21_22.pdf
Functions_21_22.pdfFunctions_21_22.pdf
Functions_21_22.pdf
paijitk
 
Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdf
prasnt1
 
Introduction to Functional Programming
Introduction to Functional ProgrammingIntroduction to Functional Programming
Introduction to Functional Programming
Francesco Bruni
 

Recently uploaded (20)

theory-slides-for react for beginners.pptx
theory-slides-for react for beginners.pptxtheory-slides-for react for beginners.pptx
theory-slides-for react for beginners.pptx
sanchezvanessa7896
 
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
charlesdick1345
 
Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Journal of Soft Computing in Civil Engineering
 
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITYADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ijscai
 
15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...
IJCSES Journal
 
Compiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptxCompiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptx
RushaliDeshmukh2
 
Level 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical SafetyLevel 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical Safety
JoseAlbertoCariasDel
 
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdffive-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
AdityaSharma944496
 
π0.5: a Vision-Language-Action Model with Open-World Generalization
π0.5: a Vision-Language-Action Model with Open-World Generalizationπ0.5: a Vision-Language-Action Model with Open-World Generalization
π0.5: a Vision-Language-Action Model with Open-World Generalization
NABLAS株式会社
 
QA/QC Manager (Quality management Expert)
QA/QC Manager (Quality management Expert)QA/QC Manager (Quality management Expert)
QA/QC Manager (Quality management Expert)
rccbatchplant
 
Avnet Silica's PCIM 2025 Highlights Flyer
Avnet Silica's PCIM 2025 Highlights FlyerAvnet Silica's PCIM 2025 Highlights Flyer
Avnet Silica's PCIM 2025 Highlights Flyer
WillDavies22
 
fluke dealers in bangalore..............
fluke dealers in bangalore..............fluke dealers in bangalore..............
fluke dealers in bangalore..............
Haresh Vaswani
 
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design ThinkingDT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DhruvChotaliya2
 
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptxExplainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
MahaveerVPandit
 
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptxLidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
RishavKumar530754
 
Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...
Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...
Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...
Journal of Soft Computing in Civil Engineering
 
Artificial Intelligence (AI) basics.pptx
Artificial Intelligence (AI) basics.pptxArtificial Intelligence (AI) basics.pptx
Artificial Intelligence (AI) basics.pptx
aditichinar
 
Data Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptxData Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptx
RushaliDeshmukh2
 
Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.
anuragmk56
 
Introduction to FLUID MECHANICS & KINEMATICS
Introduction to FLUID MECHANICS &  KINEMATICSIntroduction to FLUID MECHANICS &  KINEMATICS
Introduction to FLUID MECHANICS & KINEMATICS
narayanaswamygdas
 
theory-slides-for react for beginners.pptx
theory-slides-for react for beginners.pptxtheory-slides-for react for beginners.pptx
theory-slides-for react for beginners.pptx
sanchezvanessa7896
 
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
charlesdick1345
 
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITYADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ijscai
 
15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...
IJCSES Journal
 
Compiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptxCompiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptx
RushaliDeshmukh2
 
Level 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical SafetyLevel 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical Safety
JoseAlbertoCariasDel
 
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdffive-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
AdityaSharma944496
 
π0.5: a Vision-Language-Action Model with Open-World Generalization
π0.5: a Vision-Language-Action Model with Open-World Generalizationπ0.5: a Vision-Language-Action Model with Open-World Generalization
π0.5: a Vision-Language-Action Model with Open-World Generalization
NABLAS株式会社
 
QA/QC Manager (Quality management Expert)
QA/QC Manager (Quality management Expert)QA/QC Manager (Quality management Expert)
QA/QC Manager (Quality management Expert)
rccbatchplant
 
Avnet Silica's PCIM 2025 Highlights Flyer
Avnet Silica's PCIM 2025 Highlights FlyerAvnet Silica's PCIM 2025 Highlights Flyer
Avnet Silica's PCIM 2025 Highlights Flyer
WillDavies22
 
fluke dealers in bangalore..............
fluke dealers in bangalore..............fluke dealers in bangalore..............
fluke dealers in bangalore..............
Haresh Vaswani
 
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design ThinkingDT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DhruvChotaliya2
 
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptxExplainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
MahaveerVPandit
 
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptxLidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
RishavKumar530754
 
Artificial Intelligence (AI) basics.pptx
Artificial Intelligence (AI) basics.pptxArtificial Intelligence (AI) basics.pptx
Artificial Intelligence (AI) basics.pptx
aditichinar
 
Data Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptxData Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptx
RushaliDeshmukh2
 
Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.
anuragmk56
 
Introduction to FLUID MECHANICS & KINEMATICS
Introduction to FLUID MECHANICS &  KINEMATICSIntroduction to FLUID MECHANICS &  KINEMATICS
Introduction to FLUID MECHANICS & KINEMATICS
narayanaswamygdas
 
Ad

Function in Python.pptx by Faculty at gla university in mathura uttar pradesh

  • 1. Function in Python def function_name( parameters ): ‘’’function_docstring’’’ function_suite return [expression]
  • 2. def my_func(): x = 10 print("Value inside function:",x) x = 20 my_func() print("Value outside function:",x) Value inside function: 10 Value outside function: 20
  • 3. Pass by Reference vs Value def changeme( mylist1 ): "This changes a passed list into this function" print ("before change: ", mylist1) mylist1[2]=50 print ("after change: ", mylist1) return # Now you can call changeme function mylist = [10,20,30] changeme( mylist ) print ("Values outside the function: ", mylist)
  • 4. • Here, we are maintaining reference of the passed object and appending values in the same object. • Therefore, this would produce the following result- • before change: [10, 20, 30] • after change: [10, 20, 50] • Values outside the function: [10, 20, 50]
  • 5. def changeme( mylist1 ): "This changes a passed list into this function" mylist1 = [1,2,3,4] # This would assign new reference in mylist print ("Values inside the function: ", mylist1) return # Now you can call changeme function mylist = [10,20,30] changeme( mylist ) print ("Values outside the function: ", mylist)
  • 6. • 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 the following result- Values inside the function: [1, 2, 3, 4] Values outside the function: [10, 20, 30]
  • 7. Function Arguments • You can call a function by using the following types of formal arguments- • Required arguments • Keyword arguments • Default arguments • Variable-length arguments
  • 8. Required Arguments • the arguments passed to a function in correct positional order. • the number of arguments in the function call should match exactly with the function definition.
  • 9. # Function definition is here def printme( str ): "This prints a passed string into this function" print (str) return # Now you can call printme function printme(‘hello’) Output: hello
  • 10. Keyword Arguments • related to the function calls. • 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.
  • 11. def printme( strn ): "This prints a passed string into this function" print (strn) return # Now you can call printme function printme( strn = "My string")
  • 12. # Function definition is here def printinfo( name, age ): "This prints a passed info into this function" print ("Name: ", name) print ("Age ", age) return # Now you can call printinfo function printinfo( age=50, name="miki" )
  • 13. 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. def printinfo( name, age = 35 ): print ("Name: ", name) print ("Age ", age) # Now you can call printinfo function printinfo( age=50, name="miki" ) printinfo( name="miki" ) Name: miki Age 50 Name: miki Age 35
  • 14. 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.
  • 15. def function_name([formal_args,] *var_args_tuple ): function_stmt return [expression] • An asterisk (*) is placed before the variable name that holds the values of all non keyword variable arguments. • This tuple remains empty if no additional arguments are specified during the function call.
  • 16. printinfo( 10 ) printinfo( 70, 60, 50 ) Output is: 10 Output is: 70 60 50 # Function definition is here def printinfo( arg1, *vartuple ): print ("Output is: ") print (arg1) for var in vartuple: print (var)
  • 17. The Anonymous Functions • These functions are called anonymous because they are not declared in the standard manner by using the def keyword. • You can use the lambda keyword to create small anonymous functions. • lambda operator can have any number of arguments, but it can have only one expression. • It cannot contain any statements and • it returns a function object which can be assigned to any variable.
  • 18. • An anonymous function cannot be a direct call to print because lambda requires an expression. • Lambda functions have their own local namespace and cannot access variables other than those in their parameter list and those in the global namespace. • Mostly lambda functions are passed as parameters to a function which expects a function objects as parameter like map, reduce, filter functions
  • 19. def add(x, y): return x + y # Call the function add(2, 3) # Output: 5
  • 20. add = lambda x, y : x + y print add(2, 3) # Output: 5
  • 21. • In lambda x, y: x + y; x and y are arguments to the function and x + y is the expression which gets executed and its values is returned as output. • lambda x, y: x + y returns a function object which can be assigned to any variable, in this case function object is assigned to the add variable. >>>type (add) # Output: function
  • 22. • The syntax of lambda function contains only a single statement, which is as follows- lambda [arg1 [,arg2,.....argn]]:expression
  • 23. # Function definition is here >>>sum = lambda arg1, arg2: arg1 + arg2 # Now you can call sum as a function >>>print ("Value of total : ", sum( 10, 20 )) >>>print ("Value of total : ", sum( 20, 20 ))
  • 24. Use of Lambda Function • We use lambda functions when we require a nameless function for a short period of time. • In Python, we generally use it as an argument to a higher-order function (a function that takes in other functions as arguments). • Lambda functions are used along with built-in functions like filter(), map() etc.
  • 25. filter() filter(function, iterable) • creates a new list from the elements for which the function returns True. # Program to filter out only the even items from a list my_list = [1, 5, 4, 6, 8, 11, 3, 12] new_list = list(filter(lambda x: (x%2 == 0) , my_list)) print(new_list) Output: [4, 6, 8, 12]
  • 26. map() map(function, iterable) • It applies a function to every item in the iterable. • We can use map() to on a lambda function with a list: >>>M = [1,2,3,4,5] >>>squaredList = list(map(lambda x: x*x, M)) >>>print(squaredList)
  • 27. Reduce function reduce(function, iterable) • applies two arguments cumulatively to the items of iterable, from left to right. >>>from functools import reduce >>>list = [1,2,3,4,5] >>>s = reduce(lambda x, y: x+y, list) >>>print(s) • In this case the expression is always true, thus it simply sums up the elements of the list.
  • 28. >>>def fahrenheit(T): return ((float(9)/5)*T + 32) >>>temp = [36.5, 37, 37.5,39] >>>F = map(fahrenheit, temp) >>>print(list(F)) [97.7, 98.600, 99.5, 102.2]
  • 29. >>>temp = [36.5, 37, 37.5,39] >>>F=map(lambda T:((float(9)/5)*T +32 ), temp) >>>list(F) [97.7, 98.600, 99.5, 102.2]
  • 30. Global Vs Local variable >>>total = 0 # This is global variable. >>>def sum( arg1, arg2 ): total = arg1 + arg2; # Here total is local variable. 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 )
  • 31. • Inside the function local total : 30 • Outside the function global total : 0