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

PPTX
04. WORKING WITH FUNCTIONS-2 (1).pptx
PPTX
functions new.pptx
PPTX
FUNCTION CPU
PDF
functions notes.pdf python functions and opp
PDF
FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM)
PDF
Chapter 11 Function
PPTX
Learn more about the concepts Functions of Python
PPTX
Working with functions the minumum ppt.pptx
04. WORKING WITH FUNCTIONS-2 (1).pptx
functions new.pptx
FUNCTION CPU
functions notes.pdf python functions and opp
FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM)
Chapter 11 Function
Learn more about the concepts Functions of Python
Working with functions the minumum ppt.pptx

Similar to FUNCTIONS.pptx (20)

PPTX
Scope of Variables.pptx
PPTX
Presentation1.pptx
PPTX
use of Functions to write python program.pptx
PPTX
Chapter One Function.pptx
PPTX
scopeofvariables in pyuthon using va.pptx
PPTX
11_Functions_Introduction.pptx javascript notes
PDF
VIT351 Software Development VI Unit1
PPTX
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
PDF
Functions in Python.pdfnsjiwshkwijjahuwjwjw
PPTX
Operator Overloading and Scope of Variable
PPT
chapterintroductiontomodularprogramming-230112092330-e3eb5a74 (1).ppt
PPT
Chapter Introduction to Modular Programming.ppt
PPTX
Mastering Python lesson 4_functions_parameters_arguments
PPTX
FUNCTIONengineeringtechnologyslidesh.pptx
PPTX
FUNCTION.pptxfkrdutytrtttrrtttttttttttttt
PPTX
Functions in C
PPT
Functions in c
PPTX
function of C.pptx
PDF
Dive into Python Functions Fundamental Concepts.pdf
PPT
Basic information of function in cpu
Scope of Variables.pptx
Presentation1.pptx
use of Functions to write python program.pptx
Chapter One Function.pptx
scopeofvariables in pyuthon using va.pptx
11_Functions_Introduction.pptx javascript notes
VIT351 Software Development VI Unit1
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
Functions in Python.pdfnsjiwshkwijjahuwjwjw
Operator Overloading and Scope of Variable
chapterintroductiontomodularprogramming-230112092330-e3eb5a74 (1).ppt
Chapter Introduction to Modular Programming.ppt
Mastering Python lesson 4_functions_parameters_arguments
FUNCTIONengineeringtechnologyslidesh.pptx
FUNCTION.pptxfkrdutytrtttrrtttttttttttttt
Functions in C
Functions in c
function of C.pptx
Dive into Python Functions Fundamental Concepts.pdf
Basic information of function in cpu
Ad

Recently uploaded (20)

PPTX
UNIT-1 - COAL BASED THERMAL POWER PLANTS
PDF
Digital Logic Computer Design lecture notes
PPT
CRASH COURSE IN ALTERNATIVE PLUMBING CLASS
PPTX
Internet of Things (IOT) - A guide to understanding
PPT
Project quality management in manufacturing
PPTX
OOP with Java - Java Introduction (Basics)
PPTX
CH1 Production IntroductoryConcepts.pptx
PDF
Well-logging-methods_new................
PPTX
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
PDF
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
PPTX
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
PPTX
Foundation to blockchain - A guide to Blockchain Tech
PDF
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
PPTX
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
PDF
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
PPTX
Recipes for Real Time Voice AI WebRTC, SLMs and Open Source Software.pptx
PDF
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
PDF
Automation-in-Manufacturing-Chapter-Introduction.pdf
PPTX
CYBER-CRIMES AND SECURITY A guide to understanding
PDF
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
UNIT-1 - COAL BASED THERMAL POWER PLANTS
Digital Logic Computer Design lecture notes
CRASH COURSE IN ALTERNATIVE PLUMBING CLASS
Internet of Things (IOT) - A guide to understanding
Project quality management in manufacturing
OOP with Java - Java Introduction (Basics)
CH1 Production IntroductoryConcepts.pptx
Well-logging-methods_new................
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
Foundation to blockchain - A guide to Blockchain Tech
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
Recipes for Real Time Voice AI WebRTC, SLMs and Open Source Software.pptx
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
Automation-in-Manufacturing-Chapter-Introduction.pdf
CYBER-CRIMES AND SECURITY A guide to understanding
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
Ad

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