Functions
Functions
CLASS – XII
COMPUTER SCIENCE
FUNCTIONS IN PYTHON
Functions are the subprograms that perform specific task. Functions are
the small modules. Reusing the same code is required many times
within a same program. Functions help us to do so. We write the things
we have to do repeatedly in a function then call it where ever required.
Through functions we implement ‘Modularity’ feature of modern
programming languages.
Advantages of Using functions:
1. Program development made easy and fast: Work can be divided
among project members thus implementation can be completed
fast.
2. Program testing becomes easy: Easy to locate and isolate a faulty
function for further investigation
3. Code sharing becomes possible: A function may be used later by
many other programs this means that a python programmer can
use function written by others, instead of starting over from
scratch.
4. Code re-usability increases: A function can be used to keep away
from rewriting the same block of codes which we are going use
two or more locations in a program. This is especially useful if the
code involved is long or complicated.
5. Increases program readability: It makes possible top down
modular programming. In this style of programming, the high level
logic of the overall problem is solved first while the details of each
lower level functions are addressed later. The length of the source
program can be reduced by using functions at appropriate places.
6. Function facilitates procedural abstraction: Once a function is
written, it serves as a black box. All that a programmer would have
to know to invoke a function would be to know its name, and the
parameters that it expects.
Types of Functions:
We can divide functions into the following three types:
Docstrings:
The first string after the function header is called the docstring and is
short for documentation string. It is briefly used to explain what a
function does.
Although optional, documentation is a good programming practice.
Unless you can remember what you had for dinner last week, always
document your code.
In the above example, we have a docstring immediately below the
function header. We generally use triple quotes so that docstring can
extend up to multiple lines. This string is available to us as the __doc__
attribute of the function.
>>>print(greet.__doc__)
This function greets to
the person passed in as
a parameter
Return Statement:
Calling/Invoking a function
To call a function we simply type the function name with appropriate
parameters. Once we have defined a function, we can call it from:
● Another function
● Program
● Python prompt
Working of a function:
def addUs():
# calculate sum
addUs()
def addUs(n,m):
print(n+m)
# calculate sum
x=int(input("Enter 1st number"))
y=int(input("Enter 2nd number"))
addUs(x,y)
def addUs():
n=int(input("Enter 1st number"))
m=int(input("Enter 2nd number"))
return (n+m)
# calculate sum
c=addUs()
print(c)
#Example1
def addUs(n,m):
return(n+m)
# calculate sum
x=int(input("Enter 1st number"))
y=int(input("Enter 2nd number"))
z=addUs(x,y)
print(z)
#Example2
def power(m,n):
prod=1
for i in range(1,n+1):
prod=prod*m
return prod
# calculate value of sqr(x)-sqr(y)
x=int(input("Enter x"))
y=int(input("Enter y"))
z=power(x,2)-power(y,2)
print(z)
Exercise :
1. Write a program using UDF to return the factorial of a
number and use the same in generating the sum of
following series:
x/3! + x3/5! + x5/7! ….. xn/m!
# Global scope
str1 = "I love programming"
func()
Output: I love programming
The variable str1 is defined as the string before we call the function
func(). The only statement in func() is the “print (str1)” statement. As
there is no local str1, the value from the global str1 will be used.
Exercise :
Write a program using UDF to return reverse of a number. (Use global
number in place of parameter)
# Global scope
str1 = "I love programming" # global str1
func()
Output: Hello
If a variable with the same name is defined inside the scope of function
as well then it will use the value given inside the function only and not
the global value.
# Global scope
str1 = "I love programming"
func()
Output: UnboundLocalError: local variable 'str1' referenced before
assignment
First solution to the above problem is use of globals() function
def func():
print(globals()['str1'])
str1="Hello"
print(str1)
Output:
I love programming
Hello
I love programming
Second solution to the above problem is Global keyword
Because, Only accessing of the global variables are allowed in the
function, modification is not allowed.
Example :
c = 1 # global variable
def add():
c = c + 2 # increment c by 2
print(c)
add()
When we run the above program, the output shows an error. This is
because we can only access the global variable but cannot modify it from
inside the function.
In Python, global keyword allows you to modify the variable outside of
the current scope. It is used to create a global variable and make
changes to the variable in a local context.
Any variable can be changed or created inside of a function is local if it
hasn’t been declared as a global variable. To tell Python, that we want
# Global scope
str1 = "I love programming"
func()
print("Global String",str1)
Output:
Global String I love programming
Local String Hello
Global String Hello
The order Local, Enclosing, Global, Built-in is the order of precedence for
scope resolution. That means Python searches for the value of a name in
each of these namespaces in turn. Namespaces are how Python keeps
track of variables. In a namespace, an object name maps to the object
itself. Namespaces keep track of all objects, not just user-defined
variables. For example, functions are also objects in Python. A namespace
can contain function names that map to the contents of those functions.
Namespaces are created and destroyed as a program runs.
Exercise:
Write a menu driven program using UDFs to :
a. Calculate square of a number
b. Cube of a number
c. Check whether number is prime
d. Check whether number is Armstrong
e. Return reverse of a number if integer.
a = 10
b = 20
Create a test.py file, to test availability changes in value
import myGlobal
print(myGlobal.a)
print(myGlobal.b)
When we run the test.py file, the output will be
10
20
1. Positional
2. Default
3. Keyword
4. Variable length/arbitrary
Positional arguments:
When the function call statement should match the number and order of
parameters as defined in the function definition, it is called as positional
arguments. The process may also be called as required or mandatory
arguments.
Example 1:
def Fibonacci (n=10):
n1, n2 = 0, 1
count = 0
# check if the number of terms is valid
if n <= 0:
print("Please enter a positive integer")
elif n == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
else:
print("Fibonacci sequence:")
while count < n:
print(n1)
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1
nterms = int(input("How many terms? "))
fibonacci(nterms) # using
fibonacci() # using default parameter
Output :
How many terms? 5
Fibonacci sequence:
Fibonacci sequence:
0 1 1 2 3 5 8 13 21 34
Example 2
def area(l,b=5):
return l*b
ar=area(5,10)
print(ar)
ar=area(5)
print(ar)
Output:
50
25
Example 3
def area(l=5,b):
return l*b
ar=area(5,10)
print(ar)
ar=area(5)
print(ar)
Output:
Error - Non default argument follows default argument
IMPORTANT TIP:
In a function header, any parameter cannot have a default value
unless all parameters appearing on it’s right have their default values.
Purpose of Default arguments:
1. Used in situations where some parameters always have the same
value.
2. Greater flexibility to the programmer.
3. It combines similar functions into one.
Exercise :
Exercise : Modify the above program with one more option using all
keyword parameters.
Keyword Arguments
The default arguments give you the flexibility to specify the default value to
the right most parameters so, that they can be skipped in the function call,
if needed. But, still we may not change the order of the parameters in the
function call statement. We have to remember the correct order while
giving the arguments.
Using keyword parameters is an alternative way to make function calls in
Python. The definition of the function doesn't change. But Python offers a
An example:
def simpleInt(p,t,r):
return (p*t*r)/100
print(simpleInt(r=10,t=2,p=5000)
print(simpleInt(t=2,p=5000, r=10)
print(simpleInt(p=5000,r=10,t=2)
Output:
1000.0
1000.0
1000.0
print(sumsub(12, 4))
But if, we want to give a custom value
print(sumsub(42, 15, d=10)) # skipped c which will take default value
8
17
Keyword parameters can only be those, which are not used as
positional arguments. We can see the benefit in the example. If we
Exercise:
I. Considering the above example, identify whether following calls
are valid or not:
1. sumsub(c=5,a=2,d=9,b=7) # -9
2. sumsub(a=5,b=2) #3
3. sumsub(a=2,d=9,b=7) # -14
4. sumsub(c=2,9,2) #positional argument
follows keyword argument
5. sumsub(10,a=5,c=2,d=7) # multiple values for a
6. sumsub(10,5,c=2,d1=7) # undefined variable
7. sumsub(10,c=2,d=7) # required parameter
missing
II. Write a program using function to find HCF or GCD. Use :
1. Only positional arguments
2. One value (5) as default argument
3. Only keyword arguments.
In the function definition, we use an asterisk (*) before the parameter name
to denote this kind of argument. Here is an example.
def avg(*n):
c=0
sum=0
for i in n:
sum+=i
print(avg(3,5,8,1,12)) # 5.8
print(avg(10,20,15,20,15,10)) #15.0
Exercise :
1. WAP using function taking n number of parameters and finding
the minimum entered value.
2. WAP using function taking n number of marks of the students and
finding the count of failures.
3. WAP using function taking n number of names and find the name
with largest length.
Exercise :
1. WAP using function which takes radius as input and returns area,
circumference and diameter.
2. WAP using function to take a number as input and return first four
factors of that number.
Python Lambda/ Anonymous function
In Python, an anonymous function is a function that is defined without a
name. While normal functions are defined using the def keyword in
Python, anonymous functions are defined using the lambda keyword.
Example 1:
num = lambda a, b : a * b
print(num(5, 6))
Example 2:
func1=lambda a:3.14*a*a
print(func1(5))
Or
List Comprehension method:
l1 = [1, 5, 6, 8, 10, 15, 12]
l2=[x for x in l1 if x%5==0]
>>> print(l2)
[5, 10, 15]
Exercise:
Pass by Value:
def updateNumber(n):
print(id(n))
n += 10
print(id(n))
b=5
print(id(b))
updateNumber(b)
print(b)
print(id(b))
OUTPUT
1691040064
Call by reference
def updateList(list1):
print(id(list1))
list1 += [10]
print(id(list1))
n = [50, 60]
print(id(n))
updateList(n)
print(n)
print(id(n))
OUTPUT
34122928
34122928
34122928
[50, 60, 10]
34122928
#In above function list1 an object is being passed and its contents are
changing because it is mutable that’s why it is behaving like pass by
reference.
Exercise:
LEGB Rule:
2. Enclosing (or non local) scope is a special scope that only exists
for nested functions. If the local scope is an inner or nested
function, then the enclosing scope is the scope of the outer or
enclosing function. This scope contains the names that you define
in the enclosing function. The names in the enclosing scope are
visible from the code of the inner and enclosing functions.
def func1():
a=10
def func2():
print(a)
func2()
print(a)
func1()
func2() #error
3. Global (or module) scope is the top-most scope in a Python
program, script, or module. This Python scope contains all of the
1. def add(i):
if(i*3%2==0):
i*=i
else:
i*=4
return i
a=add(10)
print(a)
2. import math
def area(r):
return math.pi*r*r
a=int(area(10))
print(a)
4. def div5(n):
if n%5==0:
return n*5
else:
return n+5
def output(m=5):
for i in range(0,m):
print(div5(i),'@',end=" ")
print('\n')
output(7)
output()
output(3)
5.def sum(*n):
total=0
for i in n:
total+=i
print('Sum=', total)
sum()
sum(5)
sum(10,20,30)
6. def func(b):
global x
print('Global x=', x)
y=x+b
x=7
z=x-b
7. def func(x,y=100):
temp = x + y
x += temp
if(y!=200):
print(temp,x,x)
a=20
b=10
func(b)
print(a,b)
func(a,b)
print(a,b)
8. def get(x,y,z):
x+=y
y-=1
z*=(x-y)
print(x,'#',y,'#',z)
def put(z,y,x):
x*=y
y+=1
z*=(x+y)
print(x,'$',y,'$',z)
a=10
b=20
c=5
put(a,c,b)
get(b,c,a)
put(a,b,c)
get(a,c,b)
1. def in(x,y):
x=x + y
print(x.y)
x*=y
print(x**y)
2. def get(x=10,y):
x=x+y
print(x,\n,y)
4. a=5, b=10
def swap(x,y):
x=a+b
y=x-y
x=x-y
swap(a)
swap(15,34)
swap(b)
swap(a,b)
1. What is a function?
2. Why programmer need functions in python programming?
3. How to create a function in python? Explain in detail.
4. What are the parts of functions? Explain with suitable example.
5. How to call a function? Write steps.
6. What is the difference between global and globals()?
7. What is Lambda function? Explain the purpose.
8. Illustrate flow of execution in function call statement.
9. Write and explain types of functions supported by python.
10. Write the ways of import module in python program.
11. Differentiate between parameters and arguments.
12. What are the arguments supported by python? Explain each of
them with suitable example.
13. What is local variable and global variable? Explain with example.
14. What are dunder variables? Explain with the help of example.