Download as pdf or txt
Download as pdf or txt
You are on page 1of 11

CHAPTER-2 FUNCTIONS IN PYTHON

Definition:
Function is a named group of statements that exists within a program and performs a specific task.

They are also called as subprograms.


The line of code(s) are executed sequentially from top to bottom by Python interpreter.
Functions are the small modules.

Importance of functions :
Improves readability of the program and makes debugging easier
Code can be reused any number of times
Reduces redundancy so updations are easier

Types of Functions:
There are three types of functions in python:

Built in functions

Types of functions Functions defined in modules

User defined functions


Library Functions: These functions are already built in the python library.
Functions defined in modules: These functions defined in particular modules. When you want to use these
functions in program, you have to import the corresponding module of that function.
User Defined Functions: The functions those are defined by the user are called user defined functions.
Library Functions in Python:
These functions are already built in the library of python. For example: type( ), len( ), input( ) etc.
Functions defined in modules:
These functions are packed is an in-built module of python. For using these functions, we need to import the
corresponding module in the program. There are two ways to import module :
1. import <module-name>
import math as m
print(m.sqrt
2. from <module-name> import <function-name>
(don’t have to prefix module name before function name)
From math import sqrt

Functions of math module:


To work with the functions of math module, we must import math module in program.
import math
S. No. Function Description Example
1 sqrt( ) Returns the square root of a number >>>math.sqrt(49)
7.0
2 ceil(18.1 ) Returns the upper integer >>>math.ceil(81.3)
82
3 floor(18 ) Returns the lower integer >>>math.floor(81.3)
81
4 pow( ) Calculate the power of a number >>>math.pow(2,3)
8.0
5 fabs( ) Returns the absolute value of a number >>>math.fabs(-5.6)
5.6
6 exp( ) Returns the e raised to the power i.e. e3 >>>math.exp(3)
20.085536923187668
Function in random module:
randint( )- function generates the random integer values including start and end values.
Syntax: randint(start, end)
It has two parameters. Both parameters must have integer values.
Example:
import randint from random
n=randint(3,7)
*The value of n will be 3 to 7.
User defined functions:
The syntax to define a function is: def function-name (parameters) :
#statement(s)
Where:
Keyword def marks the start of function header.
A function name to uniquely identify it. Function naming follows the same rules of writing identifiers in
Python. Parameters (arguments) through which we pass values to a function. They are optional.
A colon (:) to mark the end of function header.
One or more valid python statements that make up the function body. Statements must have same
indentation level. An optional return statement to return a value from the function.
Example:
def display(name):
print("Hello " + name + " How are you?")
display(a)
Function Parameters:
A functions has two types of parameters:
Parameter or Formal Parameter: Formal parameters are written in the function prototype and function
header of the definition. Formal parameters are local variables which are assigned values from the
arguments when the function is called.
Argument or Actual Parameter: When a function is called, the values that are passed in the call are called
actual parameters. At the time of the call each actual parameter is assigned to the corresponding formal
parameter in the function definition.

Structure of a function :-
greet()

Flow of execution :-
LINE NO. STATEMENT BELONGS TO
1 #flow of control main
2 def add(x,y,z): function header
3 print("x = ",x,"y = ",y,"z = ",z) add
4 r=x+y+z add
5 return r add
6 a = int(input("Enter the first number " )) main
7 b = int(input("Enter the second number " )) main
8 c = add(a,10,b) main
9 print("result = ",c) main

Flow of execution : 6,7,8,2,3,4,5,8,9

GLOBAL VAR – a,b,c


LOCAL VAR – x,y,z,r

Arguments – optional
Return – optional

The return statement:


The return statement is used to exit a function and go back to the place from where it was called. There are
two types of functions according to return statement:
a. Function returning some value
b. Function not returning any value

#variation 1 = sum of n natural numbers : returning single value


def series(n):
sum1 = 0
for i in range(n):
sum1 = sum1 + i
return sum1+n
num = int(input("Enter the limit :"))
result = series(num)
print("The sum of series is : ", result)

#variation 2 = sum of n natural numbers : returning None or void


def series(n):
sum1 = 0
for i in range(n+1):
sum1 = sum1 + i
print("The sum of series is : ", sum1)
num = int(input("Enter the limit :"))
series(num)

# variation 3 : function returning multiple values in a tuple


def f1(a,b,c):
a=a+7
b=b*2
c = c / 10
return a,b,c
x = int(input("Enter first value"))
y = int(input("Enter second value"))
z = int(input("Enter third value"))
S = f1(x,y,z)
print(S)
print(type(S))

# variation 4 : function returning multiple values separately


def f1(a,b,c):
a=a+7
b=b*2
c = c / 10
return a,b,c
x = int(input("Enter first value"))
y = int(input("Enter second value"))
z = int(input("Enter third value"))
p,q,r = f1(x,y,z)
print(p,q,r)

Types of arguments
Python supports four types of arguments / parameters:-
1. Positional / Required arguments : In this way of parameter specification, number of passed
values(arguments) must exactly match the number of receiving values (parameters) order-wise.
Ex:-
#positional arguments
def display(ch, n):
print(ch*n)
char = input("Enter the character to be displayed")
total = int(input("Enter number of times character is to be
displayed "))
display(char,total)

#positional arguments
def SI(p,r,t):
interest = (p * r* t)/100
return interest
prin = float(input("Enter the value of principal amount :"))
time = float(input("Enter the value of time period :"))
rate = float(input("Enter the value of rate of interest :"))
result = SI(prin,time,rate)
print("The SImple Interest is ", result)
2. Default arguments : A parameter having a defined initialised value in the function header is called as
a default argument / parameter.
def f1(x , y = 10, z = 30):

f1(10)
f1(10,12)
f1(11,12,13)

NOTES :-
The default value for a parameter is considered only when no value is provided for it in the function
call statement
The default value for a parameter is replaced when value is provided for it in the function call
statement.
A parameter having default value in function header becomes optional in function call statement.
In a function header statement all the default parameters should be placed on the right that is any
parameter cannot have a default value unless all the parameters on its right are default parameters.
Ex:-
#default arguments
def display(ch='#', n=10):
print(ch)
print(ch*n)
char = input("Enter the character to be
displayed")
total = int(input("Enter number of times
character is to be displayed "))
display(char,total)
display()
display(char)
#predict the output
display(total)
#default arguments
def SI(p,r=5.0,t=6.0):
interest = (p * r* t)/100
print("p = ",p," r = ",r,"t = ",t,end=" ")
return interest
prin = float(input("Enter the value of
principal amount :"))
time = float(input("Enter the value of time
period :"))
rate = float(input("Enter the value of rate
of interest :"))

#first call with default value of time


result = SI(p=prin)
prin,rate)
print("The SImple Interest is : ", result)

#second call with default value of time and


rate
result = SI(prin)
print("The SImple Interest is : ", result)

#third call with a problem


result=SI(prin,time)
print("The SImple Interest is : ", result)

result = SI(prin,time,rate)
print("The SImple Interest is : ", result)

3. Named / keyword arguments : when in a function call statement, value is specified along with the
name of formal arguments then they are called as keyword arguments. The value is provided by
name rather than position of arguments.
def f2(w,x,y=12):

f2(10,20)
f2(10)
f2(10,20,30)
f2(10,x=20)
f2(x=20,10) #INVALID
f2(w=20,10) #INVALID
f2(x=14, y = 22, w = 17)

4. Variable length arguments : When variable number of arguments are passed in function call
statement, then we can declare function header as

def <function-name> (*<argument-name>)


def func1(*S):

func1(a,b,c,d)
func1(List1)
func1(tuple1)
func1(10,40,g,f,r,g)

Scope and Lifetime of variables:


Scope of a variable refers to the part(s) of the program where the variable is legal and accessible.

1 num1 = int(input("enter the first number :"))


2 num2 = int(input("enter the second number : "))
3 def area(x,y):
4 a=x*y
5 return a
6 num3 = area(num1,num2)
7 print(num3)

Order of execution : 1,2,6,3,4,5,6,7

Num1, num2, num3 can be used anywhere global


X, y, a can be used inside area() local

There are two types of scope for variables:


i) Local Scope ii) Global Scope

Local Scope:
Variable/parameters used inside the function.
cannot be accessed outside the function.
not visible from outside the function.
Hence, they have a local scope.

In this scope, the lifetime of variables inside a function is as long as the function executes. They are
destroyed once we return from the function. Hence, a function does not remember the value of a variable
from its previous calls.

Global Scope:
Variables/parameters inside main function.
Variable can be accessed outside the function.
Are visible from whole progam
Hence, they have a global scope.

In this scope, Lifetime of a variable is the period throughout which the variable exits in the memory.
num = 10
def f1( ):#function header
global num
num = 26
x = 20 + num
print(num,x)
f1()
print(num)
f1()

Output :
10 20
10
Hence, num can be used in f1() also hence, has global scope and x has local scope

Local and global having same name


x = 10
def f1():
x = 20
print(x)
f1()
print(x)

Output :
20
10

Here, we can see that the value of x is 10 initially. Even though the function f1()changed the value of x to
20, it did not affect the value outside the function.
This is because the variable x inside the function is different (local to the function) from the one outside.
Although they have same names, they are two different variables with different scope.

x = 10
def f1():
x += 5 # error
print(x)
f1()
print(x)

This will generate an error because UDF f1() cannot change the value of a global variable but f1() can use
the value of global variable x

In order to modify the value of variables outside the function, they must be declared as global variables
using the keyword global.
x = 10
def f1():
global x
x += 5
print(x)
f1()
print(x)
Output :
15
15

LEGB rule
Local
Environment
Global
Built-in

Passing values of parameters :


1. Call by value :
is implemented by immutable data types in Python
modification made in the value of a formal argument inside a function is not valid for the calling function
that is changes made in the values of formal arguments are not reflected back to the actual argument .
2. Call by reference
is implemented by mutable data types in Python
modification made in the value of a formal argument inside a function is valid for the calling function that is
changes made in the values of formal arguments are reflected back to the actual argument .

#passing parameters 70
def add(x,y):
x = x + 10
z=x+y
return z
def main():
a = 25
b = 35
z = add(a,b)
print(z)
main()

#call by value X as a 25
def add(x,y): Y as b 35
x = x + 10 70
z=x+y
return z
def main():
a = 25
b = 35
z = add(a,b)
print("x as a = ",a)
print(" y as b = ", b)
print(z)
main()
#call by reference [10,20,30]
def add(x): [10,20,30,50]
x.append(50)
def main():
list1 = [10,20,30]
print(list1)
add(list1)
print(list1)
main()

Short Answer Type Questions (2-Marks)


Q1. Rewrite the correct code after removing the errors: -
def SI(p,t=2,r):
return (p*r*t)/100
Ans: - def SI(p, r, t=2):
return(p*r*t)/100
Q2. Consider the following function headers.
Identify the correct statement: -
1) def correct(a=1,b=2,c): 2) def correct(a=1,b,c=3):
3) def correct(a=1,b=2,c=3): 4) def correct(a=1,b,c):
Ans: - 3) def correct(a=1,b=2,c=3)
Q3.What will be the output of the following code?
a=1
def f():
a=10
print(a)
Ans: The code will print 1 to the console.
Application Based Questions ( 3 Marks)
Q1. Write a python program to sum the sequence given below. Take the input n from the user.

Solution:
def fact(x):
j=1, res=1
while j<=x:
res=res*j
j=j+1
return res
n=int(input("enter the number : "))
i=1, sum=1
while i<=n:
f=fact(i)
sum=sum+1/f
i+=1
print(sum)
Q3. How many values a python function can return? Explain how?
Ans: Python function can return more than one values.
def square_and_cube(X):
return X*X, X*X*X, X*X*X*X
a=3
x,y,z=square_and_cube(a)
print(x,y,z)
Q4. Find the output of the following code: -
def CALLME(n1=1,n2=2):
n1=n1*n2
n2+=2
print(n1,n2)
CALLME()
CALLME(2,1)
CALLME(3)
Ans: - 2 4
23
64
Q5. Predict the output of the following code fragment?
def check(n1=1, n2=2):
n1=n1+n2
n2+=1
print(n1,n2)
check()
check(2,1)
check(3)
Ans: 3 3
32
53

You might also like