SlideShare a Scribd company logo
1 of 22
DISCOVER . LEARN . EMPOWER
PYTHON FUNCTIONS
UNIVERSITY INSTITUTE OF
ENGINEERING
DEPARTMENT OF COMPUTER SCIENCE
AND ENGINEERING
Python Functions
• A function is a block of organized, reusable code that is used to perform a single, related action. Functions provides better
modularity for your application and a high degree of code reusing.
• As you already know, Python gives you many built-in functions like print() etc. but you can also create your own functions.
These functions are called user-defined functions.
2
Defining a Function
Here are simple rules to define a function in Python:
• Function blocks begin with the keyword def followed by the function name and parentheses ( ( ) ).
• Any input parameters or arguments should be placed within these parentheses. You can also define parameters inside these
parentheses.
• The first statement of a function can be an optional statement - the documentation string of the function or docstring.
• The code block within every function starts with a colon (:) and is indented.
• The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement
with no arguments is the same as return None.
• Declaring Docstrings: The docstrings are declared using “””triple double quotes””” just below the class, method or
function declaration. All functions should have a docstring.
• Accessing Docstrings: The docstrings can be accessed using the __doc__ method of the object or using the help function.
Syntax:
def functionname( parameters ):
“””function_docstring”””
function_suite
return [expression]
By default, parameters have a positional behavior, and you need to inform them in the same order that they were defined. 3
Calling a Function
• Example:
def printme( str ):
“””This prints a passed string function”””
print(str)
return
printme("I'm first call to user defined function!")
printme("Again second call to the same function")
This would produce following result:
I'm first call to user defined function!
Again second call to the same function
4
Pass by reference vs value
All parameters (arguments) in the Python language are passed by reference. It means if you
change what a parameter refers to within a function, the change also reflects back in the calling
function. For example:
def changeme( mylist ):
mylist.append([1,2,3,4])
print("Values inside the function: ", mylist)
return
mylist = [10,20,30]
changeme( mylist )
print("Values outside the function: ", mylist)
So this would produce following result:
Values inside the function: [10, 20, 30, [1, 2, 3, 4]]
Values outside the function: [10, 20, 30, [1, 2, 3, 4]]
5
6
# Here x is a new reference to same list lst
def myFun(x):
x[0] = 20
lst = [10,11,12,13,14,15]
myFun(lst)
print(lst)
Output:
[20, 11, 12, 13, 14, 15]
When we pass a reference and change the received reference to something else, the
connection between passed and received parameter is broken. For example, consider
below program.
# Here x is a new reference to same list lst
def myFun(x):
x=[20,30,40]
# Driver Code (Note that lst is not modified ) after function call.
lst =[10,11,12,13,14,15]
myFun(lst)
print(lst)
Output:
[10, 11, 12, 13, 14, 15]
7
There is one more example where argument is being passed by reference but inside the function, but the reference is being
over-written.
def changeme( mylist ):
mylist = [1,2,3,4]
print ("Values inside the function: ", mylist )
return
mylist = [10,20,30]
changeme( mylist )
print("Values outside the function: ", mylist)
The parameter mylist is local to the function changeme. Changing mylist within the function does not affect mylist. The
function accomplishes nothing and finally this would produce following result:
Values inside the function: [1, 2, 3, 4]
Values outside the function: [10, 20, 30]
8
Another example to demonstrate that reference link is broken if we assign a new value
(inside the function).
def myFun(x):
x=20
x=10
myFun(x)
print(x)
Output:
10
9
Function Arguments:
A function by using the following types of formal arguments::
Required arguments
Keyword arguments
Default arguments
Variable-length arguments
Required arguments:
Required arguments are the arguments passed to a function in correct positional order.
def printme( str ):
print (str)
return
printme()
This would produce following result:
Traceback (most recent call last):
File "C:/Users/hp/Desktop/UT1.PY", line 4, in <module>
printme()
TypeError: printme() missing 1 required positional argument: 'str'
10
Keyword arguments:
Keyword arguments are related to the function calls. When you use keyword arguments in a
function call, the caller identifies the arguments by the parameter name.
This allows you to skip arguments or place them out of order because the Python
interpreter is able to use the keywords provided to match the values with parameters.
def printme( str ):
print (str)
return
printme( str = "My string")
This would produce following result:
My string
11
Following example gives more clear picture. Note, here order of the parameter does not
matter:
def printinfo( name, age ):
print ("Name: ", name, end=" ")
print ("Age ", age)
return
printinfo( age=50, name="miki" )
This would produce following result:
Name: miki Age 50
12
Default arguments:
A default argument is an argument that assumes a default value if a value is not provided in
the function call for that argument.
Following example gives idea on default arguments, it would print default age if it is not
passed:
def printinfo( name, age = 35 ):
print("Name: ", name , end=" ")
print ("Age ", age)
return
printinfo( age=50, name="miki")
printinfo( name="miki" )
This would produce following result:
Name: miki Age 50
Name: miki Age 35
13
Variable-length arguments:
You may need to process a function for more arguments than you specified while defining
the function. These arguments are called variable-length arguments and are not named in
the function definition, unlike required and default arguments.
The general syntax for a function with non-keyword variable arguments is this:
def functionname([formal_args,] *var_args_tuple ):
“””function_docstring”””
function_suite
return [expression]
14
An asterisk (*) is placed before the variable name that will hold the values of all
non_keyword variable arguments. This tuple remains empty if no additional arguments are
specified during the function call. For example:
def printinfo( arg1, *vartuple ):
print("Output is: ")
print (arg1)
for var in vartuple:
print(var)
return
printinfo( 10 )
printinfo( 70, 60, 50 )
This would produce following result:
Output is:
10
Output is:
70
60
50
15
The Anonymous Functions:
• You can use the lambda keyword to create small anonymous functions. These functions are called anonymous because
they are not declared in the standard manner by using the def keyword.
• Lambda forms can take any number of arguments but return just one value in the form of an expression. They cannot
contain commands or multiple expressions.
• 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.
• Although it appears that lambda's are a one-line version of a function, they are not
equivalent to inline statements in C or C++, whose purpose is by passing function stack
allocation during invocation for performance reasons.
Syntax:
lambda [arg1 [,arg2,.....argn]]:expression
Example:
sum = lambda arg1, arg2: arg1 + arg2
print("Value of total : ", sum( 10, 20 ))
This would produce following result:
Value of total : 30
16
Scope of Variables:
• All variables in a program may not be accessible at all locations in that program. This depends on where you have
declared a variable.
• The scope of a variable determines the portion of the program where you can access a particular identifier.
• There are two basic scopes of variables in Python:
Global variables
Local variables
Global vs. Local variables:
• Variables that are defined inside a function body have a local scope, and those defined outside have a global scope.
• This means that local variables can be accessed only inside the function in which they are declared whereas global
variables can be accessed throughout the program body by all functions.
17
Example:
total = 0 # This is global variable.
def sum( arg1, arg2 ):
total = arg1 + arg2
print ("Inside the function local total : ", total)
return total
# Now you can call sum function
sum( 10, 20 )
print ("Outside the function global total : ", total)
OUTPUT:
Inside the function local total : 30
Outside the function global total : 0
18
• Global variables can be read from local scope.
• def demo():
print(S)
S=“I love python”
demo()
print(S)
We can use local and global vaiable with the same name.
• def demo():
S=“I love programming”
print(S)
S=“I love python”
demo()
print(S)
19
The global statement
• We can use global keyword, if we want to change the value of a global variable within a function and outside the function
too.
• def demo():
• global S
S=“I love programming”
print(S)
S=“I love python”
demo()
print(S)
20
Returning multiple values
• It is possible in python to return multiple values.
• Example 1:
• Def calculate(num1, num2):
• return num1+num2, num1-num2
• print(“ “, calculate(10,20))
• Example 2:
• Def calculate(num1, num2):
• return num1+num2, num1-num2
• add, sub=calculate(10,20)
• print(“add= “, add,”sub=“, sub)
21
THANK YOU
36

More Related Content

Similar to PYTHON FUNCTIONS UNIVERSITY INSTITUTE

Similar to PYTHON FUNCTIONS UNIVERSITY INSTITUTE (20)

functioninpython-1.pptx
functioninpython-1.pptxfunctioninpython-1.pptx
functioninpython-1.pptx
 
functioninpython-1.pptx
functioninpython-1.pptxfunctioninpython-1.pptx
functioninpython-1.pptx
 
Python functions
Python   functionsPython   functions
Python functions
 
Python functions
Python   functionsPython   functions
Python functions
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Python Function.pdf
Python Function.pdfPython Function.pdf
Python Function.pdf
 
Python Function.pdf
Python Function.pdfPython Function.pdf
Python Function.pdf
 
Lecture 08.pptx
Lecture 08.pptxLecture 08.pptx
Lecture 08.pptx
 
Lecture 08.pptx
Lecture 08.pptxLecture 08.pptx
Lecture 08.pptx
 
functions- best.pdf
functions- best.pdffunctions- best.pdf
functions- best.pdf
 
functions- best.pdf
functions- best.pdffunctions- best.pdf
functions- best.pdf
 
Functions and Modules.pptx
Functions and Modules.pptxFunctions and Modules.pptx
Functions and Modules.pptx
 
Functions and Modules.pptx
Functions and Modules.pptxFunctions and Modules.pptx
Functions and Modules.pptx
 
Function
FunctionFunction
Function
 
Function
FunctionFunction
Function
 
functions.pptx
functions.pptxfunctions.pptx
functions.pptx
 
functions.pptx
functions.pptxfunctions.pptx
functions.pptx
 

Recently uploaded

(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130Suhani Kapoor
 
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...ZTE
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escortsranjana rawat
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AIabhishek36461
 
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escortsranjana rawat
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxPoojaBan
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learningmisbanausheenparvam
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfAsst.prof M.Gokilavani
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130Suhani Kapoor
 
microprocessor 8085 and its interfacing
microprocessor 8085  and its interfacingmicroprocessor 8085  and its interfacing
microprocessor 8085 and its interfacingjaychoudhary37
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxbritheesh05
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxDeepakSakkari2
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.eptoze12
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfAsst.prof M.Gokilavani
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionDr.Costas Sachpazis
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...Soham Mondal
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 

Recently uploaded (20)

(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
 
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AI
 
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptx
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learning
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
 
microprocessor 8085 and its interfacing
microprocessor 8085  and its interfacingmicroprocessor 8085  and its interfacing
microprocessor 8085 and its interfacing
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptx
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptx
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
 

PYTHON FUNCTIONS UNIVERSITY INSTITUTE

  • 1. DISCOVER . LEARN . EMPOWER PYTHON FUNCTIONS UNIVERSITY INSTITUTE OF ENGINEERING DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
  • 2. Python Functions • A function is a block of organized, reusable code that is used to perform a single, related action. Functions provides better modularity for your application and a high degree of code reusing. • As you already know, Python gives you many built-in functions like print() etc. but you can also create your own functions. These functions are called user-defined functions. 2
  • 3. Defining a Function Here are simple rules to define a function in Python: • Function blocks begin with the keyword def followed by the function name and parentheses ( ( ) ). • Any input parameters or arguments should be placed within these parentheses. You can also define parameters inside these parentheses. • The first statement of a function can be an optional statement - the documentation string of the function or docstring. • The code block within every function starts with a colon (:) and is indented. • The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None. • Declaring Docstrings: The docstrings are declared using “””triple double quotes””” just below the class, method or function declaration. All functions should have a docstring. • Accessing Docstrings: The docstrings can be accessed using the __doc__ method of the object or using the help function. Syntax: def functionname( parameters ): “””function_docstring””” function_suite return [expression] By default, parameters have a positional behavior, and you need to inform them in the same order that they were defined. 3
  • 4. Calling a Function • Example: def printme( str ): “””This prints a passed string function””” print(str) return printme("I'm first call to user defined function!") printme("Again second call to the same function") This would produce following result: I'm first call to user defined function! Again second call to the same function 4
  • 5. Pass by reference vs value All parameters (arguments) in the Python language are passed by reference. It means if you change what a parameter refers to within a function, the change also reflects back in the calling function. For example: def changeme( mylist ): mylist.append([1,2,3,4]) print("Values inside the function: ", mylist) return mylist = [10,20,30] changeme( mylist ) print("Values outside the function: ", mylist) So this would produce following result: Values inside the function: [10, 20, 30, [1, 2, 3, 4]] Values outside the function: [10, 20, 30, [1, 2, 3, 4]] 5
  • 6. 6 # Here x is a new reference to same list lst def myFun(x): x[0] = 20 lst = [10,11,12,13,14,15] myFun(lst) print(lst) Output: [20, 11, 12, 13, 14, 15]
  • 7. When we pass a reference and change the received reference to something else, the connection between passed and received parameter is broken. For example, consider below program. # Here x is a new reference to same list lst def myFun(x): x=[20,30,40] # Driver Code (Note that lst is not modified ) after function call. lst =[10,11,12,13,14,15] myFun(lst) print(lst) Output: [10, 11, 12, 13, 14, 15] 7
  • 8. There is one more example where argument is being passed by reference but inside the function, but the reference is being over-written. def changeme( mylist ): mylist = [1,2,3,4] print ("Values inside the function: ", mylist ) return mylist = [10,20,30] changeme( mylist ) print("Values outside the function: ", mylist) The parameter mylist is local to the function changeme. Changing mylist within the function does not affect mylist. The function accomplishes nothing and finally this would produce following result: Values inside the function: [1, 2, 3, 4] Values outside the function: [10, 20, 30] 8
  • 9. Another example to demonstrate that reference link is broken if we assign a new value (inside the function). def myFun(x): x=20 x=10 myFun(x) print(x) Output: 10 9
  • 10. Function Arguments: A function by using the following types of formal arguments:: Required arguments Keyword arguments Default arguments Variable-length arguments Required arguments: Required arguments are the arguments passed to a function in correct positional order. def printme( str ): print (str) return printme() This would produce following result: Traceback (most recent call last): File "C:/Users/hp/Desktop/UT1.PY", line 4, in <module> printme() TypeError: printme() missing 1 required positional argument: 'str' 10
  • 11. Keyword arguments: Keyword arguments are related to the function calls. When you use keyword arguments in a function call, the caller identifies the arguments by the parameter name. This allows you to skip arguments or place them out of order because the Python interpreter is able to use the keywords provided to match the values with parameters. def printme( str ): print (str) return printme( str = "My string") This would produce following result: My string 11
  • 12. Following example gives more clear picture. Note, here order of the parameter does not matter: def printinfo( name, age ): print ("Name: ", name, end=" ") print ("Age ", age) return printinfo( age=50, name="miki" ) This would produce following result: Name: miki Age 50 12
  • 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. Following example gives idea on default arguments, it would print default age if it is not passed: def printinfo( name, age = 35 ): print("Name: ", name , end=" ") print ("Age ", age) return printinfo( age=50, name="miki") printinfo( name="miki" ) This would produce following result: Name: miki Age 50 Name: miki Age 35 13
  • 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. The general syntax for a function with non-keyword variable arguments is this: def functionname([formal_args,] *var_args_tuple ): “””function_docstring””” function_suite return [expression] 14
  • 15. An asterisk (*) is placed before the variable name that will hold the values of all non_keyword variable arguments. This tuple remains empty if no additional arguments are specified during the function call. For example: def printinfo( arg1, *vartuple ): print("Output is: ") print (arg1) for var in vartuple: print(var) return printinfo( 10 ) printinfo( 70, 60, 50 ) This would produce following result: Output is: 10 Output is: 70 60 50 15
  • 16. The Anonymous Functions: • You can use the lambda keyword to create small anonymous functions. These functions are called anonymous because they are not declared in the standard manner by using the def keyword. • Lambda forms can take any number of arguments but return just one value in the form of an expression. They cannot contain commands or multiple expressions. • 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. • Although it appears that lambda's are a one-line version of a function, they are not equivalent to inline statements in C or C++, whose purpose is by passing function stack allocation during invocation for performance reasons. Syntax: lambda [arg1 [,arg2,.....argn]]:expression Example: sum = lambda arg1, arg2: arg1 + arg2 print("Value of total : ", sum( 10, 20 )) This would produce following result: Value of total : 30 16
  • 17. Scope of Variables: • All variables in a program may not be accessible at all locations in that program. This depends on where you have declared a variable. • The scope of a variable determines the portion of the program where you can access a particular identifier. • There are two basic scopes of variables in Python: Global variables Local variables Global vs. Local variables: • Variables that are defined inside a function body have a local scope, and those defined outside have a global scope. • This means that local variables can be accessed only inside the function in which they are declared whereas global variables can be accessed throughout the program body by all functions. 17
  • 18. Example: total = 0 # This is global variable. def sum( arg1, arg2 ): total = arg1 + arg2 print ("Inside the function local total : ", total) return total # Now you can call sum function sum( 10, 20 ) print ("Outside the function global total : ", total) OUTPUT: Inside the function local total : 30 Outside the function global total : 0 18
  • 19. • Global variables can be read from local scope. • def demo(): print(S) S=“I love python” demo() print(S) We can use local and global vaiable with the same name. • def demo(): S=“I love programming” print(S) S=“I love python” demo() print(S) 19
  • 20. The global statement • We can use global keyword, if we want to change the value of a global variable within a function and outside the function too. • def demo(): • global S S=“I love programming” print(S) S=“I love python” demo() print(S) 20
  • 21. Returning multiple values • It is possible in python to return multiple values. • Example 1: • Def calculate(num1, num2): • return num1+num2, num1-num2 • print(“ “, calculate(10,20)) • Example 2: • Def calculate(num1, num2): • return num1+num2, num1-num2 • add, sub=calculate(10,20) • print(“add= “, add,”sub=“, sub) 21