Functions
Functions
Sarman Singh
Seth Anandram Jaipuria School
[email protected]
Functions 2/22
Function
Functions 3/22
Syntax for functions
def function_name(parameters):
"""docstring""" statement(s)
return [expression]
Functions 4/22
Docstring
Functions 5/22
Example: Function
f (x) = x2
Above mentioned mathematical function can be written in
Python like this:
def f(x):
return x*x
Functions 6/22
Anatomy of Python function
Functions 7/22
Python Function types
User-
defined by programmer
defined
Functions 8/22
Arguments and parameters
Functions 9/22
Passing parameters
Functions 10/22
Positional/Required Arguments
Functions 11/22
Default Arguments
Functions 12/22
Keyword (Named) Arguments
Functions 13/22
Using multiple argument types together
Functions 14/22
Using multiple argument types together
Functions 14/22
Using multiple argument types together
Functions 14/22
Returning values from function
Functions 15/22
Scope of variables
Scope
Part(s) of program within which a name is legal and
accessible.
Global Scope
A name declared in top level segment( main ) of a
program, it can be used inside whole program and all
blocks(functions,other blocks).
Local Scope
A name declared in a function-body is said to havelocal
scope, i.e. it can be used only within this function.
Functions 16/22
Scope Example I
Program
1. def calcsum(x,y):
2. z=x+y
3. return z
Functions 17/22
Scope Example II
Program:
1. def calcsum(a,b,c):
2. s=a+b+c
3. return s
4. def average(x,y,z):
5. sm=calcsum(x,y,z)
6. return sm/3
7. num1=int(input("Number 1:"))
8. num2=int(input("Number 2:"))
9. num3=int(input("Number 3:"))
10. print("Average is:",average(num1,num2,num3))
Functions 18/22
Name Resolution (LEGB Rule)
Functions 19/22
Mutable/Immutable properties of passed
data objects
Functions 20/22
Passing an immutable/mutable data type
Functions 21/22
Summary of mutable/immutable type’s behaviour
Functions 22/22