◻ Large programsare often difficult to manage, thus
large programs are divided into smaller units known as
functions.
◻ It is simply a group of statements under any name i.e.
function name and can be invoked (call) from other part
of program.
◻ Take an example of School Management Software, now
this software will contain various tasks like Registering
student,Feecollection, Library book issue, TCgeneration,
Result Declaration etc. In this case we have to create
different functions for each task to manage the
software development.
Introduction
2 04. WORKING WITH FUNCTIONS-2 - 18 July 2025
3.
Introduction
◻ Set offunctions is stored in a file called MODULE.
And this approach is known as MODULARIZATION,
makes program easier to understand, test and
maintain.
◻ Commonlyusedmodulesthat contain source code for
generic need are called LIBRARIES.
◻ Modules contains set of functions. Functions is of
mainly two types:
🞑
Built-in Functions
🞑
User-Defined Functions
3 04. WORKING WITH FUNCTIONS-2 - 18 July 2025
4.
Advantages of Function
◻PROGRAMHANDLINGEASIER: only small part of the
program is dealt with at a time.
◻ REDUCEDLoC: as with function the common set of code
is written only once and can be called from any part of
program, so it reducesLine of Code
◻ EASYUPDATING : if function is not used then set of
codeisto 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
haveto makechangesto only one location.
4 04. WORKING WITH FUNCTIONS-2 - 18 July 2025
5.
User Defined Functions
◻A function is a set of statements that performsa 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([comma separated list of parameters]):
statements… .
statements… .
KEYWORD FUNCTION DEFINITION
5 04. WORKING WITH FUNCTIONS-2 - 18 July 2025
6.
P
oints to remember…
◻Keyword def marks the start of function header
◻ Function name must be unique and follows naming rules
same as for identifiers
◻ Function can take arguments. It is optional
◻ A colon(:) to mark the end of function header
◻ Function can contains one or more statement to perform
specific task
◻ Anoptional returnstatementto return a value from the
function.
◻ Function must be called/invoked to execute its code
6 04. WORKING WITH FUNCTIONS-2 - 18 July 2025
7.
User Defined functioncan be….
1. Function with no arguments and no return
2. Function with arguments but no return value
3. Function with arguments and return value
4. Function with no argument but return value
Let usunderstand each of the function type with
example….
7 04. WORKING WITH FUNCTIONS-2 - 18 July 2025
8.
Functionwith no argumentand no return
◻ This type of function is also known as void function
FUNCTION NAME NO P
ARAMETE
R,HENCEVOID
R
eturnkeyword not used
FUNCTION CALLING, IT WILL INVOKE welcome() TO PERFORMITSACTION
8 04. WORKING WITH FUNCTIONS-2 - 18 July 2025
9.
Function with parametersbut no return value
◻ P
arameters are given in the parenthesis separated
by comma.
◻ Values are passed for the parameter at the time of
function calling.
9 04. WORKING WITH FUNCTIONS-2 - 18 July 2025
Function with parameterand return
◻ We can return values from function using return
keyword.
◻ The return value must be used at the calling place
by –
■Either store it any variable
■Use with print()
■Use in any expression
11 04. WORKING WITH FUNCTIONS-2 - 18 July 2025
Function with return
NOT
E
:the return statement ends
a function execution even if it is
in the middle of function.
Anything written below return
statement will become
unreachable code.
def max(x,y):
if x>y:
return x
else:
return y
print(“Iam not reachable”)
13 04. WORKING WITH FUNCTIONS-2 - 18 July 2025
14.
Function not returningvalue
◻ Function may or may not return a value. Non returning function
is also known as VOID function. It may or may not contain
return. If it containreturn statementthenit will be in the form
of:
🞑
return [no value after return]
14 04. WORKING WITH FUNCTIONS-2 - 18 July 2025
15.
P
arametersand Arguments inFunction
◻ Parameters are the value(s) provided in the parenthesis when
we write function header. These are the values required by
function to work
◻ If there are more than one parameter, it must be separated by
comma(,)
◻ An Argument is a value that is passedto the function when it is
called. In other words arguments are the value(s) provided in
function call/invoke statement
◻ ParameterisalsoknownasFORMAL ARGUMENTS/PARAMETERS
ACTUAL
◻ Arguments is also known as
ARGUMENTS/PARAMETER
◻ Note: Function can alter only MUTABLETYPEvalues.
15 04. WORKING WITH FUNCTIONS-2 - 18 July 2025
16.
Example of Formal/ActualArguments
ACTUALARGUMENT
FORMALARGUMENT
16 04. WORKING WITH FUNCTIONS-2 - 18 July 2025
17.
T
ypes of Arguments
◻There are 4 types of Actual Argumentsallowed in
Python:
1. P
ositional arguments
2. Default arguments
3. Keyword arguments
4. Variable length arguments
17 04. WORKING WITH FUNCTIONS-2 - 18 July 2025
18.
P
ositional arguments
◻ Areargumentspassed to a function in correct
positional order
◻ Here x is passed to a and y is passed to b i.e. in the
order of their position
18 04. WORKING WITH FUNCTIONS-2 - 18 July 2025
19.
If the numberofformalargumentandactual differs thenPython
will raise anerror
19 04. WORKING WITH FUNCTIONS-2 - 18 July 2025
20.
Default arguments
◻ Sometimeswe can provide default values for our
positional arguments. In this case if we are not
passing any value then default values will be
considered.
◻ Default argument must not followed 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
20 04. WORKING WITH FUNCTIONS-2 - 18 July 2025
Keyword(Named) Arguments
◻ Thedefault 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.
◻ Toget control and flexibility over the values sent as
arguments, python offers KEYWORD ARGUMENTS.
◻ This allows to call function with arguments in any
order using name of the arguments.
23 04. WORKING WITH FUNCTIONS-2 - 18 July 2025
Rules for combiningall three type of arguments
◻ An argument list must first contain positional
arguments followed by keyword arguments
◻ Keyword arguments should be taken from the
required arguments
◻ You cannot specify a value for an argument more
than once
25 04. WORKING WITH FUNCTIONS-2 - 18 July 2025
26.
R
eturning Multiple values
◻Unlike other programming languages, python lets
you return more than one value from function.
◻ The multiple return value must be either stored in
TUPLEor wecanUNPACKthereceived value by
specifying the same number of variables on the left
of assignment of function call.
◻ Let ussee an example of both :-
26 04. WORKING WITH FUNCTIONS-2 - 18 July 2025
Multiple return valuestored by
unpacking in multiple variables
28 04. WORKING WITH FUNCTIONS-2 - 18 July 2025
29.
Composition
◻ R
efers tousing an expression as a part of large
large
expression, or a statement as a part of
statement.
◻ Examples
# Arithmetic
# Logical
🞑
Max((a+b),(c+a))
🞑
Prize(Card or
Cash)
🞑
name="Vikram“
🞑
print(name.replace("m","nt").upper()) #function
29 04. WORKING WITH FUNCTIONS-2 - 18 July 2025
30.
Scope of Variables
◻SCOPEmeansin which part(s) of the program, a
particular piece of code or data is accessible or
known.
◻ In Python there are broadly 2 kinds of Scopes:
🞑
Global Scope
🞑
Local Scope
30 04. WORKING WITH FUNCTIONS-2 - 18 July 2025
31.
Global Scope
◻ Aname declared in top level segment( main ) of
a program is said to have global scope and can be
used in entire program.
◻ Variable defined outside all functions are global
variables.
31 04. WORKING WITH FUNCTIONS-2 - 18 July 2025
32.
Local Scope
◻ Aname declare in a function body is said to have
local scope i.e. it can be used only within this
function and the other block inside the function.
◻ The formal parameters are also having local scope.
◻ Let usunderstand with example… .
32 04. WORKING WITH FUNCTIONS-2 - 18 July 2025
33.
Example – Localand Global Scope
33 04. WORKING WITH FUNCTIONS-2 - 18 July 2025
34.
VINOD KUMARVERMA, PGT(CS),KV OEFKANPUR&
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
Example – Local and Global Scope
„a‟ is not accessible
here becauseit is
declared in function
area(), so scope is
local to area()
34 04. WORKING WITH FUNCTIONS-2 - 18 July 2025
35.
Example – Localand Global Scope
Variable „ar‟ is accessible in
function showarea() because
it is having Global Scope
35 04. WORKING WITH FUNCTIONS-2 - 18 July 2025
36.
This declaration “globalcount” is
necessary for using global
variables in function, other wise an
error “local variable 'count'
referenced before assignment”
will appear because local scope
will create variable “count” and it
will be found unassigned
36 04. WORKING WITH FUNCTIONS-2 - 18 July 2025
37.
Lifetime of Variable
◻Is the time for which a variable lives in memory. For
Global variables the lifetime isentire program run
i.e. as long as program is executing. For Local
variables lifetime is their function‟s run i.e. as long
as function is executing.
37 04. WORKING WITH FUNCTIONS-2 - 18 July 2025
38.
Name Resolution (ScopeResolution)
◻ For every name used within program python follows name resolution rules
known as LEGBrule.
◻ (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 it otherwise moves to (iv)
◻ BUILT-INENVIRONMENT:if not in above scope,Python checksit in built-
in environment, if yes, Python uses its value otherwise Python would
report the error:
◻ name <variable> not defined
38 04. WORKING WITH FUNCTIONS-2 - 18 July 2025
Predict the output
UsingGLOBAL
variable “value” in
local scope
41 04. WORKING WITH FUNCTIONS-2 - 18 July 2025
42.
Predict the output
UsingGLOBAL
variable “value” in
local scope
42 04. WORKING WITH FUNCTIONS-2 - 18 July 2025
43.
Predict the output
Variable“value”
neither in local nor
global scope
43 04. WORKING WITH FUNCTIONS-2 - 18 July 2025
44.
VINOD KUMARVERMA, PGT(CS),KV OEFKANPUR&
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
Predict the output
Variable “value”
neither in local nor
global scope
44 04. WORKING WITH FUNCTIONS-2 - 18 July 2025
45.
Predict the output
Variablein Global
not in Local
(input in variable at
global scope)
45 04. WORKING WITH FUNCTIONS-2 - 18 July 2025
46.
Predict the output
Variablein Global
not in Local
(input in variable at
global scope)
46 04. WORKING WITH FUNCTIONS-2 - 18 July 2025
Mutability/Immutability of Arguments/
Parametersandfunction call
◻ From the previous example we can recall the
concept learned in class XI 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 the memory address of variable.
49 04. WORKING WITH FUNCTIONS-2 - 18 July 2025
50.
Mutability/Immutability of Arguments/
Parametersandfunction call
Because List if Mutable type, hence any change in formal
argument myList will not change the memory address, So
changes done to myList will be reflected back to List1.
However if we formal argument is assigned to some other variable or data type
thenlinkwill break andchangeswill notreflect back to actual argument
Forexample (if inside function updateData() we assign myList as:
myList = 20 OR myList = temp
50 04. WORKING WITH FUNCTIONS-2 - 18 July 2025
51.
P
assing String tofunction
◻ Function can accept string as a parameter
◻ As per Python, string is immutable type, so function
can access the value of string but cannot alter the
string
◻ To modify string, the trick is to take another string
and concatenate the modified value of parameter
string in the newly created string.
◻ Let us see few examples of passing string to
function…
51 04. WORKING WITH FUNCTIONS-2 - 18 July 2025
52.
Passingstring to functionand counthow
many vowels in it
52 04. WORKING WITH FUNCTIONS-2 - 18 July 2025
53.
Program to counthow many timesany
character ispresent in string
53 04. WORKING WITH FUNCTIONS-2 - 18 July 2025
54.
Program to Jumblethe given string by passing
it to function using temporary string
54 04. WORKING WITH FUNCTIONS-2 - 18 July 2025
55.
P
assing List tofunction
◻ We can also passList to any function as parameter
◻ Due to the mutable nature of List, function can alter
the list of values in place.
◻ It is mostly used in data structure like sorting, stack,
queue etc.
◻ Let ussee how to passList to function by few
examples:
55 04. WORKING WITH FUNCTIONS-2 - 18 July 2025
56.
P
assing list tofunction, and just
double each value
56 04. WORKING WITH FUNCTIONS-2 - 18 July 2025
57.
P
assing list tofunction to double the
odd values and half the even values
57 04. WORKING WITH FUNCTIONS-2 - 18 July 2025
58.
Passingnested list tofunction and print all those values
which are at diagonal position in the form of matrix
58 04. WORKING WITH FUNCTIONS-2 - 18 July 2025
59.
Passinglist to functionto calculate sumand average of all
numbers and return it in the form of tuple
59 04. WORKING WITH FUNCTIONS-2 - 18 July 2025
60.
Passinglist to functionto calculate sumand average of all
numbers and return it in the form of tuple
60 04. WORKING WITH FUNCTIONS-2 - 18 July 2025
61.
P
assing tuples tofunction
◻ We can also pass tuples to function as parameter
◻ Due to its immutability nature, function can only
access the values of tuples but cannot modify it.
◻ Let us see how to pass tuples in function by few
example…
61 04. WORKING WITH FUNCTIONS-2 - 18 July 2025
62.
Input n numbersin tuple and pass it function to count
how many even and odd numbersare entered.
62 04. WORKING WITH FUNCTIONS-2 - 18 July 2025
63.
Input n numbersin tuple and pass it function to count
how many even and odd numbersare entered.
63 04. WORKING WITH FUNCTIONS-2 - 18 July 2025
64.
Creating a loginprogram with the help of
passing tuple to function
64 04. WORKING WITH FUNCTIONS-2 - 18 July 2025
65.
Creating a loginprogram with the help of
passing tuple to function
OUTPUTOF PREVIOUSPROGRAM
65 04. WORKING WITH FUNCTIONS-2 - 18 July 2025
66.
P
assing Dictionary tofunction
◻ Python also allows usto passdictionaries to function
◻ Due to its mutability nature, function can alter the
keys or values of dictionary in place
◻ Let ussee few examples of how to pass dictionary
to functions.
66 04. WORKING WITH FUNCTIONS-2 - 18 July 2025
67.
P
assing dictionary tofunction with list and stores the
value of list as key and its frequency or no. of
occurrence as value
67 04. WORKING WITH FUNCTIONS-2 - 18 July 2025
68.
Passing dictionary tofunction with key and value,
and update value at that key in dictionary
68 04. WORKING WITH FUNCTIONS-2 - 18 July 2025
69.
Passing dictionary tofunction with key and value,
and update value at that key in dictionary
69 04. WORKING WITH FUNCTIONS-2 - 18 July 2025
70.
Understanding of main()function in Python
◻ By default every program starts their execution
from main() function. In Python including a main()
function is not mandatory. It can structure our Python
in a logical way that puts
components of the program
the most
in one
programs
important
function.
◻ We can get the name of current module executing
by using built-in variable name (2 underscore
before and after of name)
70 04. WORKING WITH FUNCTIONS-2 - 18 July 2025
71.
Understanding of main()function in Python
We can observe, by default the name of module will be main
Most non-python
programmers are having the
habit of writing main()
functionwheretheimportant
and starter code of programs
are written. In Python we can
also create main() and call it
by checking name to
main and then call any
function, in this case main()
71 04. WORKING WITH FUNCTIONS-2 - 18 July 2025
72.
Questions based onfunctions
◻ WAP to create function Lsearch() which takes List
and number to search and return the position of
number in list using Linear Searching method
◻ WAP to create function Bsearch() which takes List
and number to search and return the position of
number in list using Binary Searching method
◻ What is the difference between Local and Global
variables? Also give suitable Python code to
illustrate both
72 04. WORKING WITH FUNCTIONS-2 - 18 July 2025