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.
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:
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

Similar to Functions_new.pptx

Functions and modular programming.pptx
Functions and modular programming.pptxFunctions and modular programming.pptx
Functions and modular programming.pptx
zueZ3
 
Functions-.pdf
Functions-.pdfFunctions-.pdf
Functions-.pdf
arvdexamsection
 
Functions
FunctionsFunctions
Funtions of c programming. the functions of c helps to clarify all the tops
Funtions of c programming. the functions of c helps to clarify all the topsFuntions of c programming. the functions of c helps to clarify all the tops
Funtions of c programming. the functions of c helps to clarify all the tops
sameermhr345
 
Basics of cpp
Basics of cppBasics of cpp
Basics of cpp
vinay chauhan
 
Unit 7. Functions
Unit 7. FunctionsUnit 7. Functions
Unit 7. Functions
Ashim Lamichhane
 
CH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptxCH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptx
sangeeta borde
 
CPP06 - Functions
CPP06 - FunctionsCPP06 - Functions
CPP06 - Functions
Michael Heron
 
Chapter Introduction to Modular Programming.ppt
Chapter Introduction to Modular Programming.pptChapter Introduction to Modular Programming.ppt
Chapter Introduction to Modular Programming.ppt
AmanuelZewdie4
 
functions modules and exceptions handlings.ppt
functions modules and exceptions handlings.pptfunctions modules and exceptions handlings.ppt
functions modules and exceptions handlings.ppt
Rajasekhar364622
 
Functions
FunctionsFunctions
Functions
PralhadKhanal1
 
CHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptxCHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptx
GebruGetachew2
 
Python_Functions_Unit1.pptx
Python_Functions_Unit1.pptxPython_Functions_Unit1.pptx
Python_Functions_Unit1.pptx
Koteswari Kasireddy
 
Basic c++
Basic c++Basic c++
CPP07 - Scope
CPP07 - ScopeCPP07 - Scope
CPP07 - Scope
Michael Heron
 
FUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPTFUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPT
03062679929
 
FUNCTIONS IN C.pptx
FUNCTIONS IN C.pptxFUNCTIONS IN C.pptx
FUNCTIONS IN C.pptx
SKUP1
 
FUNCTIONS IN C.pptx
FUNCTIONS IN C.pptxFUNCTIONS IN C.pptx
FUNCTIONS IN C.pptx
LECO9
 
Function
FunctionFunction
Function
yash patel
 

Similar to Functions_new.pptx (20)

Functions and modular programming.pptx
Functions and modular programming.pptxFunctions and modular programming.pptx
Functions and modular programming.pptx
 
Functions-.pdf
Functions-.pdfFunctions-.pdf
Functions-.pdf
 
Functions
FunctionsFunctions
Functions
 
Funtions of c programming. the functions of c helps to clarify all the tops
Funtions of c programming. the functions of c helps to clarify all the topsFuntions of c programming. the functions of c helps to clarify all the tops
Funtions of c programming. the functions of c helps to clarify all the tops
 
Basics of cpp
Basics of cppBasics of cpp
Basics of cpp
 
Unit 7. Functions
Unit 7. FunctionsUnit 7. Functions
Unit 7. Functions
 
CH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptxCH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptx
 
CPP06 - Functions
CPP06 - FunctionsCPP06 - Functions
CPP06 - Functions
 
Chapter Introduction to Modular Programming.ppt
Chapter Introduction to Modular Programming.pptChapter Introduction to Modular Programming.ppt
Chapter Introduction to Modular Programming.ppt
 
functions modules and exceptions handlings.ppt
functions modules and exceptions handlings.pptfunctions modules and exceptions handlings.ppt
functions modules and exceptions handlings.ppt
 
Functions
FunctionsFunctions
Functions
 
Functions
FunctionsFunctions
Functions
 
CHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptxCHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptx
 
Python_Functions_Unit1.pptx
Python_Functions_Unit1.pptxPython_Functions_Unit1.pptx
Python_Functions_Unit1.pptx
 
Basic c++
Basic c++Basic c++
Basic c++
 
CPP07 - Scope
CPP07 - ScopeCPP07 - Scope
CPP07 - Scope
 
FUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPTFUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPT
 
FUNCTIONS IN C.pptx
FUNCTIONS IN C.pptxFUNCTIONS IN C.pptx
FUNCTIONS IN C.pptx
 
FUNCTIONS IN C.pptx
FUNCTIONS IN C.pptxFUNCTIONS IN C.pptx
FUNCTIONS IN C.pptx
 
Function
FunctionFunction
Function
 

Recently uploaded

ethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.pptethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.ppt
Jayaprasanna4
 
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptxCFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
R&R Consult
 
MCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdfMCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdf
Osamah Alsalih
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Sreedhar Chowdam
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
gdsczhcet
 
Halogenation process of chemical process industries
Halogenation process of chemical process industriesHalogenation process of chemical process industries
Halogenation process of chemical process industries
MuhammadTufail242431
 
addressing modes in computer architecture
addressing modes  in computer architectureaddressing modes  in computer architecture
addressing modes in computer architecture
ShahidSultan24
 
Democratizing Fuzzing at Scale by Abhishek Arya
Democratizing Fuzzing at Scale by Abhishek AryaDemocratizing Fuzzing at Scale by Abhishek Arya
Democratizing Fuzzing at Scale by Abhishek Arya
abh.arya
 
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Teleport Manpower Consultant
 
Vaccine management system project report documentation..pdf
Vaccine management system project report documentation..pdfVaccine management system project report documentation..pdf
Vaccine management system project report documentation..pdf
Kamal Acharya
 
Quality defects in TMT Bars, Possible causes and Potential Solutions.
Quality defects in TMT Bars, Possible causes and Potential Solutions.Quality defects in TMT Bars, Possible causes and Potential Solutions.
Quality defects in TMT Bars, Possible causes and Potential Solutions.
PrashantGoswami42
 
Final project report on grocery store management system..pdf
Final project report on grocery store management system..pdfFinal project report on grocery store management system..pdf
Final project report on grocery store management system..pdf
Kamal Acharya
 
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang,  ICLR 2024, MLILAB, KAIST AI.pdfJ.Yang,  ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
MLILAB
 
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
MdTanvirMahtab2
 
WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234
AafreenAbuthahir2
 
ASME IX(9) 2007 Full Version .pdf
ASME IX(9)  2007 Full Version       .pdfASME IX(9)  2007 Full Version       .pdf
ASME IX(9) 2007 Full Version .pdf
AhmedHussein950959
 
ethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.pptethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.ppt
Jayaprasanna4
 
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
bakpo1
 
The role of big data in decision making.
The role of big data in decision making.The role of big data in decision making.
The role of big data in decision making.
ankuprajapati0525
 
block diagram and signal flow graph representation
block diagram and signal flow graph representationblock diagram and signal flow graph representation
block diagram and signal flow graph representation
Divya Somashekar
 

Recently uploaded (20)

ethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.pptethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.ppt
 
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptxCFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
 
MCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdfMCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdf
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
 
Halogenation process of chemical process industries
Halogenation process of chemical process industriesHalogenation process of chemical process industries
Halogenation process of chemical process industries
 
addressing modes in computer architecture
addressing modes  in computer architectureaddressing modes  in computer architecture
addressing modes in computer architecture
 
Democratizing Fuzzing at Scale by Abhishek Arya
Democratizing Fuzzing at Scale by Abhishek AryaDemocratizing Fuzzing at Scale by Abhishek Arya
Democratizing Fuzzing at Scale by Abhishek Arya
 
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
 
Vaccine management system project report documentation..pdf
Vaccine management system project report documentation..pdfVaccine management system project report documentation..pdf
Vaccine management system project report documentation..pdf
 
Quality defects in TMT Bars, Possible causes and Potential Solutions.
Quality defects in TMT Bars, Possible causes and Potential Solutions.Quality defects in TMT Bars, Possible causes and Potential Solutions.
Quality defects in TMT Bars, Possible causes and Potential Solutions.
 
Final project report on grocery store management system..pdf
Final project report on grocery store management system..pdfFinal project report on grocery store management system..pdf
Final project report on grocery store management system..pdf
 
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang,  ICLR 2024, MLILAB, KAIST AI.pdfJ.Yang,  ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
 
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
 
WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234
 
ASME IX(9) 2007 Full Version .pdf
ASME IX(9)  2007 Full Version       .pdfASME IX(9)  2007 Full Version       .pdf
ASME IX(9) 2007 Full Version .pdf
 
ethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.pptethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.ppt
 
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
 
The role of big data in decision making.
The role of big data in decision making.The role of big data in decision making.
The role of big data in decision making.
 
block diagram and signal flow graph representation
block diagram and signal flow graph representationblock diagram and signal flow graph representation
block diagram and signal flow graph representation
 

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.
  • 39.
  • 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:
  • 42.
  • 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.