SlideShare a Scribd company logo
WORKING
WITH
FUNCTIONS
Introduction
 Large programs are often difficult to manage, thus large programs are
divided into smaller unitsknownas functions.
 It issimply a group of statements under any namei.e. function nameand canbe
invoked(call) from other part of program.
 T
ake an example of School Management Software, now this software will
contain various tasks like Registering student, Fee collection, Library book issue,
TC generation, Result Declaration etc. In this case we have to create different
functionsfor eachtask to manage the software development.
Introduction
 Set of functions is stored in a file called MODULE. And this approach is
knownasMODULARIZATION, makesprogram easier to understand,test
and maintain.
 Commonly used modules that contain source code for generic need are
called LIBRARIES.
 Modulescontains setof functions.Functionsisof mainly two types:
Built-in Functions
Advantages of Function
 PROGRAM HANDLING EASIER: only small part of the program is dealt with
at a time.
 REDUCEDLoC:aswith functionthe commonsetof code iswritten only onceand
canbe called from any part of program, soit reducesLineof Code
 EASY UPDATING : if function is not used then set of code is to be repeated
everywhere it is required. Hence if we want to change in any
formula/expression then we have to make changes to every place, if
forgotten then output will be not the desired output. With function we have to
UserDefinedFunctions
 A function is a set of statements that performs a specific task; a common
structuring elements that allows you to use a piece of code repeatedly in
different part of program. Functions are also known as sub-routine, methods,
procedure or subprogram.
 Syntax to create USERDEFINEDFUNCTION
def function_name([commaseparated list of parameters]):
statements…. statements….
KEYWORD FUNCTIONDEFINITION
Pointstoremember…
 Keyword def marksthe start of function header
 Functionnamemustbe uniqueand follows namingrules sameasfor
identifiers
 Functioncantake arguments.It isoptional
 A colon(:) to mark the end of function header
 Functioncancontainsoneor morestatementto perform specific task
 Anoptional returnstatementto return a value from the function.
 Functionmustbe called/invoked to execute its code
UserDefined function can be….
1. Functionwith noargumentsand noreturn
2. Function with argumentsbut no returnvalue
3. Function with argumentsand return value
4. Function with no argument but return value
Function with no argument and no return
 Thistype of function isalso knownasvoid function
FUNCTIONNAME NO P
ARAMETER,HENCEVOID
Returnkeyword notused
FUNCTIONCALLING,ITWILLINVOKEwelcome()TO PERFORMITSACTION
Functionwithparametersbutno return value
 Parametersare given in the parenthesisseparated by comma.
 Valuesare passedfor the parameter at the time of function
calling.
Functionwithparametersbutno return value
Functionwith parameter and return
 We canreturn values from function usingreturn
keyword.
 Thereturn value mustbe usedat the calling place by
–
 Eitherstore it any variable
 Usewith print()
 Usein any expression
Functionwith
return
Functionwithreturn
NOTE:the return statement ends a
functionexecutionevenif it is inthe
middleof function. Anythingwritten
below return statement will
become unreachable code.
def max(x,y):
if x>y:
returnx
else:
returny
print(“Iam not reachable”)
ParametersandArgumentsin Function
 Parameters are the value(s) provided in the parenthesis when we write
function header. Theseare the values required by function to work
 If there are morethan oneparameter, it mustbe separated by comma(,)
 An Argument is a value that is passed to the function when it is called. In
other words arguments are the value(s) provided in function call/invoke
statement
 Parameter isalso knownasFORMAL ARGUMENTS/PARAMETERS
 Arguments is also known as ACTUAL ARGUMENTS/PARAMETER
 Note: Functioncanalter only MUTABLETYPEvalues.
Exampleof Formal/Actual Arguments
ACTUALARGUMENT
FORMALARGUMENT
TypesofArguments
 Thereare 4 types of ActualArguments allowed in
Python:
1. Positional arguments
2. Default arguments
3. Keyword arguments
4. Variable length arguments
Positional arguments
 Are argumentspassedto a function in correct positional
order
 Here x ispassedto a and y ispassedto b i.e. in the order of their position
IfthenumberofformalargumentandactualdiffersthenPythonwillraiseanerror
Default arguments
 Sometimes we can provide default values for our positional
arguments. In this case if we are not passing any value then default
valueswill be considered.
 Default argumentmustnotfollowed by non-default arguments.
def interest(principal,rate,time=15):
def interest(principal,rate=8.5,time=15):
def interest(principal,rate=8.5,time):
VALID
INVALID
Default arguments
Keyword(Named)Arguments
 The default keyword gives flexibility to specify default value for a
parameter so that it can be skipped in the function call, if needed.
However, still we cannot change the order of arguments in function
call i.e. you have to remember the order of the arguments and pass
the value accordingly.
 T
oget control and flexibility over the values sent as arguments, python
offers KEYWORDARGUMENTS.
 This allows to call function with arguments in any order using name of
Keyword(Named)Argument
Rules forcombining all threetypeof
arguments
 Anargumentlist mustfirst contain positional arguments
followed by keyword arguments
 Keyword argumentsshouldbe taken from the required
arguments
 Y
oucannotspecify a value for an argumentmore than once
Exampleof legal/illegal function call
FUNCTION CALL LEGAL/
ILLEGAL
REASON
Average(n2=20, n1=40,n3=80) LEGAL Nondefault values provided as
named arguments
Average(100,200,n1=300) LEGAL Keyword argument canbe in any
order
Average(100,n2=10,n3=15) LEGAL Positional argument before the
keyword arguments
Average(n3=70,n1=90,100) ILLEGAL Keyword argument before the
positional arguments
Average(100,n1=23,n2=1) ILLEGAL Multiple values provided for n1
def Average(n3,n2,n1=200):
return(n1+n2+n3)/3
ReturningMultiple values
 Unlikeother programming languages,python lets youreturn
morethanonevalue from function.
 Themultiple return value mustbe either stored in TUPLEor wecan
UNP
ACKthe received value by specifying the samenumberof
variables onthe left of assignmentof function call.
Multiple return value stored in TUPLE
Multiple return value stored by
unpacking in multiple variables
Scopeof
Variables
 SCOPE means in which part(s) of the program, a
particular piece of code or data isaccessible or known.
 InPython there are broadly 2 kinds of Scopes:
Global Scope
Local Scope
Global Scope
 A name declared in top level segment( main ) of a program is
said to haveglobal scopeand canbe usedin entire program.
 Variable defined outsideall functionsare global variables.
 Aname declare in a function body is said to have local scope i.e. it can be
usedonly within this function and the other block inside the function.
 Theformal parameters are also having local scope.
Local Scope
Example– Localand Global Scope
Example– Localand Global Scope
“a‟isnot accessible
here becauseit is
declared infunction
area(), soscopeis
local to area()
Example– Localand Global Scope
Variable "ar‟ is accessible in
function showarea() because
it ishaving Global Scope
Thisdeclaration “global count” is
necessaryfor usingglobal
variables in function, other wise an
error “local variable 'count'
referenced before assignment”
will appear becauselocal scope
will create variable “count” and it
will be found unassigned
Lifetime of Variable
 Isthe time for whicha variable livesinmemory.
 For Global variables the lifetime isentire program run
i.e. aslong asprogram isexecuting.
• For Local variables lifetime is their function‟s run i.e. as long as
function isexecuting.
NameResolution(ScopeResolution)
 Forevery nameusedwithin program python follows nameresolutionrules knownasLEGB rule.
 (i) LOCAL : first check whether name is in local environment, if yes Python uses its value
otherwise moves to (ii)
 (ii) ENCLOSING ENVIRONMENT: if not in local, Python checks whether name is in Enclosing
Environment,if yes Python uses its value otherwise moves to (iii)
 GLOBAL ENVIRONMENT: if not in above scope Python checks it in Global environment, if yes
Python uses itotherwise moves to (iv)
 BUILT-IN ENVIRONMENT: if not in above scope, Python checks it in built-in environment, if
yes, Python uses its value otherwise Python would reportthe error:
 name<variable> notdefined
Predict the output
Programwith
variable “value” in
both LOCALand
GLOBALSCOPE
Predict the output
Programwith
variable “value” in
both LOCALand
GLOBALSCOPE
Predict the output
UsingGLOBAL
variable “value” in
local scope
Predict the output
UsingGLOBAL
variable “value” in
local scope
Predict the output
Variable “value”
neither in local nor
global scope
Predict the output
Variable “value”
neither in local nor
global scope
Predict the output
Variable in Global
notin Local
(input in variable at
global scope)
Predict the output
Variable in Global
notin Local
(input in variable at
global scope)
Mutability/Immutability of
Arguments/Parameters and function call
Mutability/Immutability of
Arguments/Parameters and function call
Mutability/Immutability of
Arguments/Parameters and function call
 Fromthe previous example we can recall the concept learned in classXI
that Python variables are not storage containers, rather Python
variables are like memory references, they refer to memory address
where the value is stored, thus any change in immutable type data
will also change the memory address. So any change to formal
argument will not reflect back to its corresponding actual argument
and in case of mutable type, any change in mutable type will not
change thememory address of variable.
Mutability/Immutability of
Arguments/Parameters and function call
Because List if Mutable type, hence any change in formal
argument myList will not change the memory address, So
changes done tomyListwill be reflectedback to List1.
Howeverif weformalargumentisassignedtosomeothervariableordatatype then
linkwillbreakandchangeswillnotreflectbacktoactualargument
Forexample (if inside function updateData() we assign myList as:
myList = 20 OR myList = temp
PassingString to function
 Functioncanaccept string asa parameter
 As per Python, string is immutable type, so function can access the
value of string but cannotalter the string
 T
o modify string, the trick is to take another string and concatenate
the modified value of parameter string in the newly created string.
Passing string tofunction and counthow
many vowels in it
Program to counthowmanytimesany
character ispresent in string
Program toJumblethegiven string by passing itto
functionusing temporary string
PassingListto function
 We canalso passListto any function asparameter
 Dueto the mutable nature of List,function canalter the list of
valuesin place.
 It ismostlyusedin data structurelike sorting, stack, queue etc.
Passing list tofunction,and just
double each value
Passinglist to functionto double the odd
valuesand half the even values
Passingnested list to function and print all thosevalues
whichare at diagonal position in the form of matrix
Passinglist to functionto calculate sumand average of
all numbersand return it in the form of tuple
Passinglist to functionto calculate sumand average of
all numbersand return it in the form of tuple
Passingtuples to function
 We can also passtuples to function as parameter
 Dueto its immutability nature, function can only access
the values of tuples but cannot modify it.
Creating a login program with the
help of passing tuple to
function
Creating a login program with the
help of passing tuple to
function
OUTPUTOFPREVIOUSPROGRAM
Input n numbers in tuple and pass it function to
count howmanyevenand odd numbersare
entered.
Input n numbers in tuple and pass it function to
count howmanyevenand odd numbersare
entered.
PassingDictionary to function
 Pythonalso allows usto passdictionaries to function
 Dueto its mutability nature,function canalter the keysor values
of dictionary in place
 Letusseefew examples of howto passdictionary to functions.
P
assing dictionary to function with list and stores the
value of list as key and its frequency or no. of
occurrenceasvalue
Passingdictionary to function with keyand value,
and update value at that key in dictionary
Passingdictionary to function with keyand value,
and update value at that key in dictionary

More Related Content

Similar to FUNCTIONS.pptx

Chapter One Function.pptx
Chapter One Function.pptxChapter One Function.pptx
Chapter One Function.pptx
miki304759
 
VIT351 Software Development VI Unit1
VIT351 Software Development VI Unit1VIT351 Software Development VI Unit1
VIT351 Software Development VI Unit1
YOGESH SINGH
 
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptxCH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
SangeetaBorde3
 
Functions in Python.pdfnsjiwshkwijjahuwjwjw
Functions in Python.pdfnsjiwshkwijjahuwjwjwFunctions in Python.pdfnsjiwshkwijjahuwjwjw
Functions in Python.pdfnsjiwshkwijjahuwjwjw
MayankSinghRawat6
 
Operator Overloading and Scope of Variable
Operator Overloading and Scope of VariableOperator Overloading and Scope of Variable
Operator Overloading and Scope of Variable
MOHIT DADU
 
Chapter Introduction to Modular Programming.ppt
Chapter Introduction to Modular Programming.pptChapter Introduction to Modular Programming.ppt
Chapter Introduction to Modular Programming.ppt
AmanuelZewdie4
 
Mastering Python lesson 4_functions_parameters_arguments
Mastering Python lesson 4_functions_parameters_argumentsMastering Python lesson 4_functions_parameters_arguments
Mastering Python lesson 4_functions_parameters_arguments
Ruth Marvin
 
Functions in C
Functions in CFunctions in C
Functions in C
Kamal Acharya
 
Functions in c
Functions in cFunctions in c
Functions in c
SunithaVesalpu
 
function of C.pptx
function of C.pptxfunction of C.pptx
function of C.pptx
shivas379526
 
Dive into Python Functions Fundamental Concepts.pdf
Dive into Python Functions Fundamental Concepts.pdfDive into Python Functions Fundamental Concepts.pdf
Dive into Python Functions Fundamental Concepts.pdf
SudhanshiBakre1
 
Basic information of function in cpu
Basic information of function in cpuBasic information of function in cpu
Basic information of function in cpu
Dhaval Jalalpara
 
FUNCTIONS IN R PROGRAMMING.pptx
FUNCTIONS IN R PROGRAMMING.pptxFUNCTIONS IN R PROGRAMMING.pptx
FUNCTIONS IN R PROGRAMMING.pptx
SafnaSaff1
 
Modular Programming in C
Modular Programming in CModular Programming in C
Modular Programming in C
bhawna kol
 
c.p function
c.p functionc.p function
c.p function
giri5624
 
Functions and Modules.pptx
Functions and Modules.pptxFunctions and Modules.pptx
Functions and Modules.pptx
Ashwini Raut
 
4. function
4. function4. function
4. function
Shankar Gangaju
 
User defined functions.1
User defined functions.1User defined functions.1
User defined functions.1
Mohammad Zuber Vohra
 

Similar to FUNCTIONS.pptx (20)

Chapter One Function.pptx
Chapter One Function.pptxChapter One Function.pptx
Chapter One Function.pptx
 
VIT351 Software Development VI Unit1
VIT351 Software Development VI Unit1VIT351 Software Development VI Unit1
VIT351 Software Development VI Unit1
 
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptxCH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
 
Functions in Python.pdfnsjiwshkwijjahuwjwjw
Functions in Python.pdfnsjiwshkwijjahuwjwjwFunctions in Python.pdfnsjiwshkwijjahuwjwjw
Functions in Python.pdfnsjiwshkwijjahuwjwjw
 
Operator Overloading and Scope of Variable
Operator Overloading and Scope of VariableOperator Overloading and Scope of Variable
Operator Overloading and Scope of Variable
 
Chapter Introduction to Modular Programming.ppt
Chapter Introduction to Modular Programming.pptChapter Introduction to Modular Programming.ppt
Chapter Introduction to Modular Programming.ppt
 
Mastering Python lesson 4_functions_parameters_arguments
Mastering Python lesson 4_functions_parameters_argumentsMastering Python lesson 4_functions_parameters_arguments
Mastering Python lesson 4_functions_parameters_arguments
 
Functions in C
Functions in CFunctions in C
Functions in C
 
Functions in c
Functions in cFunctions in c
Functions in c
 
function of C.pptx
function of C.pptxfunction of C.pptx
function of C.pptx
 
Dive into Python Functions Fundamental Concepts.pdf
Dive into Python Functions Fundamental Concepts.pdfDive into Python Functions Fundamental Concepts.pdf
Dive into Python Functions Fundamental Concepts.pdf
 
Basic information of function in cpu
Basic information of function in cpuBasic information of function in cpu
Basic information of function in cpu
 
FUNCTIONS IN R PROGRAMMING.pptx
FUNCTIONS IN R PROGRAMMING.pptxFUNCTIONS IN R PROGRAMMING.pptx
FUNCTIONS IN R PROGRAMMING.pptx
 
Modular Programming in C
Modular Programming in CModular Programming in C
Modular Programming in C
 
Ch4 functions
Ch4 functionsCh4 functions
Ch4 functions
 
c.p function
c.p functionc.p function
c.p function
 
Functions and Modules.pptx
Functions and Modules.pptxFunctions and Modules.pptx
Functions and Modules.pptx
 
4. function
4. function4. function
4. function
 
Function
FunctionFunction
Function
 
User defined functions.1
User defined functions.1User defined functions.1
User defined functions.1
 

Recently uploaded

The Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdfThe Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdf
Pipe Restoration Solutions
 
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
 
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation & Control
 
ML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptxML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptx
Vijay Dialani, PhD
 
HYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationHYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generation
Robbie Edward Sayers
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
TeeVichai
 
Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
gerogepatton
 
English lab ppt no titlespecENG PPTt.pdf
English lab ppt no titlespecENG PPTt.pdfEnglish lab ppt no titlespecENG PPTt.pdf
English lab ppt no titlespecENG PPTt.pdf
BrazilAccount1
 
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
 
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
 
DESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docxDESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docx
FluxPrime1
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
Kamal Acharya
 
space technology lecture notes on satellite
space technology lecture notes on satellitespace technology lecture notes on satellite
space technology lecture notes on satellite
ongomchris
 
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
 
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
H.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdfH.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdf
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
MLILAB
 
AP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specificAP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specific
BrazilAccount1
 
Fundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptxFundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptx
manasideore6
 
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
zwunae
 
Standard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - NeometrixStandard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - Neometrix
Neometrix_Engineering_Pvt_Ltd
 
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)

The Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdfThe Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdf
 
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
 
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
 
ML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptxML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptx
 
HYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationHYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generation
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
 
Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
 
English lab ppt no titlespecENG PPTt.pdf
English lab ppt no titlespecENG PPTt.pdfEnglish lab ppt no titlespecENG PPTt.pdf
English lab ppt no titlespecENG PPTt.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
 
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.
 
DESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docxDESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docx
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
 
space technology lecture notes on satellite
space technology lecture notes on satellitespace technology lecture notes on satellite
space technology lecture notes on satellite
 
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
 
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
H.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdfH.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdf
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
 
AP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specificAP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specific
 
Fundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptxFundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptx
 
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
 
Standard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - NeometrixStandard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - Neometrix
 
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.pptx

  • 2. Introduction  Large programs are often difficult to manage, thus large programs are divided into smaller unitsknownas functions.  It issimply a group of statements under any namei.e. function nameand canbe invoked(call) from other part of program.  T ake an example of School Management Software, now this software will contain various tasks like Registering student, Fee collection, Library book issue, TC generation, Result Declaration etc. In this case we have to create different functionsfor eachtask to manage the software development.
  • 3. Introduction  Set of functions is stored in a file called MODULE. And this approach is knownasMODULARIZATION, makesprogram easier to understand,test and maintain.  Commonly used modules that contain source code for generic need are called LIBRARIES.  Modulescontains setof functions.Functionsisof mainly two types: Built-in Functions
  • 4. Advantages of Function  PROGRAM HANDLING EASIER: only small part of the program is dealt with at a time.  REDUCEDLoC:aswith functionthe commonsetof code iswritten only onceand canbe called from any part of program, soit reducesLineof Code  EASY UPDATING : if function is not used then set of code is to be repeated everywhere it is required. Hence if we want to change in any formula/expression then we have to make changes to every place, if forgotten then output will be not the desired output. With function we have to
  • 5. UserDefinedFunctions  A function is a set of statements that performs a specific task; a common structuring elements that allows you to use a piece of code repeatedly in different part of program. Functions are also known as sub-routine, methods, procedure or subprogram.  Syntax to create USERDEFINEDFUNCTION def function_name([commaseparated list of parameters]): statements…. statements…. KEYWORD FUNCTIONDEFINITION
  • 6. Pointstoremember…  Keyword def marksthe start of function header  Functionnamemustbe uniqueand follows namingrules sameasfor identifiers  Functioncantake arguments.It isoptional  A colon(:) to mark the end of function header  Functioncancontainsoneor morestatementto perform specific task  Anoptional returnstatementto return a value from the function.  Functionmustbe called/invoked to execute its code
  • 7. UserDefined function can be…. 1. Functionwith noargumentsand noreturn 2. Function with argumentsbut no returnvalue 3. Function with argumentsand return value 4. Function with no argument but return value
  • 8. Function with no argument and no return  Thistype of function isalso knownasvoid function FUNCTIONNAME NO P ARAMETER,HENCEVOID Returnkeyword notused FUNCTIONCALLING,ITWILLINVOKEwelcome()TO PERFORMITSACTION
  • 9. Functionwithparametersbutno return value  Parametersare given in the parenthesisseparated by comma.  Valuesare passedfor the parameter at the time of function calling.
  • 11. Functionwith parameter and return  We canreturn values from function usingreturn keyword.  Thereturn value mustbe usedat the calling place by –  Eitherstore it any variable  Usewith print()  Usein any expression
  • 13. Functionwithreturn NOTE:the return statement ends a functionexecutionevenif it is inthe middleof function. Anythingwritten below return statement will become unreachable code. def max(x,y): if x>y: returnx else: returny print(“Iam not reachable”)
  • 14. ParametersandArgumentsin Function  Parameters are the value(s) provided in the parenthesis when we write function header. Theseare the values required by function to work  If there are morethan oneparameter, it mustbe separated by comma(,)  An Argument is a value that is passed to the function when it is called. In other words arguments are the value(s) provided in function call/invoke statement  Parameter isalso knownasFORMAL ARGUMENTS/PARAMETERS  Arguments is also known as ACTUAL ARGUMENTS/PARAMETER  Note: Functioncanalter only MUTABLETYPEvalues.
  • 16. TypesofArguments  Thereare 4 types of ActualArguments allowed in Python: 1. Positional arguments 2. Default arguments 3. Keyword arguments 4. Variable length arguments
  • 17. Positional arguments  Are argumentspassedto a function in correct positional order  Here x ispassedto a and y ispassedto b i.e. in the order of their position
  • 19. Default arguments  Sometimes we can provide default values for our positional arguments. In this case if we are not passing any value then default valueswill be considered.  Default argumentmustnotfollowed by non-default arguments. def interest(principal,rate,time=15): def interest(principal,rate=8.5,time=15): def interest(principal,rate=8.5,time): VALID INVALID
  • 21. Keyword(Named)Arguments  The default keyword gives flexibility to specify default value for a parameter so that it can be skipped in the function call, if needed. However, still we cannot change the order of arguments in function call i.e. you have to remember the order of the arguments and pass the value accordingly.  T oget control and flexibility over the values sent as arguments, python offers KEYWORDARGUMENTS.  This allows to call function with arguments in any order using name of
  • 23. Rules forcombining all threetypeof arguments  Anargumentlist mustfirst contain positional arguments followed by keyword arguments  Keyword argumentsshouldbe taken from the required arguments  Y oucannotspecify a value for an argumentmore than once
  • 24. Exampleof legal/illegal function call FUNCTION CALL LEGAL/ ILLEGAL REASON Average(n2=20, n1=40,n3=80) LEGAL Nondefault values provided as named arguments Average(100,200,n1=300) LEGAL Keyword argument canbe in any order Average(100,n2=10,n3=15) LEGAL Positional argument before the keyword arguments Average(n3=70,n1=90,100) ILLEGAL Keyword argument before the positional arguments Average(100,n1=23,n2=1) ILLEGAL Multiple values provided for n1 def Average(n3,n2,n1=200): return(n1+n2+n3)/3
  • 25. ReturningMultiple values  Unlikeother programming languages,python lets youreturn morethanonevalue from function.  Themultiple return value mustbe either stored in TUPLEor wecan UNP ACKthe received value by specifying the samenumberof variables onthe left of assignmentof function call.
  • 26. Multiple return value stored in TUPLE
  • 27. Multiple return value stored by unpacking in multiple variables
  • 28. Scopeof Variables  SCOPE means in which part(s) of the program, a particular piece of code or data isaccessible or known.  InPython there are broadly 2 kinds of Scopes: Global Scope Local Scope
  • 29. Global Scope  A name declared in top level segment( main ) of a program is said to haveglobal scopeand canbe usedin entire program.  Variable defined outsideall functionsare global variables.  Aname declare in a function body is said to have local scope i.e. it can be usedonly within this function and the other block inside the function.  Theformal parameters are also having local scope. Local Scope
  • 31. Example– Localand Global Scope “a‟isnot accessible here becauseit is declared infunction area(), soscopeis local to area()
  • 32. Example– Localand Global Scope Variable "ar‟ is accessible in function showarea() because it ishaving Global Scope
  • 33. Thisdeclaration “global count” is necessaryfor usingglobal variables in function, other wise an error “local variable 'count' referenced before assignment” will appear becauselocal scope will create variable “count” and it will be found unassigned
  • 34. Lifetime of Variable  Isthe time for whicha variable livesinmemory.  For Global variables the lifetime isentire program run i.e. aslong asprogram isexecuting. • For Local variables lifetime is their function‟s run i.e. as long as function isexecuting.
  • 35. NameResolution(ScopeResolution)  Forevery nameusedwithin program python follows nameresolutionrules knownasLEGB rule.  (i) LOCAL : first check whether name is in local environment, if yes Python uses its value otherwise moves to (ii)  (ii) ENCLOSING ENVIRONMENT: if not in local, Python checks whether name is in Enclosing Environment,if yes Python uses its value otherwise moves to (iii)  GLOBAL ENVIRONMENT: if not in above scope Python checks it in Global environment, if yes Python uses itotherwise moves to (iv)  BUILT-IN ENVIRONMENT: if not in above scope, Python checks it in built-in environment, if yes, Python uses its value otherwise Python would reportthe error:  name<variable> notdefined
  • 36. Predict the output Programwith variable “value” in both LOCALand GLOBALSCOPE
  • 37. Predict the output Programwith variable “value” in both LOCALand GLOBALSCOPE
  • 38. Predict the output UsingGLOBAL variable “value” in local scope
  • 39. Predict the output UsingGLOBAL variable “value” in local scope
  • 40. Predict the output Variable “value” neither in local nor global scope
  • 41. Predict the output Variable “value” neither in local nor global scope
  • 42. Predict the output Variable in Global notin Local (input in variable at global scope)
  • 43. Predict the output Variable in Global notin Local (input in variable at global scope)
  • 46. Mutability/Immutability of Arguments/Parameters and function call  Fromthe previous example we can recall the concept learned in classXI that Python variables are not storage containers, rather Python variables are like memory references, they refer to memory address where the value is stored, thus any change in immutable type data will also change the memory address. So any change to formal argument will not reflect back to its corresponding actual argument and in case of mutable type, any change in mutable type will not change thememory address of variable.
  • 47. Mutability/Immutability of Arguments/Parameters and function call Because List if Mutable type, hence any change in formal argument myList will not change the memory address, So changes done tomyListwill be reflectedback to List1. Howeverif weformalargumentisassignedtosomeothervariableordatatype then linkwillbreakandchangeswillnotreflectbacktoactualargument Forexample (if inside function updateData() we assign myList as: myList = 20 OR myList = temp
  • 48. PassingString to function  Functioncanaccept string asa parameter  As per Python, string is immutable type, so function can access the value of string but cannotalter the string  T o modify string, the trick is to take another string and concatenate the modified value of parameter string in the newly created string.
  • 49. Passing string tofunction and counthow many vowels in it
  • 51. Program toJumblethegiven string by passing itto functionusing temporary string
  • 52. PassingListto function  We canalso passListto any function asparameter  Dueto the mutable nature of List,function canalter the list of valuesin place.  It ismostlyusedin data structurelike sorting, stack, queue etc.
  • 53. Passing list tofunction,and just double each value
  • 54. Passinglist to functionto double the odd valuesand half the even values
  • 55. Passingnested list to function and print all thosevalues whichare at diagonal position in the form of matrix
  • 56. Passinglist to functionto calculate sumand average of all numbersand return it in the form of tuple
  • 57. Passinglist to functionto calculate sumand average of all numbersand return it in the form of tuple
  • 58. Passingtuples to function  We can also passtuples to function as parameter  Dueto its immutability nature, function can only access the values of tuples but cannot modify it.
  • 59. Creating a login program with the help of passing tuple to function
  • 60. Creating a login program with the help of passing tuple to function OUTPUTOFPREVIOUSPROGRAM
  • 61. Input n numbers in tuple and pass it function to count howmanyevenand odd numbersare entered.
  • 62. Input n numbers in tuple and pass it function to count howmanyevenand odd numbersare entered.
  • 63. PassingDictionary to function  Pythonalso allows usto passdictionaries to function  Dueto its mutability nature,function canalter the keysor values of dictionary in place  Letusseefew examples of howto passdictionary to functions.
  • 64. P assing dictionary to function with list and stores the value of list as key and its frequency or no. of occurrenceasvalue
  • 65. Passingdictionary to function with keyand value, and update value at that key in dictionary
  • 66. Passingdictionary to function with keyand value, and update value at that key in dictionary