SlideShare a Scribd company logo
Python - Functions
Introduction
• Large program is broken into smaller units known as
functions.
• Functions are named blocks of code that are designed to
do specific job.
• Can be executed by calling the function name
• makes your programs easier to write, read, test, and fix
errors.
Points to be remembered while defining a function
• Function blocks begin with the keyword “def” followed by
function name and parenthesis ().
• Any input parameters or arguments should be placed
within these parentheses when you define a function.
• The code block always comes after a colon (:) and is
indented.
• The statement “return [expression]” exits a function,
optionally passing back an expression to the caller. A “return”
with no arguments is the same as return None.
Eg:
def hello():
print (“hello - Python”)
return
Eg:
def calc (x):
r=2*x**2
return r
Types of Functions
Functions Description
User-defined functions Functions defined by the users
themselves.
Built-in functions Functions that are inbuilt with in
Python. Eg. print()
Functions defined in Functions pre-defined in particular
module and can be used only if
corresponding module is imported.
Eg: for sin() , import math
Lambda functions Functions that are anonymous un-
named function.
Recursion functions Functions that calls itself is known
Advantages of User-defined Functions
1. Functions help us to divide a program into modules. This
makes the code easier to manage.
2. It implements code reuse. Simply call the function to
execute a sequence of statements for multiple times.
3. Functionality can be modified easily. Also different
programmers can use various functions. (Code sharing)
Function Arguments
1. Positional or Required arguments :
- the number of values (arguments) in the function call should match
exactly with the number of values (parameters) in the function definition.
Eg:
def printstring(str):
print (str)
return
printstring()
TypeError: printstring() missing 1 required positional argument: 'str'
Eg:
def printstring(str):
print (str)
return
printstring(‘Welcome’)
Instead of printstring() in the above code if we use printstring (“Welcome”)
Output:
Welcome
- also, arguments that are passed to a function in correct positional order. ie.
the first parameter receives the value of the first argument, second to
second, and so on.
Function Arguments
3 Default Arguments
- an argument that takes a default value if no value is provided in the
function call statement. The default values are specified in the function
header statement.
Eg:
def printinfo( name, salary = 13500):
print (“Name: “, name)
print (“Salary: “, salary)
return
printinfo(“Mani”)
printinfo(“Mani”,12000)
Output:
Name: Mani
Salary: 13500
Name: Mani
Salary: 12000
Eg:
def printdata (name, age=25):
print ("Name :",name)
print ("Age :",age)
return
printdata ("Guhan")
Output:
Name: Guhan
Age:25
Function Arguments
2. Keyword Arguments:
- Keyword arguments will invoke the function after the parameters
are recognized by their argument names.
- The value of the keyword argument is matched with the parameter
name and so, one can also put arguments in improper order (not in order).
Note: TypeError: printdata() got an unexpected keyword argument 'name1'
def printdata (name, age):
print ("Name :",name)
print ("Age :",age)
return
printdata (age=25, name1="Guhan")
Output:
Name:Guhan
Age:25
def printdata (name, age):
print ("Name :",name)
print ("Age :",age)
return
printdata (age=25, name="Guhan")
Function Arguments
4. Variable-Length Arguments:
In Variable Length arguments we can pass the arguments using two
methods.
1. Non keyword variable arguments (tuples)
2. Keyword variable arguments
Using multiple argument types together
Rules for combining all three types of arguments:
• An argument list must first contain required arguments followed by
keyword arguments.
• Keyword arguments should be taken from the required arg.
• You cannot specify a value for an argument more than once.
def interest(prin,cc,time=2,rate=0.09):
return prin*time*rate
Interest(prin=3000,cc=5)
Interest(rate=0.12,prin=5000,cc=4)
Interest(cc=4,rate=0.12,prin=5000)
Interest(5000,3,rate=0.05)
Interest(rate=0.05,5000,3)
Interest(5000,print=300,cc=2)
Interest(500,time=2,rate=0.05)
legal
legal
legal
legal
Not legal
Not legal
Not legal
Structure of a Python program
Generally all function definitions are given at the top followed by other
statements which are not indented.
These statements are called as ‘Top-level statements’.
The execution of a python programs starts always from the top-level
statements.
Python gives a name to top-level program as “__main__”
Python stores this name in a built-in variable called “ __name__”
print(__name__)
Output: __main__
def function():
def function():
def function():
# top-level statements
statement-1
statement 2
…
Example:
def fun1():
print(“hello”)
# top-level statements (or) __main__
print(“top-level statements”)
fun1()
Flow of execution in a function call
def sum(x,y)
what is this statement called as ?
The flow of execution refers to the order in which statements are
executed during a program run by the python interpreter.
What is a block? A block is a piece of python program text that is
executed as a unit.
Yes, it is a function header statement.
Ok. Now, how will you call this function that executes it?
sum(a,b)
A function body is a also a block which is executed by creating an execution
frame and when control is transferred inside an execution frame, the
statements in the function body is executed.
At the end of execution of a function, the function returns the control to
the caller program.
Flow of execution in a function call
An execution frame contains:
• administrative information for debugging.
• Name of the function
• Values passed to the function
• Local variable created within function
• Information for next instruction to be executed.
Flow of execution in a function call
def function():
…
return
# __main__
…
func():
print(…)
def sum(x,y):
z=x+y
print(z)
return
Python begins its execution with first line of __main__ segment.
Initially the execution of def function ignored until called.
# __main__
n1=float(input("enter first number"))
n2=float(input("enter second number"))
sum(n1,n2)
print(“control sent back to the caller-exec.over)
Example:
The entire program is executed as follows;
main.1main.2main.3sum.1()sum.2 sum.3 sum.4
main.4
Example:
def sum(x,y):
s=x+y
return s
# __main__
n1=float(input("enter first number"))
n2=float(input("enter second number"))
res=sum(n1,n2)
print("sum of {} and {} is:".format(n1,n2),res)
The entire program is executed as follows;
main.1main.2main.3sum.1()sum.2 sum.3 main.3 
main.4
Guidelines that python follows to a program:
• Execution always begin with first line of __main__
• Ignore all comment lines and executes non-blank lines.
• Python interpreter executes the function header(def function) line to
determine for proper header function and skips all other statements in the
function body.
• The lines of function body are not executed until it is called.
• If a function contain any inner function, and it is not executed until the
outer function is called.
• Python first jumps to the function header line, as soon as the call
statement is executed and then executes all other lines in the function
body.
• A function terminated with the execution of return or last line of the
function body, whichever occurs earlier.
• If a called function returns a value like return<variable/value/expression>,
then the control is jumped to the function call where it completely
replaces with return value and completes it.
• If the function does not return any value, then the control jumps back to
the line following the function call statement.
Example:
1. def sum(x,y):
2. s=x+y
3. return s
4. #__main__
5. n1=float(input("enter first number"))
6. n2=float(input("enter second number"))
7. res=sum(n1,n2) s3
8. print("sum of {} and {} is:{}".format(n1,n2,res))
When tracing the above program, the flow of execution as follows:
1 56712378
2. void function: If a function does not return any value, then it is
called void function but may or may not have return statement.
Eg
def greet():
print(“hello world”)
greet()
Eg:
def sum(x,y):
s=x+y
print(s)
return
sum(5,6)
Note: void function do not return any value but return ‘None’ to its
caller.
def greet():
print(“hello”)
print(greet())
def greet():
return(“hello”)
print(greet())
Output:
hello
None
# greet() function return ‘None’ and so it is printed
Output:
hello
Note : greet() function return ‘hello’ and so it is printed
Returning values from functions::
• Function returning some value (non void)
• Function not returning any value(void)
1. Non void function: a literal eg return a / a variable eg. return 5/ an
expression eg. return (x+y)
def sum(x,y):
s=x+y
return s
result= sum(5,3)
Note: sum(5,3) is replaced with 8
Ie. result=8
Returning values from functions::
add_result=sum(a,b)  return value is used in assignment statement
print(sum(3,4))  return value is used in print statement
sum(4,5) > 6  return value used in relational expression.
Note: if the return value is not used, python will not report any error
but the return value is completely wasted.
Four possible combination of functions:
1. Non –void function without any arg
2. Non-void function with some arg
3. Void function without arg
4. Void function with some arg.
Practice Questions:
Write a non-function that returns a value without args.
def sum():
n1,n2=int(input("enter first no.")),int(input("enter second no."))
return(n1+n2)
print("sum=",sum())
Practice Questions:
Write a non-function that returns with args.
def sum(a,b):
return(n1+n2)
n1,n2=int(input("enter first no.")),int(input("enter second no."))
print("sum=",sum(n1,n2))
Practice Questions:
Write a void function that adds two numbers without args.
def sum():
n1,n2=int(input("enter first no.")),int(input("enter second no."))
print(n1+n2)
sum()
Practice Questions:
Write a void function that adds two numbers with some args.
def sum(a,b):
print("sum=",a+b)
n1,n2=int(input("enter first no.")),int(input("enter second no."))
sum(n1,n2)
Returning multiple values must ensure the following;
(i) Return <value1/variable1/exp1>, <value2/variable2/exp2>, …
(ii) Function call statment should receive or use of the following
form:
(a) either receive the returned values in the form of tuple
variable
(b) or by specifying same number of variables on the left-
hand side of the assignment in fucntion call by directly unpacking
the tuple.
# function call receiving as tuple:
def max_min(a):
return (max(a),min(a))
list1=[34,-56,3,-7,23,10,8,-2]
rt=max_min(list1)
print('maximum:{} and minimum:{}'.format(rt[0],rt[1]))
Note the here the function returns comma separated multiple values
and therefore ‘t’ is a tuple type. (packing)
Write a function that returns comma separated values:
# fucntion call directly unpacking the tuple.
def max_min(a):
t=max(a),min(a)
return t
list1=[34,-56,3,-7,23,10,8,-2]
ma,mi=max_min(list1)
print('maximum:{} and minimum:{}'.format(ma,mi))
Note: received values are in the form of two different variables not
as tuple. (unpacking)
Write a function that returns a tuple:
import math
try:
def fu(a):
print(int(math.sqrt(a)))
fun('36')
except NameError:
print("Function name error")
except TypeError:
print("type mismatch")
else:
print("no exception")
Write a program to handle an exception raised due to inappropriate
#argument passed/function call
What is the possible outcome/s of following code
import random
colors=['red','green','yellow','blue','orange','violet']
print(colors[random.randint(3,5)])
Possible options:
a) green b) yellow c) blue d) violet
What is the purpose of the "return" statement in a function?
a) It specifies the type of the function.
b) It defines the input parameters of the function.
c) It indicates the end of a function.
d) It returns a value from the function to the caller.
Which of the following function header is correct?
a) def cal_si(p=100, r, t=2)
b) def cal_si(p=100, r=8, t)
c) def cal_si(p, r=8, t=2)
d) def cal_si(p, r=8, t)
Which of the following components are part of a function header in
Python?
a) Return Statement
b) Function Name
c) Parameter List
d) Both b and c
Consider the code given below: Which of the following
statements should be given in the blank for #Missing
Statement, if the output produced is 110?
b=100
def fun(a):
…………………
b=b+a
print(a,b)
fun(b)
print(b)
a) global a
b) global b=100
c) global b
d) global a=100
import random
low=25
point=5
for i in range(1,5):
number=low+random.randint(0,point)
print(number,end=" : ")
point-=1;
print()
What are the possible output/s for the following code?
Output Options:
i. 29: 26:25 :28 : ii. 24: 28:25:26: iii. 29: 26:24 :28 : iv. 29: 26:25:26:
Answer: iv)
import random
limit=4
points=100+random.randint(0,limit)
for p in range(points,99,-1):
print(p,end=" # ")
print()
What are the possible outcome/s for the following code:
Output Options:
i. 103#102#101#100# ii. 100#101#102#103#
Iii. 100#101#102#103#104# iv.104#103#102#101#100#
Answer: i) and iv)
import random
AR=[20,30,40,50,60,70]
Lower=random.randint(1,3)
Upper=random.randint(2,4)
for k in range(lower, upper + 1):
print(AR[k],end=“#”)
What possible outputs(s) are expected to be displayed on
screen at the time of execution of the program from the
following code? Also specify the maximum values that can
be assigned to each of the variables Lower and Upper.
a) 10#40#70# b) 30#40#50# c) 50#60#70# d) 40#50#70#
b) & d)
18. What will be the output of the following code?
>>> def a(b=11, c=21):
b += 13; c -= 13
return b+c 0.77
>>> print(a(25), a(35))
a) 15 18 b) 46 56 c) 25 35 d) 13 12
Scope of Variables:
It refers to the part of the program, where the variable is accessible.
two types of scopes - local scope and global scope.
Local Scope :
A variable declared inside the function's body is said to have local scope is
known as local variable.
Rules of local variable:
A variable with local scope can be accessed only within the function/block that it is
created in.
• When a variable is created inside the function/block, the variable becomes local to it.
• A local variable only exists while the function is executing.
• The formal parameters are also local to function.
Note: it can be multi-level. There can be nested local scope of an inside block called
enclosed scope.
Eg:
def loc():
y=0 # local scope
print(y)
loc()
Output:
0
def loc():
y = "local”
loc()
print(y)
the output shows the following error:
NameError: name 'y' is not defined
Global Scope :
A name declared in top-level statement (__main__) of a program is said
to have a global scope and can be used anywhere in the program. It can
be created by defining a variable outside the scope of any
function/block.
Rules of global Keyword:
• When we define a variable outside a function, it’s global by default.
You don’t have to use global keyword.
• We use global keyword to modify a global variable inside a function.
• Use of global keyword outside a function has no effect
c = 1 # global variable
def add():
print(c)
add()
Output:
1
c = 1 # global variable
def add():
c = c + 2 # increment c by 2
print(c)
add()
Output: Unbound Local Error: local
variable 'c' referenced before
assignment
def gra(x,y):
ma,mi=max(x,y),min(x,y)
return ma,mi
#__main__
n1=float(input("enter first number"))
n2=float(input("enter second number"))
ma,mi=gra(n1,n2)
print("max:{} and min:{}".format(ma,mi))
1. x=5
2. def sum(y):
2. s=x+y
3. return s
4. #__main__
5. n1=float(input("enter first number"))
6. res=n1+sum(x)
8. print("sum is:”,res)
OUTPUT:
enter first number6
sum is:16.0
OUTPUT:
enter first number34
enter second number67
max:67.0 and min:34.0
Note: Refer scope examples on page: 114 – 117.
Life time of variable:
Life time of a variable is the time for which a variable lives in a memory.
Global variable – lives in memory as long as the program is running.
Local variable – lives as long as the function runs.
Name resolution (Resolving the scope of a Name:
Python follows name resolution rule, also known as LEGB rule:
(i) It checks with its local environment(LEGB) – if it has a variable with the same name. if
yes, Python uses its value otherwise, then it moves to step(ii)
(ii) Checks the enclosing environment(LEGB) – if whether there is a variable with the same
name. if yes, Python uses otherwise, python repeats this in the higher level enclosing
environment otherwise, it moves to step (iii)
(iii) Python checks the global environment(LEGB) – if there is same variable, if yes it uses
otherwise it moves to step(iv)
(iv) Python checks its Built-in environment(LEGB) – it contains all built-in variable and
functions, python checks if there is variable in same name, python uses its value
otherwise python reports an error:
name<variable> not defined.
Built-in namespace-4
Global namespace-3
Enclosed - 2
Local -1
Mutable/Immutable Properties of passed data Objects
Python variables are not storage containers, rather are like memory
references
Mutable – changeable/modifiable.
Immutable – non-modifiable.
Depending upon the mutability/immutability of its data type,
python variables behave differently.
def state(y):
y=y+5
x=10
print('address before calling:',id(x),x)
state(x)
print('address after calling:',id(x),x)
Immutable properties of passed data :
If a variable referring to an immutable type, then any change in its value will
also change its memory address it is referring to.
Output
address before calling:140734302669528 10
address after calling: 140734302669688 15
Example:
def state(a):
a[0]=10
x=[1,2]
print('address before calling:',id(x),x)
state(x)
print("address after calling:",id(x),x)
mutable properties of passed data :
If variable referring to a mutable type,then any change in its value of
mutable type will not change the memory address of the variable. The value
will change in place (change reflected), if the variable in the function is not
assigned a different variable or data type.
output:
address before calling: 2473295957824 [1, 2]
address after calling: 2473295957824 [10, 2]
Mutable/Immutable Properties of passed data Objects
Conclusion :
Changes in immutable type are not reflected in the caller
function at all.
Changes, if any, in mutable types,
• are reflected in caller function if its name is not assigned a
different variable or datatype.
• are not reflected in caller function if its name is assigned a
different variable or datatype.
Example: (refer page 129)
def fun1(list2):
print("variable list2",list2,id(list2))
new=[3,5]
list2=new
list2[0]=100
print("variable list2",list2,id(list2))
print("variable new",new,id(new))
list1=[10,20]
fun1(list1)
print("address of list1 after func.call",list1,id(list1))
mutable type of data – assigning parameter to a new variable:
Variable referring to a mutable type then any change in its value of mutable type will change the
memory address of the variable. The value will not change in place (change not reflected), if
the variable in the function is assigned a different variable or data type.
output:
variable list2 [10, 20] 2207440063744
variable list2 [100, 5] 2207396385536
variable new [100, 5] 2207396385536
address of list1 after func.call [10, 20]
2207440063744
Conclusion :
Changes in immutable type are not reflected in the caller function at all.
Changes, if any, in mutable types,
• are reflected in caller function if its name is not assigned a different variable or
datatype.
• are not reflected in caller function if its name is assigned a different variable or
datatype.

More Related Content

Similar to Working with functions.pptx. Hb. (20)

PPTX
Python Functions.pptx
AnuragBharti27
 
PDF
Functions2.pdf
prasnt1
 
PPTX
functions new.pptx
bhuvanalakshmik2
 
PPT
functions _
SwatiHans10
 
PDF
Functions in Pythons UDF and Functions Concepts
nitinaees
 
PPTX
Python programming - Functions and list and tuples
MalligaarjunanN
 
PDF
3-Python Functions.pdf in simple.........
mxdsnaps
 
PPTX
functioninpython-1.pptx
SulekhJangra
 
PPTX
Understanding Python Programming Language -Functions
elharriettm
 
PPT
Py-Slides-3 difficultpythoncoursefforbeginners.ppt
mohamedsamydeveloper
 
PPTX
Py-slides-3 easyforbeginnerspythoncourse.pptx
mohamedsamydeveloper
 
PPT
Python programming variables and comment
MalligaarjunanN
 
PPTX
Functions in python programming and its calling statement
rehna9
 
PPTX
Python_Functions_Modules_ User define Functions-
VidhyaB10
 
PPT
Powerpoint presentation for Python Functions
BalaSubramanian376976
 
PPTX
FUNCTIONS.pptx
KalashJain27
 
PPTX
functions.pptx
KavithaChekuri3
 
PPTX
UNIT 3 python.pptx
TKSanthoshRao
 
PDF
python_function.pdf
University of Economics in Katowice
 
PDF
Python_Functions.pdf
MikialeTesfamariam
 
Python Functions.pptx
AnuragBharti27
 
Functions2.pdf
prasnt1
 
functions new.pptx
bhuvanalakshmik2
 
functions _
SwatiHans10
 
Functions in Pythons UDF and Functions Concepts
nitinaees
 
Python programming - Functions and list and tuples
MalligaarjunanN
 
3-Python Functions.pdf in simple.........
mxdsnaps
 
functioninpython-1.pptx
SulekhJangra
 
Understanding Python Programming Language -Functions
elharriettm
 
Py-Slides-3 difficultpythoncoursefforbeginners.ppt
mohamedsamydeveloper
 
Py-slides-3 easyforbeginnerspythoncourse.pptx
mohamedsamydeveloper
 
Python programming variables and comment
MalligaarjunanN
 
Functions in python programming and its calling statement
rehna9
 
Python_Functions_Modules_ User define Functions-
VidhyaB10
 
Powerpoint presentation for Python Functions
BalaSubramanian376976
 
FUNCTIONS.pptx
KalashJain27
 
functions.pptx
KavithaChekuri3
 
UNIT 3 python.pptx
TKSanthoshRao
 
Python_Functions.pdf
MikialeTesfamariam
 

Recently uploaded (20)

PDF
LAW OF CONTRACT ( 5 YEAR LLB & UNITARY LLB)- MODULE-3 - LEARN THROUGH PICTURE
APARNA T SHAIL KUMAR
 
PDF
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 
PDF
CEREBRAL PALSY: NURSING MANAGEMENT .pdf
PRADEEP ABOTHU
 
PDF
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
PPTX
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 
PPTX
How to Set Maximum Difference Odoo 18 POS
Celine George
 
PDF
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
PPTX
2025 Winter SWAYAM NPTEL & A Student.pptx
Utsav Yagnik
 
PPTX
Unit 2 COMMERCIAL BANKING, Corporate banking.pptx
AnubalaSuresh1
 
PDF
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
PDF
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
PDF
SSHS-2025-PKLP_Quarter-1-Dr.-Kerby-Alvarez.pdf
AishahSangcopan1
 
PPTX
MENINGITIS: NURSING MANAGEMENT, BACTERIAL MENINGITIS, VIRAL MENINGITIS.pptx
PRADEEP ABOTHU
 
PPT
Talk on Critical Theory, Part II, Philosophy of Social Sciences
Soraj Hongladarom
 
PPTX
PATIENT ASSIGNMENTS AND NURSING CARE RESPONSIBILITIES.pptx
PRADEEP ABOTHU
 
PDF
community health nursing question paper 2.pdf
Prince kumar
 
PDF
Generative AI: it's STILL not a robot (CIJ Summer 2025)
Paul Bradshaw
 
PDF
The dynastic history of the Chahmana.pdf
PrachiSontakke5
 
PPTX
HYDROCEPHALUS: NURSING MANAGEMENT .pptx
PRADEEP ABOTHU
 
PDF
LAW OF CONTRACT (5 YEAR LLB & UNITARY LLB )- MODULE - 1.& 2 - LEARN THROUGH P...
APARNA T SHAIL KUMAR
 
LAW OF CONTRACT ( 5 YEAR LLB & UNITARY LLB)- MODULE-3 - LEARN THROUGH PICTURE
APARNA T SHAIL KUMAR
 
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 
CEREBRAL PALSY: NURSING MANAGEMENT .pdf
PRADEEP ABOTHU
 
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 
How to Set Maximum Difference Odoo 18 POS
Celine George
 
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
2025 Winter SWAYAM NPTEL & A Student.pptx
Utsav Yagnik
 
Unit 2 COMMERCIAL BANKING, Corporate banking.pptx
AnubalaSuresh1
 
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
SSHS-2025-PKLP_Quarter-1-Dr.-Kerby-Alvarez.pdf
AishahSangcopan1
 
MENINGITIS: NURSING MANAGEMENT, BACTERIAL MENINGITIS, VIRAL MENINGITIS.pptx
PRADEEP ABOTHU
 
Talk on Critical Theory, Part II, Philosophy of Social Sciences
Soraj Hongladarom
 
PATIENT ASSIGNMENTS AND NURSING CARE RESPONSIBILITIES.pptx
PRADEEP ABOTHU
 
community health nursing question paper 2.pdf
Prince kumar
 
Generative AI: it's STILL not a robot (CIJ Summer 2025)
Paul Bradshaw
 
The dynastic history of the Chahmana.pdf
PrachiSontakke5
 
HYDROCEPHALUS: NURSING MANAGEMENT .pptx
PRADEEP ABOTHU
 
LAW OF CONTRACT (5 YEAR LLB & UNITARY LLB )- MODULE - 1.& 2 - LEARN THROUGH P...
APARNA T SHAIL KUMAR
 
Ad

Working with functions.pptx. Hb.

  • 2. Introduction • Large program is broken into smaller units known as functions. • Functions are named blocks of code that are designed to do specific job. • Can be executed by calling the function name • makes your programs easier to write, read, test, and fix errors.
  • 3. Points to be remembered while defining a function • Function blocks begin with the keyword “def” followed by function name and parenthesis (). • Any input parameters or arguments should be placed within these parentheses when you define a function. • The code block always comes after a colon (:) and is indented. • The statement “return [expression]” exits a function, optionally passing back an expression to the caller. A “return” with no arguments is the same as return None. Eg: def hello(): print (“hello - Python”) return Eg: def calc (x): r=2*x**2 return r
  • 4. Types of Functions Functions Description User-defined functions Functions defined by the users themselves. Built-in functions Functions that are inbuilt with in Python. Eg. print() Functions defined in Functions pre-defined in particular module and can be used only if corresponding module is imported. Eg: for sin() , import math Lambda functions Functions that are anonymous un- named function. Recursion functions Functions that calls itself is known
  • 5. Advantages of User-defined Functions 1. Functions help us to divide a program into modules. This makes the code easier to manage. 2. It implements code reuse. Simply call the function to execute a sequence of statements for multiple times. 3. Functionality can be modified easily. Also different programmers can use various functions. (Code sharing)
  • 6. Function Arguments 1. Positional or Required arguments : - the number of values (arguments) in the function call should match exactly with the number of values (parameters) in the function definition. Eg: def printstring(str): print (str) return printstring() TypeError: printstring() missing 1 required positional argument: 'str' Eg: def printstring(str): print (str) return printstring(‘Welcome’) Instead of printstring() in the above code if we use printstring (“Welcome”) Output: Welcome - also, arguments that are passed to a function in correct positional order. ie. the first parameter receives the value of the first argument, second to second, and so on.
  • 7. Function Arguments 3 Default Arguments - an argument that takes a default value if no value is provided in the function call statement. The default values are specified in the function header statement. Eg: def printinfo( name, salary = 13500): print (“Name: “, name) print (“Salary: “, salary) return printinfo(“Mani”) printinfo(“Mani”,12000) Output: Name: Mani Salary: 13500 Name: Mani Salary: 12000 Eg: def printdata (name, age=25): print ("Name :",name) print ("Age :",age) return printdata ("Guhan") Output: Name: Guhan Age:25
  • 8. Function Arguments 2. Keyword Arguments: - Keyword arguments will invoke the function after the parameters are recognized by their argument names. - The value of the keyword argument is matched with the parameter name and so, one can also put arguments in improper order (not in order). Note: TypeError: printdata() got an unexpected keyword argument 'name1' def printdata (name, age): print ("Name :",name) print ("Age :",age) return printdata (age=25, name1="Guhan") Output: Name:Guhan Age:25 def printdata (name, age): print ("Name :",name) print ("Age :",age) return printdata (age=25, name="Guhan")
  • 9. Function Arguments 4. Variable-Length Arguments: In Variable Length arguments we can pass the arguments using two methods. 1. Non keyword variable arguments (tuples) 2. Keyword variable arguments
  • 10. Using multiple argument types together Rules for combining all three types of arguments: • An argument list must first contain required arguments followed by keyword arguments. • Keyword arguments should be taken from the required arg. • You cannot specify a value for an argument more than once. def interest(prin,cc,time=2,rate=0.09): return prin*time*rate Interest(prin=3000,cc=5) Interest(rate=0.12,prin=5000,cc=4) Interest(cc=4,rate=0.12,prin=5000) Interest(5000,3,rate=0.05) Interest(rate=0.05,5000,3) Interest(5000,print=300,cc=2) Interest(500,time=2,rate=0.05) legal legal legal legal Not legal Not legal Not legal
  • 11. Structure of a Python program Generally all function definitions are given at the top followed by other statements which are not indented. These statements are called as ‘Top-level statements’. The execution of a python programs starts always from the top-level statements. Python gives a name to top-level program as “__main__” Python stores this name in a built-in variable called “ __name__” print(__name__) Output: __main__ def function(): def function(): def function(): # top-level statements statement-1 statement 2 … Example: def fun1(): print(“hello”) # top-level statements (or) __main__ print(“top-level statements”) fun1()
  • 12. Flow of execution in a function call def sum(x,y) what is this statement called as ? The flow of execution refers to the order in which statements are executed during a program run by the python interpreter. What is a block? A block is a piece of python program text that is executed as a unit. Yes, it is a function header statement. Ok. Now, how will you call this function that executes it? sum(a,b) A function body is a also a block which is executed by creating an execution frame and when control is transferred inside an execution frame, the statements in the function body is executed. At the end of execution of a function, the function returns the control to the caller program.
  • 13. Flow of execution in a function call An execution frame contains: • administrative information for debugging. • Name of the function • Values passed to the function • Local variable created within function • Information for next instruction to be executed.
  • 14. Flow of execution in a function call def function(): … return # __main__ … func(): print(…) def sum(x,y): z=x+y print(z) return Python begins its execution with first line of __main__ segment. Initially the execution of def function ignored until called. # __main__ n1=float(input("enter first number")) n2=float(input("enter second number")) sum(n1,n2) print(“control sent back to the caller-exec.over) Example:
  • 15. The entire program is executed as follows; main.1main.2main.3sum.1()sum.2 sum.3 sum.4 main.4 Example: def sum(x,y): s=x+y return s # __main__ n1=float(input("enter first number")) n2=float(input("enter second number")) res=sum(n1,n2) print("sum of {} and {} is:".format(n1,n2),res) The entire program is executed as follows; main.1main.2main.3sum.1()sum.2 sum.3 main.3  main.4
  • 16. Guidelines that python follows to a program: • Execution always begin with first line of __main__ • Ignore all comment lines and executes non-blank lines. • Python interpreter executes the function header(def function) line to determine for proper header function and skips all other statements in the function body. • The lines of function body are not executed until it is called. • If a function contain any inner function, and it is not executed until the outer function is called. • Python first jumps to the function header line, as soon as the call statement is executed and then executes all other lines in the function body. • A function terminated with the execution of return or last line of the function body, whichever occurs earlier. • If a called function returns a value like return<variable/value/expression>, then the control is jumped to the function call where it completely replaces with return value and completes it. • If the function does not return any value, then the control jumps back to the line following the function call statement.
  • 17. Example: 1. def sum(x,y): 2. s=x+y 3. return s 4. #__main__ 5. n1=float(input("enter first number")) 6. n2=float(input("enter second number")) 7. res=sum(n1,n2) s3 8. print("sum of {} and {} is:{}".format(n1,n2,res)) When tracing the above program, the flow of execution as follows: 1 56712378
  • 18. 2. void function: If a function does not return any value, then it is called void function but may or may not have return statement. Eg def greet(): print(“hello world”) greet() Eg: def sum(x,y): s=x+y print(s) return sum(5,6) Note: void function do not return any value but return ‘None’ to its caller.
  • 19. def greet(): print(“hello”) print(greet()) def greet(): return(“hello”) print(greet()) Output: hello None # greet() function return ‘None’ and so it is printed Output: hello Note : greet() function return ‘hello’ and so it is printed
  • 20. Returning values from functions:: • Function returning some value (non void) • Function not returning any value(void) 1. Non void function: a literal eg return a / a variable eg. return 5/ an expression eg. return (x+y) def sum(x,y): s=x+y return s result= sum(5,3) Note: sum(5,3) is replaced with 8 Ie. result=8
  • 21. Returning values from functions:: add_result=sum(a,b)  return value is used in assignment statement print(sum(3,4))  return value is used in print statement sum(4,5) > 6  return value used in relational expression. Note: if the return value is not used, python will not report any error but the return value is completely wasted.
  • 22. Four possible combination of functions: 1. Non –void function without any arg 2. Non-void function with some arg 3. Void function without arg 4. Void function with some arg.
  • 23. Practice Questions: Write a non-function that returns a value without args. def sum(): n1,n2=int(input("enter first no.")),int(input("enter second no.")) return(n1+n2) print("sum=",sum())
  • 24. Practice Questions: Write a non-function that returns with args. def sum(a,b): return(n1+n2) n1,n2=int(input("enter first no.")),int(input("enter second no.")) print("sum=",sum(n1,n2))
  • 25. Practice Questions: Write a void function that adds two numbers without args. def sum(): n1,n2=int(input("enter first no.")),int(input("enter second no.")) print(n1+n2) sum()
  • 26. Practice Questions: Write a void function that adds two numbers with some args. def sum(a,b): print("sum=",a+b) n1,n2=int(input("enter first no.")),int(input("enter second no.")) sum(n1,n2)
  • 27. Returning multiple values must ensure the following; (i) Return <value1/variable1/exp1>, <value2/variable2/exp2>, … (ii) Function call statment should receive or use of the following form: (a) either receive the returned values in the form of tuple variable (b) or by specifying same number of variables on the left- hand side of the assignment in fucntion call by directly unpacking the tuple.
  • 28. # function call receiving as tuple: def max_min(a): return (max(a),min(a)) list1=[34,-56,3,-7,23,10,8,-2] rt=max_min(list1) print('maximum:{} and minimum:{}'.format(rt[0],rt[1])) Note the here the function returns comma separated multiple values and therefore ‘t’ is a tuple type. (packing) Write a function that returns comma separated values:
  • 29. # fucntion call directly unpacking the tuple. def max_min(a): t=max(a),min(a) return t list1=[34,-56,3,-7,23,10,8,-2] ma,mi=max_min(list1) print('maximum:{} and minimum:{}'.format(ma,mi)) Note: received values are in the form of two different variables not as tuple. (unpacking) Write a function that returns a tuple:
  • 30. import math try: def fu(a): print(int(math.sqrt(a))) fun('36') except NameError: print("Function name error") except TypeError: print("type mismatch") else: print("no exception") Write a program to handle an exception raised due to inappropriate #argument passed/function call
  • 31. What is the possible outcome/s of following code import random colors=['red','green','yellow','blue','orange','violet'] print(colors[random.randint(3,5)]) Possible options: a) green b) yellow c) blue d) violet What is the purpose of the "return" statement in a function? a) It specifies the type of the function. b) It defines the input parameters of the function. c) It indicates the end of a function. d) It returns a value from the function to the caller.
  • 32. Which of the following function header is correct? a) def cal_si(p=100, r, t=2) b) def cal_si(p=100, r=8, t) c) def cal_si(p, r=8, t=2) d) def cal_si(p, r=8, t) Which of the following components are part of a function header in Python? a) Return Statement b) Function Name c) Parameter List d) Both b and c
  • 33. Consider the code given below: Which of the following statements should be given in the blank for #Missing Statement, if the output produced is 110? b=100 def fun(a): ………………… b=b+a print(a,b) fun(b) print(b) a) global a b) global b=100 c) global b d) global a=100
  • 34. import random low=25 point=5 for i in range(1,5): number=low+random.randint(0,point) print(number,end=" : ") point-=1; print() What are the possible output/s for the following code? Output Options: i. 29: 26:25 :28 : ii. 24: 28:25:26: iii. 29: 26:24 :28 : iv. 29: 26:25:26: Answer: iv)
  • 35. import random limit=4 points=100+random.randint(0,limit) for p in range(points,99,-1): print(p,end=" # ") print() What are the possible outcome/s for the following code: Output Options: i. 103#102#101#100# ii. 100#101#102#103# Iii. 100#101#102#103#104# iv.104#103#102#101#100# Answer: i) and iv)
  • 36. import random AR=[20,30,40,50,60,70] Lower=random.randint(1,3) Upper=random.randint(2,4) for k in range(lower, upper + 1): print(AR[k],end=“#”) What possible outputs(s) are expected to be displayed on screen at the time of execution of the program from the following code? Also specify the maximum values that can be assigned to each of the variables Lower and Upper. a) 10#40#70# b) 30#40#50# c) 50#60#70# d) 40#50#70# b) & d)
  • 37. 18. What will be the output of the following code? >>> def a(b=11, c=21): b += 13; c -= 13 return b+c 0.77 >>> print(a(25), a(35)) a) 15 18 b) 46 56 c) 25 35 d) 13 12
  • 38. Scope of Variables: It refers to the part of the program, where the variable is accessible. two types of scopes - local scope and global scope. Local Scope : A variable declared inside the function's body is said to have local scope is known as local variable. Rules of local variable: A variable with local scope can be accessed only within the function/block that it is created in. • When a variable is created inside the function/block, the variable becomes local to it. • A local variable only exists while the function is executing. • The formal parameters are also local to function. Note: it can be multi-level. There can be nested local scope of an inside block called enclosed scope. Eg: def loc(): y=0 # local scope print(y) loc() Output: 0 def loc(): y = "local” loc() print(y) the output shows the following error: NameError: name 'y' is not defined
  • 39. Global Scope : A name declared in top-level statement (__main__) of a program is said to have a global scope and can be used anywhere in the program. It can be created by defining a variable outside the scope of any function/block. Rules of global Keyword: • When we define a variable outside a function, it’s global by default. You don’t have to use global keyword. • We use global keyword to modify a global variable inside a function. • Use of global keyword outside a function has no effect c = 1 # global variable def add(): print(c) add() Output: 1 c = 1 # global variable def add(): c = c + 2 # increment c by 2 print(c) add() Output: Unbound Local Error: local variable 'c' referenced before assignment
  • 40. def gra(x,y): ma,mi=max(x,y),min(x,y) return ma,mi #__main__ n1=float(input("enter first number")) n2=float(input("enter second number")) ma,mi=gra(n1,n2) print("max:{} and min:{}".format(ma,mi)) 1. x=5 2. def sum(y): 2. s=x+y 3. return s 4. #__main__ 5. n1=float(input("enter first number")) 6. res=n1+sum(x) 8. print("sum is:”,res) OUTPUT: enter first number6 sum is:16.0 OUTPUT: enter first number34 enter second number67 max:67.0 and min:34.0 Note: Refer scope examples on page: 114 – 117.
  • 41. Life time of variable: Life time of a variable is the time for which a variable lives in a memory. Global variable – lives in memory as long as the program is running. Local variable – lives as long as the function runs. Name resolution (Resolving the scope of a Name: Python follows name resolution rule, also known as LEGB rule: (i) It checks with its local environment(LEGB) – if it has a variable with the same name. if yes, Python uses its value otherwise, then it moves to step(ii) (ii) Checks the enclosing environment(LEGB) – if whether there is a variable with the same name. if yes, Python uses otherwise, python repeats this in the higher level enclosing environment otherwise, it moves to step (iii) (iii) Python checks the global environment(LEGB) – if there is same variable, if yes it uses otherwise it moves to step(iv) (iv) Python checks its Built-in environment(LEGB) – it contains all built-in variable and functions, python checks if there is variable in same name, python uses its value otherwise python reports an error: name<variable> not defined. Built-in namespace-4 Global namespace-3 Enclosed - 2 Local -1
  • 42. Mutable/Immutable Properties of passed data Objects Python variables are not storage containers, rather are like memory references Mutable – changeable/modifiable. Immutable – non-modifiable. Depending upon the mutability/immutability of its data type, python variables behave differently.
  • 43. def state(y): y=y+5 x=10 print('address before calling:',id(x),x) state(x) print('address after calling:',id(x),x) Immutable properties of passed data : If a variable referring to an immutable type, then any change in its value will also change its memory address it is referring to. Output address before calling:140734302669528 10 address after calling: 140734302669688 15
  • 44. Example: def state(a): a[0]=10 x=[1,2] print('address before calling:',id(x),x) state(x) print("address after calling:",id(x),x) mutable properties of passed data : If variable referring to a mutable type,then any change in its value of mutable type will not change the memory address of the variable. The value will change in place (change reflected), if the variable in the function is not assigned a different variable or data type. output: address before calling: 2473295957824 [1, 2] address after calling: 2473295957824 [10, 2]
  • 45. Mutable/Immutable Properties of passed data Objects Conclusion : Changes in immutable type are not reflected in the caller function at all. Changes, if any, in mutable types, • are reflected in caller function if its name is not assigned a different variable or datatype. • are not reflected in caller function if its name is assigned a different variable or datatype.
  • 46. Example: (refer page 129) def fun1(list2): print("variable list2",list2,id(list2)) new=[3,5] list2=new list2[0]=100 print("variable list2",list2,id(list2)) print("variable new",new,id(new)) list1=[10,20] fun1(list1) print("address of list1 after func.call",list1,id(list1)) mutable type of data – assigning parameter to a new variable: Variable referring to a mutable type then any change in its value of mutable type will change the memory address of the variable. The value will not change in place (change not reflected), if the variable in the function is assigned a different variable or data type. output: variable list2 [10, 20] 2207440063744 variable list2 [100, 5] 2207396385536 variable new [100, 5] 2207396385536 address of list1 after func.call [10, 20] 2207440063744 Conclusion : Changes in immutable type are not reflected in the caller function at all. Changes, if any, in mutable types, • are reflected in caller function if its name is not assigned a different variable or datatype. • are not reflected in caller function if its name is assigned a different variable or datatype.