SlideShare a Scribd company logo
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.
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.
• Syntax:
• def functionname( parameters ):
• "function_docstring" function_suite return [expression]
• 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.
• Example:
def printme( str ):
"This prints a passed string function"
print str
return
Calling a Function
• Following is the example to call printme() function:
def printme( str ): "This is a print 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
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 ): "This changes a passed list“
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]]
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 ): "This changes a passed list"
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]
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 ): "This prints a passed string"
print str;
return;
printme();
• This would produce following result:
Traceback (most recent call last):
File "test.py", line 11, in <module> printme();
TypeError: printme() takes exactly 1 argument (0 given)
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 ): "This prints a passed string"
print str;
return;
printme( str = "My string");
• This would produce following result:
My string
Following example gives more clear picture. Note, here order of
the parameter does not matter:
def printinfo( name, age ): "Test function"
print "Name: ", name;
print "Age ", age;
return;
printinfo( age=50, name="miki" );
• This would produce following result:
Name: miki Age 50
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 ): “Test function"
print "Name: ", name;
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
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]
• An asterisk (*) is placed before the variable name that will
hold the values of all nonkeyword variable arguments. This
tuple remains empty if no additional arguments are specified
during the function call. For example:
def printinfo( arg1, *vartuple ):
"This is test"
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
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:
• Following is the example to show how lembda form of
function works:
sum = lambda arg1, arg2: arg1 + arg2;
print "Value of total : ", sum( 10, 20 )
print "Value of total : ", sum( 20, 20 )
• This would produce following result:
Value of total : 30
Value of total : 40
Thank you

More Related Content

Similar to Python programming - Functions and list and tuples (20)

PDF
Python functions
Learnbay Datascience
 
PDF
Unit 1-Part-5-Functions and Set Operations.pdf
Harsha Patil
 
PPTX
Lecture 08.pptx
Mohammad Hassan
 
PPTX
Functions in Python Programming Language
BeulahS2
 
PPTX
Learn more about the concepts Functions of Python
PrathamKandari
 
PPTX
JNTUK python programming python unit 3.pptx
Venkateswara Babu Ravipati
 
PDF
Python Function.pdf
NehaSpillai1
 
PDF
functions notes.pdf python functions and opp
KirtiGarg71
 
PPTX
UNIT 3 python.pptx
TKSanthoshRao
 
PPTX
functions.pptx
KavithaChekuri3
 
PPTX
UNIT-02-pythonfunctions python function using detehdjsjehhdjejdhdjdjdjddjdhdhhd
tony8553004135
 
PPTX
Functions in C++
home
 
PPTX
Functions and modular programming.pptx
zueZ3
 
PDF
Chapter Functions for grade 12 computer Science
KrithikaTM
 
PPTX
Python functions part12
Vishal Dutt
 
PPTX
Function in Python.pptx by Faculty at gla university in mathura uttar pradesh
bloodskullgoswami
 
PPTX
functioninpython-1.pptx
SulekhJangra
 
PDF
functionnotes.pdf
AXL Computer Academy
 
PPTX
Functions and Modules.pptx
Ashwini Raut
 
PDF
PSPC-UNIT-4.pdf
ArshiniGubbala3
 
Python functions
Learnbay Datascience
 
Unit 1-Part-5-Functions and Set Operations.pdf
Harsha Patil
 
Lecture 08.pptx
Mohammad Hassan
 
Functions in Python Programming Language
BeulahS2
 
Learn more about the concepts Functions of Python
PrathamKandari
 
JNTUK python programming python unit 3.pptx
Venkateswara Babu Ravipati
 
Python Function.pdf
NehaSpillai1
 
functions notes.pdf python functions and opp
KirtiGarg71
 
UNIT 3 python.pptx
TKSanthoshRao
 
functions.pptx
KavithaChekuri3
 
UNIT-02-pythonfunctions python function using detehdjsjehhdjejdhdjdjdjddjdhdhhd
tony8553004135
 
Functions in C++
home
 
Functions and modular programming.pptx
zueZ3
 
Chapter Functions for grade 12 computer Science
KrithikaTM
 
Python functions part12
Vishal Dutt
 
Function in Python.pptx by Faculty at gla university in mathura uttar pradesh
bloodskullgoswami
 
functioninpython-1.pptx
SulekhJangra
 
functionnotes.pdf
AXL Computer Academy
 
Functions and Modules.pptx
Ashwini Raut
 
PSPC-UNIT-4.pdf
ArshiniGubbala3
 

More from MalligaarjunanN (20)

PDF
bro_nodejs-1 front end development .pdf
MalligaarjunanN
 
PDF
Microprocessor and microcontroller record.pdf
MalligaarjunanN
 
PDF
8087 MICROPROCESSOR and diagram with definition.pdf
MalligaarjunanN
 
PDF
8089 microprocessor with diagram and analytical
MalligaarjunanN
 
PPTX
English article power point presentation eng.pptx
MalligaarjunanN
 
PPTX
Digital principle and computer design Presentation (1).pptx
MalligaarjunanN
 
PPTX
Technical English grammar and tenses.pptx
MalligaarjunanN
 
PPTX
Polymorphism topic power point presentation li.pptx
MalligaarjunanN
 
PPTX
Chemistry iconic bond topic chem ppt.pptx
MalligaarjunanN
 
PPTX
C programming DOC-20230723-WA0001..pptx
MalligaarjunanN
 
PPTX
Chemistry fluorescent topic chemistry.pptx
MalligaarjunanN
 
PPTX
C programming power point presentation c ppt.pptx
MalligaarjunanN
 
PPTX
Inheritance_Polymorphism_Overloading_overriding.pptx
MalligaarjunanN
 
PPTX
Python programming file handling mhhk.pptx
MalligaarjunanN
 
PPTX
Computer organisation and architecture updated unit 2 COA ppt.pptx
MalligaarjunanN
 
PPTX
Data structures trees and graphs - Heap Tree.pptx
MalligaarjunanN
 
PPTX
Data structures trees and graphs - AVL tree.pptx
MalligaarjunanN
 
PPTX
Data structures trees - B Tree & B+Tree.pptx
MalligaarjunanN
 
PPTX
Computer organisation and architecture .
MalligaarjunanN
 
PPTX
pythoncommentsandvariables-231016105804-9a780b91 (1).pptx
MalligaarjunanN
 
bro_nodejs-1 front end development .pdf
MalligaarjunanN
 
Microprocessor and microcontroller record.pdf
MalligaarjunanN
 
8087 MICROPROCESSOR and diagram with definition.pdf
MalligaarjunanN
 
8089 microprocessor with diagram and analytical
MalligaarjunanN
 
English article power point presentation eng.pptx
MalligaarjunanN
 
Digital principle and computer design Presentation (1).pptx
MalligaarjunanN
 
Technical English grammar and tenses.pptx
MalligaarjunanN
 
Polymorphism topic power point presentation li.pptx
MalligaarjunanN
 
Chemistry iconic bond topic chem ppt.pptx
MalligaarjunanN
 
C programming DOC-20230723-WA0001..pptx
MalligaarjunanN
 
Chemistry fluorescent topic chemistry.pptx
MalligaarjunanN
 
C programming power point presentation c ppt.pptx
MalligaarjunanN
 
Inheritance_Polymorphism_Overloading_overriding.pptx
MalligaarjunanN
 
Python programming file handling mhhk.pptx
MalligaarjunanN
 
Computer organisation and architecture updated unit 2 COA ppt.pptx
MalligaarjunanN
 
Data structures trees and graphs - Heap Tree.pptx
MalligaarjunanN
 
Data structures trees and graphs - AVL tree.pptx
MalligaarjunanN
 
Data structures trees - B Tree & B+Tree.pptx
MalligaarjunanN
 
Computer organisation and architecture .
MalligaarjunanN
 
pythoncommentsandvariables-231016105804-9a780b91 (1).pptx
MalligaarjunanN
 
Ad

Recently uploaded (20)

PDF
Biomechanics of Gait: Engineering Solutions for Rehabilitation (www.kiu.ac.ug)
publication11
 
PDF
PORTFOLIO Golam Kibria Khan — architect with a passion for thoughtful design...
MasumKhan59
 
PPTX
Depth First Search Algorithm in 🧠 DFS in Artificial Intelligence (AI)
rafeeqshaik212002
 
PDF
MAD Unit - 2 Activity and Fragment Management in Android (Diploma IT)
JappanMavani
 
PPTX
Green Building & Energy Conservation ppt
Sagar Sarangi
 
PDF
Set Relation Function Practice session 24.05.2025.pdf
DrStephenStrange4
 
PPTX
GitOps_Without_K8s_Training_detailed git repository
DanialHabibi2
 
DOCX
CS-802 (A) BDH Lab manual IPS Academy Indore
thegodhimself05
 
PPTX
Hashing Introduction , hash functions and techniques
sailajam21
 
PPTX
Evaluation and thermal analysis of shell and tube heat exchanger as per requi...
shahveer210504
 
PDF
Design Thinking basics for Engineers.pdf
CMR University
 
PDF
Zilliz Cloud Demo for performance and scale
Zilliz
 
PPTX
美国电子版毕业证南卡罗莱纳大学上州分校水印成绩单USC学费发票定做学位证书编号怎么查
Taqyea
 
PDF
Pressure Measurement training for engineers and Technicians
AIESOLUTIONS
 
PPTX
Day2 B2 Best.pptx
helenjenefa1
 
PPTX
265587293-NFPA 101 Life safety code-PPT-1.pptx
chandermwason
 
PPTX
Heart Bleed Bug - A case study (Course: Cryptography and Network Security)
Adri Jovin
 
PPTX
GitOps_Without_K8s_Training simple one without k8s
DanialHabibi2
 
PPTX
Solar Thermal Energy System Seminar.pptx
Gpc Purapuza
 
PPTX
artificial intelligence applications in Geomatics
NawrasShatnawi1
 
Biomechanics of Gait: Engineering Solutions for Rehabilitation (www.kiu.ac.ug)
publication11
 
PORTFOLIO Golam Kibria Khan — architect with a passion for thoughtful design...
MasumKhan59
 
Depth First Search Algorithm in 🧠 DFS in Artificial Intelligence (AI)
rafeeqshaik212002
 
MAD Unit - 2 Activity and Fragment Management in Android (Diploma IT)
JappanMavani
 
Green Building & Energy Conservation ppt
Sagar Sarangi
 
Set Relation Function Practice session 24.05.2025.pdf
DrStephenStrange4
 
GitOps_Without_K8s_Training_detailed git repository
DanialHabibi2
 
CS-802 (A) BDH Lab manual IPS Academy Indore
thegodhimself05
 
Hashing Introduction , hash functions and techniques
sailajam21
 
Evaluation and thermal analysis of shell and tube heat exchanger as per requi...
shahveer210504
 
Design Thinking basics for Engineers.pdf
CMR University
 
Zilliz Cloud Demo for performance and scale
Zilliz
 
美国电子版毕业证南卡罗莱纳大学上州分校水印成绩单USC学费发票定做学位证书编号怎么查
Taqyea
 
Pressure Measurement training for engineers and Technicians
AIESOLUTIONS
 
Day2 B2 Best.pptx
helenjenefa1
 
265587293-NFPA 101 Life safety code-PPT-1.pptx
chandermwason
 
Heart Bleed Bug - A case study (Course: Cryptography and Network Security)
Adri Jovin
 
GitOps_Without_K8s_Training simple one without k8s
DanialHabibi2
 
Solar Thermal Energy System Seminar.pptx
Gpc Purapuza
 
artificial intelligence applications in Geomatics
NawrasShatnawi1
 
Ad

Python programming - Functions and list and tuples

  • 1. 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. • Syntax: • def functionname( parameters ): • "function_docstring" function_suite return [expression]
  • 3. • 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. • Example: def printme( str ): "This prints a passed string function" print str return
  • 4. Calling a Function • Following is the example to call printme() function: def printme( str ): "This is a print 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
  • 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 ): "This changes a passed list“ 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]]
  • 6. 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 ): "This changes a passed list" 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]
  • 7. 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 ): "This prints a passed string" print str; return; printme(); • This would produce following result: Traceback (most recent call last): File "test.py", line 11, in <module> printme(); TypeError: printme() takes exactly 1 argument (0 given)
  • 8. 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 ): "This prints a passed string" print str; return; printme( str = "My string"); • This would produce following result: My string
  • 9. Following example gives more clear picture. Note, here order of the parameter does not matter: def printinfo( name, age ): "Test function" print "Name: ", name; print "Age ", age; return; printinfo( age=50, name="miki" ); • This would produce following result: Name: miki Age 50
  • 10. 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 ): “Test function" print "Name: ", name; 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
  • 11. 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]
  • 12. • An asterisk (*) is placed before the variable name that will hold the values of all nonkeyword variable arguments. This tuple remains empty if no additional arguments are specified during the function call. For example: def printinfo( arg1, *vartuple ): "This is test" 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
  • 13. 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
  • 14. Example: • Following is the example to show how lembda form of function works: sum = lambda arg1, arg2: arg1 + arg2; print "Value of total : ", sum( 10, 20 ) print "Value of total : ", sum( 20, 20 ) • This would produce following result: Value of total : 30 Value of total : 40