Functions
Functions
CHAPTER -3
CLASS 12TH
BY Harish Chander
• TOPICS
1. Built-in
[Link]
[Link] Defined
Built-in Functions
• These are the functions which are predefined in python we
have to just call them to use.
• Functions make any programming language efficient and
provide a structure to language.
• Python has many built-in functions which makes programming
easy, fast and efficient.
• They always reside in standard library and we need not to
import any module to use them.
2. Input Functions: This function is used to take input from user in the form
of string.
e.g. x=eval(“45+10“)
print(x) # answer will be 55
Python Modules
•Module is a .py file which contains the definitions of functions and variables.
•When we divide a program into modules then each module contains functions
and variables. And each functions is made for a special task.
•When we make such functions which may be used in other programs also
then we write them in module.
•We can import those module in any program an we can use the functions.
function defined in Modules
•We can use them in any part of our program by calling them.
User Defined
We make our own functions
Sum() , interest() , sub()
User-defined Functions. . .
def sum(a,b):
def sum(a,b): c=a+b
c=a+b return c
print(c) OUTPUT 30 x=10
x=10 40 y=20 OUTPUT 30
y=20 z=sum(x,y)
sum(x,y) print(z)
sum(20,20)
Flow of execution in a function call
1. def interest(a,b,c):
1. def sum(a,b): 2. i=a*b*c/100
2. c=a+b Flow of execution 3. return i
has started from
3. print(c) line 4 bcoz main 4. p=int(input())
4. x=10 program is 5. r=int(input())
executed first, and
5. y=20 when function is 6. t=int(input())
6. sum(x,y)
called then 7. ci=interest(p,r,t)
function is
executed 8. print(ci)
4-5-6-1-2-3 4-5-6-7-1-2-3-7-8
VOID FUNTION NON VOID FUNTIONS
Void and Non Void Function
def sum(a,b):
c=a+b def sc(a):
print(c) Output return a**2 , a**3
return 30 n=int(input())
x=10 None s,c=sc(n)
y=20 print(s,c)
z=sum(x,y) Output
9
print(z) 27
We may use return ,but it will Value return can be literal ,variable
return None value to the function
call. -----Void funtions , expression. ---- Non Void funtions
User-defined Functions without argument and without
return (Practical)
Returning values from function
Non void function without any argument
def sum():
a=10
b=20
return a+b
c=sum()
print(c)
Output : 30
User-defined Functions with argument and without
return (Practical)
User-defined Functions with argument and with
return value (Practical)
Returning values from function
def sum(a,b):
return a+b
x=20 Output : 50
y=30
z=sum(x,y)
print(z)
Returning values from function
def sum():
a=10
b=20 Output : 30
print(a+b)
sum()
Returning values from function
Void functions with arguments
def sum(a,b):
print(a+b)
x=20
y=30
Output : 50
sum(x,y)
User-defined Functions with multiple return
values (Practical)
Returning Multiple values from Functions
Receive Values as tuple
def sum(a,b):
return a+b,a-b
x=10 Output : (30, -10)
y=20
c=sum(x,y)
print(c)
Returning Multiple values from Funtions
Unpack received values of tuple
unpacking means – creating multiple
variables to receive returned values.
def sum(a,b):
return a+b,a-b
x=10
y=20
Output : 30 -10
sm,sb=sum(x,y)
print(sm,sb)
User-defined Functions with multiple return
values (Practical)
Pahrameters and Arguments in Functions
•When we write header of any function then the one or more values
given to its parenthesis ( ) are known as parameter.
•These are the values which are used by the function for any specific
task.
def sum(a,b):
Parameter – received c=a+b
values in function print(c)
definition It should be of x=10
variable type. y=20
sum(x,y)
1. Positional Arguments
[Link] Arguments
[Link] Arguments
•If we change the position of the arguments then the answer will be changed.
Passing Arguments
• These are the arguments through which we can provide default values to the
function.
•If we don’t pass any value to the function then it will take a pre defined value.
Example
Default Arguments
Passing Arguments
Default argument
If right parameter have
We can have less arguments if
default value then only, left
default value for a parameter is parameters can also have
provided. default value.
def sum(a,b,c=10):
d=a+b+c
print(d)
x=10
y=20
sum(x,y)
def sum(a,b=60,c): #wrong
d=a+b+c
print(d)
x=10
y=20
sum(x,y)
Keyword Arguments
•If a function have many arguments and we want to
change the sequence of them then we have to use
keyword arguments.
int(str(52))
int(float(“52.5”)*2) Function call as part of larger
function call i.e. composition
int(str(52)+str(10))
Fruitful Function = Functions
returning a value are also
known as Fruitful Funtion
Non-fruitful function= A void function
(somestimes called non-fruitful functions)
Returns legal empty value of python i.e
None to its caller.
Variable Length Arguments
• As we can assume by the name that we can pass any number of arguments according to the
requirement. Such arguments are known as variable length arguments.
•Scope of variable means the part of program where the variable will be
visible. It means where we can use this variable.
•We can say that scope is the collection of variables and their values.
•Scope can of two types –
•Global (module)
–All those names which are assigned at top level in module or directly assigned in
interpreter.
•Local (function)
def sum(a):
c=a+y
return c
x=10
y=20
Output : 30
z=sum(x)
print(z)
Scope of Variables
Local scope
Name declared in function [Link] is usable within function (we can’t use a & b
outside the function sum(), program showing error ) (a , b are local variable)
def sum():
a=10
b=20 Print (c) Output : 30
return a+b
c=sum() Print(a) Error
print(c)
print(a)
Example
def calcsum(a,b,c):
s=a+b+c
x=5
return s
def func(a):
b=a+1
def v(x,y,z):
return b sm=calcsum(x,y,z)
return sm/3
y=int(input("Enter number kr be="))
z=y+func(x) a=int(input("Number1="))
print(z) b=int(input("Number2="))
c=int(input("Number3="))
OUTPUT print("Average number is",v(a,b,c))
Enter number kr be=6
12 OUTPUT
Number1=1
Number2=2
Number3=3
Average number is 2.0
Flow of Execution at the Time of Function Call
• The execution of any program starts from the very first line and this execution goes line by
line.
•When function is called then the control is jumped into the body of function.
•Then all the statements of the function gets executed from top to bottom one by one.
•And again the control returns to the place where it was called.
2. Local
[Link]
[Link]
[Link] in
Local(L): Defined inside
function
def myfuc1(a):
print("\t Inside myfuc1()")
print("\t Valuereceived in 'a' as",a)
a=a+2
print("\t Value of 'a' now changes to",a)
print("\t returing from myfuc1()") Calling by passing 'num withvalue is 3
Inside myfuc1()
num=3 Valuereceived in 'a' as 3
Value of 'a' now changes to 5
print("Calling by passing 'num withvalue is",num) returing from myfuc1()
myfuc1(num) Back from myfuc1()is 'num' is 3
print("Back from myfuc1()is 'num' is",num)
Sample Code 2.1
def myfuc2(mylist):
print("Inside called funtion now=1")
print("List received=2",mylist)
OUTPUT
mylist[0]+=2
List before funtion call=4 [1]
print("list within called=3",mylist) Inside called funtion now=1
return List received=2 [1]
list1=[1] list within called=3 [3]
print("List before funtion call=4",list1) list after call=5 [3]
myfuc2(list1)
print("list after call=5",list1)
Sample Code 2.2
def myfunc3(mylist):
print("Inside Called Funtion now=1")
print("List recieved:=2",mylist)
OUTPUT
[Link](2)
[Link]([5,1]) list before call=5 [1]
print("adding elements=3",mylist) Inside Called Funtion now=1
[Link](5) List recieved:=2 [1]
print("after all changes=4",mylist) adding elements=3 [1, 2, 5, 1]
return after all changes=4 [1, 2, 1]
list1=[1]
list after call=6 [1, 2, 1]
print("list before call=5",list1)
myfunc3(list1)
print("list after call=6",list1)
Sample Code 2.2
def myfunc4(mylist):
print("Inside called function=1")
print("List Received=2",mylist) OUTPUT
new=[3,5] list before call=4 [1, 4]
mylist=new Inside called function=1
[Link](6)
List Received=2 [1, 4]
print("list after changes=3",mylist)
return list after changes=3 [3, 5, 6]
list1=[1,4] list after call=5 [1, 4]
print("list before call=4",list1)
myfunc4(list1)
print("list after call=5",list1)
QUES 2 From the program code given below identity the parts mentioned below:
def processnumber(x):
x=72
Fnction header : def processnumber(x):
return x+3 Function call : processnumber(y)
y=54 Arguments: y
res=processnumber(y) Parameters : x
Function body: x=72
print(res) return x+3
Main program: y=54
res=processnumber(y)
Identify :Function header,function call,
arguments,parameters,function
body,main program
QUES 3 Trace the following code and predict output produced by it.
1. def power(b,p):
2. y=b**p
3. return y
4.
5. def calcsquare(x):
6. a=power(x,2) OUTPUT
7. return a
8. 52
9.n=5
10. result=calcsquare(n)+power(3,3)
[Link](result)
FLOW== 1-5-9-10-5-6-1-2-3-6-7-10-1-2-3-10-11
QUES 4 – Trace the flow of execution for following programs:
1. def power(b,p): def increment(x):
1. def increment(x): z=45
2. r=b**p
2. x=x+1 x=x+1
3. return r return x
4. 3.
5. def calcs(a): 4. y=3
inc(b) inc(b)
print(a) print(a)
SOLUTION
Output Global names : invaders,pos,level,res
error
OUTPUT
Local name : max_level
UnboundLocalError: local
variable 'a' referenced before 25 Built in : len
assignment
QUES 15 QUES 16
def check(n1=1,n2=2):
def func(message,num=1):
n1=n1+n2
print(message*num) n2+=1
print(n1,n2)
func('python')
func('Easy',3) check()
check(2,1)
check(3)
OUTPUT check(2,6)
python check(5,9)
EasyEasyEasy OUTPUT
33
32
53
87
14 10
QUES 17 QUES 18 QUES 21
def oct2other(n):
a=1 def inte(prnc,time=2,rate=0.10):
print("(1)passed octal number:",n)
return(prnc*time*rate)
def f(): print(inte(100,1))
numstring=str(n)
decnum=int(numstring,8)
a=10 print(inte(20,rate=0.50)) print("(2)Number in Decimal:",decnum)
print("(3)Number in binary:",bin(decnum))
print(a) print(inte(20,3,0.12))
print("(4)Number in
print(inte(time=4,prnc=20))
Hexadecimal:",hex(decnum))
num=int(input("(5)Enter an octal number:"))
OUTPUT OUTPUT oct2other(num)
1 10.0
20.0
7.199999999999999 (5)Enter an octal number:5
8.0 (1)passed octal number: 5
(2)Number in Decimal: 5
(3)Number in binary: 0b101
(4)Number in Hexadecimal: 0x5
QUES 22
def retse(init,step):
return init,init+step,init+2*step,init+3*step
QUES 1
FIND THE ERROR ANS
total=0; def sum(arg1,arg2):
def sum(arg1,arg2): total=0
total=arg1+arg2; total=arg1+arg2
print("Total:",total) print("Total:",total)
return total; return total
sum(10,20);
print("Total:",total) sum(10,20)
OUTPUT
Total: 30
QUES 1
def power(b,p):
y=b**p
return y
def calcsquare(x):
a=power(x,2)
OUTPUT
return a 25
n=5
result=calcsquare(n)
print(result)
QUES 4 QUES 5 QUES 5
num=1
def myfuc(): def display():
global num print("Hello",end=' ')
num=10
return num
display()
print(num) print(“Nikhil!")
print(myfuc())
print(num)
OUTPUT OUTPUT
1
10
10
Hello Nikhil!
QUES 6
a=10
y=5
def myfuc():
a=10 OUTPUT
y=5
y=a y=5 a=10
a=2
print("y=",y,"a=",a)
y=10 a=2
print("a+y=",a+y)
return a+y
a+y=12
12
print("y=",y,"a=",a)
print(myfuc()) y=5 a=10
print("y=",y,"a=",a)
QUES 7
Repair this Program ANS
def addem(x,y,z):
def addem(x,y,z): a=x+y+z
return x+y+z return a
print("the answer is",x+y+z) x=1
y=2
z=3
a=addem(x,y,z)
print("the answer is=",a)
OUTPUT
the answer is= 6
QUES 9 QUES 10
OUTPUT OUTPUT
5 times 5 = 25 BLANK
QUES 11 QUES 11 QUES 11
def alpha(n,string='xyz',k=10):
def minus(total,dec) define check() return beta(string)
output=total-dec N=input('Enter N:') return n
i=3 def beta(string)
print(output) return string==str(n)
answer=1+i**4/N
return(output) Return answer print(alpha("Valentine's Day"):)
print(beta(string='true')
def check(): print(alpha(n=5,"Good-bye"):)
def minus(total,dec):
N=int(input('Enter N:')) (5 liya)
output=total-dec i=3
print(output) answer=1+i**4/N
return output return answer
q=10 a=check()
y=6 print(a)
a=minus(q,y)
OUTPUT
Output Enter N:5
4 17.2
QUES 12
def suma(a,b,c,d):
a=1
b=2
c=3
d=4
result=0
result=result+a+b+c+d
return result
def length():
return 4
def mean(a,b,c,d):
return float(suma(a,b,c,d))/length()
print(suma(a,b,c,d),length(),mean(a,b,c,d))
QUES 17
QUES 17
def increment(n): def increment(n):
[Link]([4]) [Link]([49])
return n return n[0],n[1],n[2],n[3]
L=[1,2,3] L=[23,35,47]
M=increment(L) m1,m2,m3,m4=increment(L)
print(L,M) print(L)
print(m1,m2,m3,m4)
print(L[3]==m4)
OUTPUT OUTPUT
[1, 2, 3, [4]] [1, 2, 3, [4]] [23, 35, 47, [49]]
23 35 47 [49]
True