SlideShare a Scribd company logo
FUNCTIONS
FUNCTIONS
• Some applications contain million lines of code .
• It require a team of programmers to develop such codes and it is
hard to debugging.
• Programs are divided into manageable pieces called program
routines (or simply routines).
• program routines provide the opportunity for code reuse.
MEASURES OF LINES OF PROGRAM CODE
CONTD…
• A ROUTINE is a named group of instructions performing some
task.
• A ROUTINE can be invoked ( called ) as many times as needed in a
given program.
• When a routine terminates, execution automatically returns
to the point from which it was called.
• A function is python’s version of a program routine. Some
functions are designed to return a Value, while others are
designed for other purposes.
CONTD..
• Functions help break our program into smaller and modular
chunks.
• As our program grows larger and larger, functions make it more
organized and manageable.
• TYPES OF FUNCTIONS:
• BUILT-IN FUNCTIONS
• USER DEFINED FUNCTIONS
TYPES OF FUNCTIONS
• BUILT-IN FUNCTIONS:The python interpreter has a
number of functions that are always available for
use.
• These functions are called built-in functions.
• Example: print() function prints the given object to
the standard output device (screen) or to the text
stream file
• USER DEFINED FUNCTIONS:Functions that we define
ourselves to do certain specific task are referred as
user-defined functions.
SOME BUILT IN FUNCTIONS
CONTINUE….
CONTINUE…
CONTINUE….
• LEN:RETURN THE LENGTH (THE NUMBER OF ITEMS) OF AN
OBJECT. THE ARGUMENT MAY BE A SEQUENCE (SUCH AS A
STRING, BYTES, TUPLE, LIST, OR RANGE) OR A COLLECTION
(SUCH AS A DICTIONARY, SET, OR FROZEN SET).
CONTINUE….
• ROUND:RETURN NUMBER ROUNDED TO NDIGITS PRECISION
AFTER THE DECIMAL POINT. IF NDIGITS IS OMITTED OR
IS NONE, IT RETURNS THE NEAREST INTEGER TO ITS INPUT.
• SORTED:RETURN A NEW SORTED LIST FROM THE ITEMS IN
ITERABLE
• POWER:THE POW() METHOD RETURNS X TO THE POWER OF Y
• SUM:SUM(ITERABLE) SUMS THE NUMERIC VALUES IN AN
ITERABLE SUCH AS A LIST, TUPLE, OR SET.
SUM(ITERABLE) DOES NOT WORK WITH STRINGS BECAUSE YOU
CAN'T DO MATH ON STRINGS (WHEN YOU ADD TWO STRINGS
YOU ARE REALLY USING AN OPERATION CALLED
CONCATENATION).
CONTINUE…….
• HELP:THE HELP() FUNCTION IS YOUR NEW BEST FRIEND. INVOKE
THE BUILT-IN HELP SYSTEM ON ANY OBJECT AND IT WILL
RETURN USAGE INFORMATION ON THE OBJECT.
FUNCTION CALL
• When you define a function, you specify the name and the
sequence of
Statements.
• Later, you can “call” the function by name.
• Ex: >>> type(32)
<type 'int’>
• The name of the function is type. The expression in parentheses is
called the argument of the function.
• The result, for this function, is the type of the argument.
TYPE CONVERSION FUNCTIONS
• Python provides built-in functions that convert values from one type to
another.
• The int Function takes any value and converts it to an integer, if it can,
or complains otherwise.
• Ex: >>>int(‘32’)
32
>>>int(‘Hello’)
Value Error: invalid literal for int(): Hello
>>>int(3.9)
3
CONTD..
• float converts integers and strings to floating-point numbers.
• str converts its argument to a string.
• Ex:
>>> FLOAT(32)
32.0
>>> FLOAT('3.14159')
3.14159
>>> STR(32)
'32'
>>> STR(3.14159)
'3.14159'
MATH FUNCTIONS
• Python has a math module that provides most of the familiar
mathematical functions.
• A module is a file that contains a collection of related functions.
• Before we can use the module, we have to import it:
>>> import math
• Ex:
>>> ratio = signal_power / noise_power
>>> decibels = 10 * math.log10(ratio)
>>> radians = 0.7
>>> height = math. sin(radians)
COMPOSITION
• One of the most useful features of programming languages is
their ability to take small Building blocks and compose them.
• For example, the argument of a function can be any Kind of
expression, including arithmetic operators and even function calls:
• Ex:
>>>x = math.sin(degrees / 360.0 * 2 * math.pi)
>>>x = math.exp(math.log(x+1))
ADDING NEW FUNCTIONS
• So far, we have only been using the functions that come with python, but
it is also possible to add new functions.
• A function definition specifies the name of a new function and the
sequence of statements that execute when the function is called.
• Ex:
def print_lyrics():
print "i'm a lumberjack, and i'm okay."
print "i sleep all night and i work all day."
Empty paranthesis indicates no
arguments
Name of
function
Keyword to indicate function
definition
CONTD..
• The first line of the function definition is called the header; the
rest is called the body.
• The header has to end with a colon and the body has to be
indented.
• By convention, the Indentation is always four spaces .
• The body can contain any number of Statements.
• To end the function, you have to enter an empty line in interactive
mode.
• The syntax for calling the new function is the same as for built-in
functions:
>>> print_lyrics()
I'm a lumberjack, and I'm okay.
CONTD..
• Once you have defined a function, you can use it inside another
function.
• For example, to repeat the previous refrain, we could write a
function called repeat_lyrics:
• >>>def repeat_lyrics():
print_lyrics()
print_lyrics()
ADVANTAGES OF USER DEFINED
FUNCTIONS
• User-defined functions help to decompose a large
program into small segments which makes program
easy to understand, maintain and debug.
• If repeated code occurs in a program,function can
be used to include those codes and execute when
needed by calling that function.
• Programmers working on large project can divide
the workload by making different functions.
DEFINITIONS AND USES
>>>def print_lyrics():
print "i'm a lumberjack, and i'm okay."
print "i sleep all night and i work all day."
>>>def repeat_lyrics():
print_lyrics()
print_lyrics()
>>>repeat_lyrics()
i'm a lumberjack, and i'm okay.
i sleep all night and i work all day.
i'm a lumberjack, and i'm okay.
i sleep all night and i work all day.
CONTD..
• Function definitions get executed just like other statements, but
the effect is to create function objects.
• The statements inside the function do not get executed until the
function is called, and the function definition generates no output.
• The function definition has to be executed before the first time it
is called.
• Try the following
• Move the last line of the program to the top.
• Move the definition of print_lyrics after the definition of
repeat_lyrics.
FLOW OF EXECUTION
• Execution always begins at the first statement of the program.
• Function definitions do not alter the flow of execution of the
program, but remember that statements inside the function are
not executed until the function is called.
• During the function call the flow jumps to the body of the
function, executes all the statements there, and then comes back
to pick up where it left off.
• Python is good at keeping track of where it is.
• When it gets to the end of the program, it terminates
PARAMETERS AND ARGUMENTS
• Some of the functions takes arguments.
• Ex:
def print_twice(bruce):
print bruce
print bruce
• This function assigns the argument to a parameter named bruce.
• When the function is called, it prints the value of the parameter
(whatever it is) twice.
CONTD..
• EX:
ARGUMENTS IN FUNCTIONS
• You can call a function by using the following types
of formal arguments:
1.Required arguments
2. Keyword arguments
3.Default arguments
4.Variable-length arguments
REQUIRED ARGUMENTS
• Required arguments are the arguments passed to a
function in correct positional order.
• Here, the number of arguments in the function call
should match exactly with the function definition.
• To call the function printme(), you definitely need to
pass one argument, otherwise it gives a syntax error
as follows
REQUIRED ARGUMENTS
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.
CONTINUE….
 You can also make keyword calls to the
printme() function in the following ways –
CONTINUE…
• The following example gives more clear picture. Note that the
order of parameters does not matter
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.
• The following example gives an idea on default
arguments, it prints default age if it is not passed
CONTINUE…
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.
CONTINUE….
• SYNTAX FOR A FUNCTION WITH NON-KEYWORD VARIABLE
ARGUMENTS
An asterisk (*) is placed before the variable name
that holds the values of all no keyword variable
arguments.
This tuple remains empty if no additional
arguments are specified during the function call
CONTINUE…..
>>> printinfo(10)
ouptput is:
10
>>> printinfo(10,20,30)
ouptput is:
10
20
30
VARIABLES AND PARAMETERS ARE LOCAL
• When you create a variable inside a function, it is local, which
means that it only exists inside the function.
Functions_new.pptx
STACK DIAGRAMS
• To keep track of which variables can be used where, it is
sometimes useful to draw a stack diagram.
• Stack diagrams show the value of each variable, but they also
show the function each variable belongs to.
• Each function is represented by a frame.
• A frame is a box with the name of a function beside it and the
parameters and variables of the function inside it.
• The frames are arranged in a stack that indicates which function
called which, and so on.
CONTD..
• In the above example, print_twice was called by cat_twice, and
cat_twice was called by __main__, which is a special name for the
topmost frame.
• When you create a variable outside of any function, it belongs to
__main__.
• If an error occurs during a function call, python prints the name of
the function, and the name of the function that called it, and the
name of the function that called that, all the way back to __main__.
• Ex: If you try to access cat from within print_twice, you get a Name Error:
Functions_new.pptx
CONTD..
• This list of functions is called a traceback.
• It tells you what program file the error occurred in, and what line,
and what functions were executing at the time. It also shows the
line of code that caused the error.
• The order is the same as the order of the frames in the stack
diagram.
FRUITFUL FUNCTIONS AND VOID FUNCTIONS
• Some of the functions we are using yield results.bhey are called as
fruitful functions.
• If fruitful functions are running in interactive mode python will
display the result but in script mode the retun value will be lost
• Ex: math.sqrt(5).
• Whereas other functions, perform an action but don’t return a
value. They are called void functions.
• If you try to assign the result to a variable, you get a special value
called None.
• Ex: result=print_twice
WHY FUNCTIONS?
Gives you an opportunity to name a group of statements, which
makes your program easier to read and debug.
Functions can make a program smaller by eliminating repetitive
code.
Allows you to debug the parts one at a time and then assemble
them into a working whole.
Well-designed functions are often useful for many programs.

More Related Content

PPTX
2_3 Functions 5d.pptx2_3 Functions 5d.pptx
usha raj
 
PDF
Python functions
Prof. Dr. K. Adisesha
 
PDF
3-Python Functions.pdf in simple.........
mxdsnaps
 
PPTX
UNIT-02-pythonfunctions python function using detehdjsjehhdjejdhdjdjdjddjdhdhhd
tony8553004135
 
PPTX
Chapter One Function.pptx
miki304759
 
PPTX
Functions
Lakshmi Sarvani Videla
 
PDF
ch-3 funtions - 1 class 12.pdf
zafar578075
 
PPT
Python programming variables and comment
MalligaarjunanN
 
2_3 Functions 5d.pptx2_3 Functions 5d.pptx
usha raj
 
Python functions
Prof. Dr. K. Adisesha
 
3-Python Functions.pdf in simple.........
mxdsnaps
 
UNIT-02-pythonfunctions python function using detehdjsjehhdjejdhdjdjdjddjdhdhhd
tony8553004135
 
Chapter One Function.pptx
miki304759
 
ch-3 funtions - 1 class 12.pdf
zafar578075
 
Python programming variables and comment
MalligaarjunanN
 

Similar to Functions_new.pptx (20)

PPTX
Function in C Programming
Anil Pokhrel
 
PPT
functions _
SwatiHans10
 
PPTX
UNIT 3 python.pptx
TKSanthoshRao
 
PPTX
Functions and modular programming.pptx
zueZ3
 
PDF
Functions-.pdf
arvdexamsection
 
PPTX
Functions
Golda Margret Sheeba J
 
PPTX
Funtions of c programming. the functions of c helps to clarify all the tops
sameermhr345
 
PPTX
Function Overloading Call by value and call by reference
TusharAneyrao1
 
PPT
Py-Slides-3 difficultpythoncoursefforbeginners.ppt
mohamedsamydeveloper
 
PPT
python slides introduction interrupt.ppt
Vinod Deenathayalan
 
PPT
Basics of cpp
vinay chauhan
 
PPT
Powerpoint presentation for Python Functions
BalaSubramanian376976
 
PPTX
Unit 7. Functions
Ashim Lamichhane
 
PPTX
CH.4FUNCTIONS IN C (1).pptx
sangeeta borde
 
PPTX
CPP06 - Functions
Michael Heron
 
PDF
Programming in C Functions PPT Presentation.pdf
Ramesh Wadawadagi
 
PPTX
FUNCTIONengineeringtechnologyslidesh.pptx
ricknova674
 
PPTX
FUNCTION.pptxfkrdutytrtttrrtttttttttttttt
hboi8164
 
PDF
All chapters C++ - Copy.pdfyttttttttttttttttttttttttttttt
jacobdiriba
 
PPT
Chapter Introduction to Modular Programming.ppt
AmanuelZewdie4
 
Function in C Programming
Anil Pokhrel
 
functions _
SwatiHans10
 
UNIT 3 python.pptx
TKSanthoshRao
 
Functions and modular programming.pptx
zueZ3
 
Functions-.pdf
arvdexamsection
 
Funtions of c programming. the functions of c helps to clarify all the tops
sameermhr345
 
Function Overloading Call by value and call by reference
TusharAneyrao1
 
Py-Slides-3 difficultpythoncoursefforbeginners.ppt
mohamedsamydeveloper
 
python slides introduction interrupt.ppt
Vinod Deenathayalan
 
Basics of cpp
vinay chauhan
 
Powerpoint presentation for Python Functions
BalaSubramanian376976
 
Unit 7. Functions
Ashim Lamichhane
 
CH.4FUNCTIONS IN C (1).pptx
sangeeta borde
 
CPP06 - Functions
Michael Heron
 
Programming in C Functions PPT Presentation.pdf
Ramesh Wadawadagi
 
FUNCTIONengineeringtechnologyslidesh.pptx
ricknova674
 
FUNCTION.pptxfkrdutytrtttrrtttttttttttttt
hboi8164
 
All chapters C++ - Copy.pdfyttttttttttttttttttttttttttttt
jacobdiriba
 
Chapter Introduction to Modular Programming.ppt
AmanuelZewdie4
 

Recently uploaded (20)

PPTX
Module2 Data Base Design- ER and NF.pptx
gomathisankariv2
 
PDF
Introduction to Data Science: data science process
ShivarkarSandip
 
PPTX
easa module 3 funtamental electronics.pptx
tryanothert7
 
PDF
flutter Launcher Icons, Splash Screens & Fonts
Ahmed Mohamed
 
PDF
2025 Laurence Sigler - Advancing Decision Support. Content Management Ecommer...
Francisco Javier Mora Serrano
 
PPTX
Chapter_Seven_Construction_Reliability_Elective_III_Msc CM
SubashKumarBhattarai
 
PDF
Zero Carbon Building Performance standard
BassemOsman1
 
PDF
JUAL EFIX C5 IMU GNSS GEODETIC PERFECT BASE OR ROVER
Budi Minds
 
PPTX
database slide on modern techniques for optimizing database queries.pptx
aky52024
 
DOCX
SAR - EEEfdfdsdasdsdasdasdasdasdasdasdasda.docx
Kanimozhi676285
 
PDF
Advanced LangChain & RAG: Building a Financial AI Assistant with Real-Time Data
Soufiane Sejjari
 
PPTX
IoT_Smart_Agriculture_Presentations.pptx
poojakumari696707
 
PPT
SCOPE_~1- technology of green house and poyhouse
bala464780
 
PPTX
MT Chapter 1.pptx- Magnetic particle testing
ABCAnyBodyCanRelax
 
PDF
Introduction to Ship Engine Room Systems.pdf
Mahmoud Moghtaderi
 
PDF
Biodegradable Plastics: Innovations and Market Potential (www.kiu.ac.ug)
publication11
 
PPTX
Inventory management chapter in automation and robotics.
atisht0104
 
PDF
Chad Ayach - A Versatile Aerospace Professional
Chad Ayach
 
PDF
settlement FOR FOUNDATION ENGINEERS.pdf
Endalkazene
 
PPT
1. SYSTEMS, ROLES, AND DEVELOPMENT METHODOLOGIES.ppt
zilow058
 
Module2 Data Base Design- ER and NF.pptx
gomathisankariv2
 
Introduction to Data Science: data science process
ShivarkarSandip
 
easa module 3 funtamental electronics.pptx
tryanothert7
 
flutter Launcher Icons, Splash Screens & Fonts
Ahmed Mohamed
 
2025 Laurence Sigler - Advancing Decision Support. Content Management Ecommer...
Francisco Javier Mora Serrano
 
Chapter_Seven_Construction_Reliability_Elective_III_Msc CM
SubashKumarBhattarai
 
Zero Carbon Building Performance standard
BassemOsman1
 
JUAL EFIX C5 IMU GNSS GEODETIC PERFECT BASE OR ROVER
Budi Minds
 
database slide on modern techniques for optimizing database queries.pptx
aky52024
 
SAR - EEEfdfdsdasdsdasdasdasdasdasdasdasda.docx
Kanimozhi676285
 
Advanced LangChain & RAG: Building a Financial AI Assistant with Real-Time Data
Soufiane Sejjari
 
IoT_Smart_Agriculture_Presentations.pptx
poojakumari696707
 
SCOPE_~1- technology of green house and poyhouse
bala464780
 
MT Chapter 1.pptx- Magnetic particle testing
ABCAnyBodyCanRelax
 
Introduction to Ship Engine Room Systems.pdf
Mahmoud Moghtaderi
 
Biodegradable Plastics: Innovations and Market Potential (www.kiu.ac.ug)
publication11
 
Inventory management chapter in automation and robotics.
atisht0104
 
Chad Ayach - A Versatile Aerospace Professional
Chad Ayach
 
settlement FOR FOUNDATION ENGINEERS.pdf
Endalkazene
 
1. SYSTEMS, ROLES, AND DEVELOPMENT METHODOLOGIES.ppt
zilow058
 

Functions_new.pptx

  • 2. FUNCTIONS • Some applications contain million lines of code . • It require a team of programmers to develop such codes and it is hard to debugging. • Programs are divided into manageable pieces called program routines (or simply routines). • program routines provide the opportunity for code reuse.
  • 3. MEASURES OF LINES OF PROGRAM CODE
  • 4. CONTD… • A ROUTINE is a named group of instructions performing some task. • A ROUTINE can be invoked ( called ) as many times as needed in a given program. • When a routine terminates, execution automatically returns to the point from which it was called. • A function is python’s version of a program routine. Some functions are designed to return a Value, while others are designed for other purposes.
  • 5. CONTD.. • Functions help break our program into smaller and modular chunks. • As our program grows larger and larger, functions make it more organized and manageable. • TYPES OF FUNCTIONS: • BUILT-IN FUNCTIONS • USER DEFINED FUNCTIONS
  • 6. TYPES OF FUNCTIONS • BUILT-IN FUNCTIONS:The python interpreter has a number of functions that are always available for use. • These functions are called built-in functions. • Example: print() function prints the given object to the standard output device (screen) or to the text stream file • USER DEFINED FUNCTIONS:Functions that we define ourselves to do certain specific task are referred as user-defined functions.
  • 7. SOME BUILT IN FUNCTIONS
  • 10. CONTINUE…. • LEN:RETURN THE LENGTH (THE NUMBER OF ITEMS) OF AN OBJECT. THE ARGUMENT MAY BE A SEQUENCE (SUCH AS A STRING, BYTES, TUPLE, LIST, OR RANGE) OR A COLLECTION (SUCH AS A DICTIONARY, SET, OR FROZEN SET).
  • 11. CONTINUE…. • ROUND:RETURN NUMBER ROUNDED TO NDIGITS PRECISION AFTER THE DECIMAL POINT. IF NDIGITS IS OMITTED OR IS NONE, IT RETURNS THE NEAREST INTEGER TO ITS INPUT. • SORTED:RETURN A NEW SORTED LIST FROM THE ITEMS IN ITERABLE • POWER:THE POW() METHOD RETURNS X TO THE POWER OF Y • SUM:SUM(ITERABLE) SUMS THE NUMERIC VALUES IN AN ITERABLE SUCH AS A LIST, TUPLE, OR SET. SUM(ITERABLE) DOES NOT WORK WITH STRINGS BECAUSE YOU CAN'T DO MATH ON STRINGS (WHEN YOU ADD TWO STRINGS YOU ARE REALLY USING AN OPERATION CALLED CONCATENATION).
  • 12. CONTINUE……. • HELP:THE HELP() FUNCTION IS YOUR NEW BEST FRIEND. INVOKE THE BUILT-IN HELP SYSTEM ON ANY OBJECT AND IT WILL RETURN USAGE INFORMATION ON THE OBJECT.
  • 13. FUNCTION CALL • When you define a function, you specify the name and the sequence of Statements. • Later, you can “call” the function by name. • Ex: >>> type(32) <type 'int’> • The name of the function is type. The expression in parentheses is called the argument of the function. • The result, for this function, is the type of the argument.
  • 14. TYPE CONVERSION FUNCTIONS • Python provides built-in functions that convert values from one type to another. • The int Function takes any value and converts it to an integer, if it can, or complains otherwise. • Ex: >>>int(‘32’) 32 >>>int(‘Hello’) Value Error: invalid literal for int(): Hello >>>int(3.9) 3
  • 15. CONTD.. • float converts integers and strings to floating-point numbers. • str converts its argument to a string. • Ex: >>> FLOAT(32) 32.0 >>> FLOAT('3.14159') 3.14159 >>> STR(32) '32' >>> STR(3.14159) '3.14159'
  • 16. MATH FUNCTIONS • Python has a math module that provides most of the familiar mathematical functions. • A module is a file that contains a collection of related functions. • Before we can use the module, we have to import it: >>> import math • Ex: >>> ratio = signal_power / noise_power >>> decibels = 10 * math.log10(ratio) >>> radians = 0.7 >>> height = math. sin(radians)
  • 17. COMPOSITION • One of the most useful features of programming languages is their ability to take small Building blocks and compose them. • For example, the argument of a function can be any Kind of expression, including arithmetic operators and even function calls: • Ex: >>>x = math.sin(degrees / 360.0 * 2 * math.pi) >>>x = math.exp(math.log(x+1))
  • 18. ADDING NEW FUNCTIONS • So far, we have only been using the functions that come with python, but it is also possible to add new functions. • A function definition specifies the name of a new function and the sequence of statements that execute when the function is called. • Ex: def print_lyrics(): print "i'm a lumberjack, and i'm okay." print "i sleep all night and i work all day." Empty paranthesis indicates no arguments Name of function Keyword to indicate function definition
  • 19. CONTD.. • The first line of the function definition is called the header; the rest is called the body. • The header has to end with a colon and the body has to be indented. • By convention, the Indentation is always four spaces . • The body can contain any number of Statements. • To end the function, you have to enter an empty line in interactive mode. • The syntax for calling the new function is the same as for built-in functions: >>> print_lyrics() I'm a lumberjack, and I'm okay.
  • 20. CONTD.. • Once you have defined a function, you can use it inside another function. • For example, to repeat the previous refrain, we could write a function called repeat_lyrics: • >>>def repeat_lyrics(): print_lyrics() print_lyrics()
  • 21. ADVANTAGES OF USER DEFINED FUNCTIONS • User-defined functions help to decompose a large program into small segments which makes program easy to understand, maintain and debug. • If repeated code occurs in a program,function can be used to include those codes and execute when needed by calling that function. • Programmers working on large project can divide the workload by making different functions.
  • 22. DEFINITIONS AND USES >>>def print_lyrics(): print "i'm a lumberjack, and i'm okay." print "i sleep all night and i work all day." >>>def repeat_lyrics(): print_lyrics() print_lyrics() >>>repeat_lyrics() i'm a lumberjack, and i'm okay. i sleep all night and i work all day. i'm a lumberjack, and i'm okay. i sleep all night and i work all day.
  • 23. CONTD.. • Function definitions get executed just like other statements, but the effect is to create function objects. • The statements inside the function do not get executed until the function is called, and the function definition generates no output. • The function definition has to be executed before the first time it is called. • Try the following • Move the last line of the program to the top. • Move the definition of print_lyrics after the definition of repeat_lyrics.
  • 24. FLOW OF EXECUTION • Execution always begins at the first statement of the program. • Function definitions do not alter the flow of execution of the program, but remember that statements inside the function are not executed until the function is called. • During the function call the flow jumps to the body of the function, executes all the statements there, and then comes back to pick up where it left off. • Python is good at keeping track of where it is. • When it gets to the end of the program, it terminates
  • 25. PARAMETERS AND ARGUMENTS • Some of the functions takes arguments. • Ex: def print_twice(bruce): print bruce print bruce • This function assigns the argument to a parameter named bruce. • When the function is called, it prints the value of the parameter (whatever it is) twice.
  • 27. ARGUMENTS IN FUNCTIONS • You can call a function by using the following types of formal arguments: 1.Required arguments 2. Keyword arguments 3.Default arguments 4.Variable-length arguments
  • 28. REQUIRED ARGUMENTS • Required arguments are the arguments passed to a function in correct positional order. • Here, the number of arguments in the function call should match exactly with the function definition. • To call the function printme(), you definitely need to pass one argument, otherwise it gives a syntax error as follows
  • 30. 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.
  • 31. CONTINUE….  You can also make keyword calls to the printme() function in the following ways –
  • 32. CONTINUE… • The following example gives more clear picture. Note that the order of parameters does not matter
  • 33. 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. • The following example gives an idea on default arguments, it prints default age if it is not passed
  • 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.
  • 36. CONTINUE…. • SYNTAX FOR A FUNCTION WITH NON-KEYWORD VARIABLE ARGUMENTS An asterisk (*) is placed before the variable name that holds the values of all no keyword variable arguments. This tuple remains empty if no additional arguments are specified during the function call
  • 37. CONTINUE….. >>> printinfo(10) ouptput is: 10 >>> printinfo(10,20,30) ouptput is: 10 20 30
  • 38. VARIABLES AND PARAMETERS ARE LOCAL • When you create a variable inside a function, it is local, which means that it only exists inside the function.
  • 40. STACK DIAGRAMS • To keep track of which variables can be used where, it is sometimes useful to draw a stack diagram. • Stack diagrams show the value of each variable, but they also show the function each variable belongs to. • Each function is represented by a frame. • A frame is a box with the name of a function beside it and the parameters and variables of the function inside it. • The frames are arranged in a stack that indicates which function called which, and so on.
  • 41. CONTD.. • In the above example, print_twice was called by cat_twice, and cat_twice was called by __main__, which is a special name for the topmost frame. • When you create a variable outside of any function, it belongs to __main__. • If an error occurs during a function call, python prints the name of the function, and the name of the function that called it, and the name of the function that called that, all the way back to __main__. • Ex: If you try to access cat from within print_twice, you get a Name Error:
  • 43. CONTD.. • This list of functions is called a traceback. • It tells you what program file the error occurred in, and what line, and what functions were executing at the time. It also shows the line of code that caused the error. • The order is the same as the order of the frames in the stack diagram.
  • 44. FRUITFUL FUNCTIONS AND VOID FUNCTIONS • Some of the functions we are using yield results.bhey are called as fruitful functions. • If fruitful functions are running in interactive mode python will display the result but in script mode the retun value will be lost • Ex: math.sqrt(5). • Whereas other functions, perform an action but don’t return a value. They are called void functions. • If you try to assign the result to a variable, you get a special value called None. • Ex: result=print_twice
  • 45. WHY FUNCTIONS? Gives you an opportunity to name a group of statements, which makes your program easier to read and debug. Functions can make a program smaller by eliminating repetitive code. Allows you to debug the parts one at a time and then assemble them into a working whole. Well-designed functions are often useful for many programs.