notes on Functions and modules
notes on Functions and modules
Shridhar)
A function is a block of organized and reusable program code that performs a single, specific and well
defined task. A function is a block of code which only runs when it is called. We can pass data, known as
parameters into a function. A function can return data as a result.
Functions can be categorized into the following three types
1. Built in function
2. Modules
3. User defined functions
Need for function
1. Dividing the program into separate well defined functions facilitates each function to be written
and tested separately.
2. Understanding coding and testing multiple separate functions are far easier than doing the same
for one huge function .
3. Debugging the programs is easy. When the program is divided into functions.
4. All the libraries in python contain pre-defined and pre tested functions. Which the programmers
are free to use directly in their programs.
5. Big projects can be handled very easily by dividing it into small functions.
6. Like python libraries, programmers can also make their own functions and use then from
different points in the main program .
7. Code reuse is one of the most prominent reason to use functions.
Function definition
1. A function f that uses another function g is known as the called function.
2. The inputs that the function takes are known as arguments/parameters.
3. When a called function returns some results back to calling function, it is said to return that
result. The calling function may or may not pass parameters to the called function, if called
function accepts arguments the calling function will pass parameters else no.
4. Function declaration is a declaration statement that identifies a function with its name, a list of
arguments that it accepts and the type of data it returns.
5. Function definition consists of a function header that identifies the function, followed by the
body of the function containing the executable code for that function.
6. There are three types of functions built in function, anonymous and user defined function. Built
in function are part of python language. User defined function are created by the users using a
key work i.e def
While defining a function we must remember following points.
1. Function block starts with the key word def
2. The key word and parentheses ( ) and a colon after parentheses.
3. Parameters must be placed within parentheses. Through parameters values are passed to the
function. Parameters are optional in case no values are to be passed.
4. A function may have a return statement.
5. We can assign the function name to a variable. Doing this will allow us to call the same function
using the name of that variable.
Function call
Once the basic structure of a function is finalized it can be executed by calling it. The function call
statement invokes the function. When function is invoked the program control jumps to the called
function to execute the statement that are a part of that function. Once the called function is executed
the program control passes back to the calling function.
Syntax :
function _name()
function call statement has following syntax when it accepts parameters.
Function_name(variable1,variable2,variable3,………..)
When the function called the interpreter checks that the correct number and type of arguments are
used in the function call. It also checks the type of the returned value ( if it returns a value to the calling
function )
NOTE: List of variables used in function call is known as the actual parameter list. The actual parameter
list may be variable names, expression, or constants .
Function parameters:
A function can take parameters which are nothing but some values that are passed to it so that the
function can manipulate them to produce the desired result. These parameters are normal variables
with a small difference that the values of these variables are defined ( initialized) when we call the
function and are then passed to the function. Parameters are specified within the pair of parentheses in
the function definition and re separated by commas.
Key points to remember while calling the function.
1. The function name and the number of arguments in the function call must be same as that given
in the function definition.
2. If by mistake the parameters passed to a function are more than that it is specified to accept,
then an error will be returned.
output:
enter the first number : 10
enter the second number:20
sum of 10 and 20 = 30
program to demonstrate that the arguments may be passed in the form of expressions to the called
function.
def xyz(i):
print(“Hello world”,i)
xyz(5+2*3)
output:
Hello world 11
1. The parameters list must be separated with commas.
2. If the function returns a value then it may be assigned to some variable in the calling program
Lets revise:
A=10
B= 20
C=A+B
print (“addition of the numbers “,C)
with function
def add(a,b):
c=a+b
print(“addition of no”,c)
add(10,20)
program with default parameters
def add(a=20,b=10): # default parameters a= 20 and b=10
s=a+b
print(“addition of no”,s)
add()
Nested functions
Function inside another function is called nested function. In this, the inner function can access
variables defined in both outer as well as inner function, but the outer function can access variables
defined only in the outer function . for ex.
def outerfunc():
outervar=10
def innerfunc():
innervar=20
print(“outer variable = “,outervar)
print(“Inner variable = “,innervar)
innerfunc()
print(“Outer variable = “,outervar)
print(“Inner variable = “,innervar) #not accessible
outerfunc() # function call
Return Statement
Return statement returns the value back to caller function. Return statement is used for two things.
1. Returns a value to the caller
2. To end and exit a function and go back to its caller.
3. Return statement cannot be used outside of a function definition once you return a value from a
function it immediately exists that function. Therefore any code written after the return
statement is never executed.
Program on function
PROGRAM NO 1
#program that subtracts 2 nos.using a function
def diff(x,y):
return x-y
a=20
b=10
sub=diff
m=mul
print(sub(a,b))
PROGRAM NO 2
#program that subtracts 2 nos.using a function
def diff(x,y):
return x-y
def mul(x,y):
return x*y
a=20
b=10
add=diff
m=mul
print(add(a,b))
print(m(a,b))
PROGRAM NO 3
#program that displays a string repeatedly using function
def clear():
print('\n'*300)
def fun():
for i in range(4):
print("Hello Students")
clear()
fun()
PROGRAM NO 4
#print strings using function
def prin(str):
"this print a passed string into this function"
print(str)
return;
prin("I am first call to user defied function")
prin("Again second call to the same function")
PROGRAM NO 5
#program to greets to tghe person passed as parameters
def greet(name):
print("hello" + name +"good morning")
#greet()
PROGRAM NO 6
#program to check whether x is even or odd
def evenodd(x):
if(x%2==0):
print ("even")
else:
print ("Odd")
evenodd(3)
evenodd(4)
PROGRAM NO 7
#program to add and multiply 2 nos.
def calsum(x,y):
s= x+y
return s
def calmul(a,b):
m=a*b
return m
num1= float(input("enter first no.:"))
num2= float(input("enter second no:"))
sum=calsum(num1,num2)
mul=calmul(num1,num2)
print ("sum of two given numbers is ",sum)
print(" multiplication of no is:",mul)
PROGRAM NO 8
# program to find simple interest
def si(x,y,z):
sii=(x*y*z)/100
return sii
p=float(input("enter principal :"))
r=float(input("enter rate of int:"))
t=float(input("enter time period:"))
inter=si(p,r,t)
print("simple interest",inter)
PROGRAM NO 9
#WAP using function to check whether two no. are equal or not
def check(a,b):
if(a==b):
return 0
if(a>b):
return 1
if(a<b):
return -1
a=3
b=5
res=check(a,b)
if(res==0):
print("a is equal to b")
if(res==1):
print("a is greater than b")
if(res==-1):
print("a is less than b")
PROGRAM NO 10
# program to swap two no. using function
def swap(a,b):
a,b=b,a
print("after swap:")
print("first number=",a)
print("second number=",b)
a=input("\n enter the first number:")
b=input("\n enter the second number:")
print("before swap:")
print("first no=",a)
print("sescond no =",b)
swap(a,b)
PROGRAM NO 11
#wap to return the average of its arguments
def avg(a,b):
return(a+b)/2.0
a=int(input("enter first no."))
b=int(input("enter second no."))
print("average = ",avg(a,b))
PROGRAM NO 12
#wap using function and return statement to check whether a no
#is even or odd
def evenodd(a):
if(a%2==0):
return 1
else:
return -1
a= int(input("Enter the number:"))
flag=evenodd(a)
if(flag==1):
print("number is even")
if(flag==-1):
print("Number is odd")
PROGRAM NO 12
#wap to convert time into minutes
def clear():
print('\n'*90)
def ttom(hrs,minu):
minu=hrs*60+minu
return minu
h=int(input("enter the hours:"))
m= int(input("enter the minutes:"))
mn=ttom(h,m)
print("minutes=",mn)
PROGRAM NO 13
#wap to calculate simple interest.if customer is a senior citizen
#he is being offered 10% rate of interest. for all other
#customets the ROI is 12%
def interest(p,y,s):
if(s=='y'):
SI=float((p*y*10)/100)
else:
SI=float((p*y*12)/100)
return SI
p=float(input("enter the principal amount:"))
y=float(input("enter the number of years:"))
s=input("Is customer senior citizen(y/n):")
print("Interest:",interest(p,y,s))
PROGRAM NO 14
#wap to calculate the volume of cuboid using default arguments
def volume(l,w=3,h=4):
print("length :",l,"\t width:",w,"\t height:",h)
return l*w*h
print("volume:",volume(4,6,2))
print("volume:",volume(4,6))
print("volume:",volume(4))
PROGRAM NO 15
# program to understand local and global variable
num1 = 10 # globla variable
print("globla variable num1=",num1)
def func(num2): #num2 is function parameter
print("in function - local variable num2=",num2)
num3 = 30 #num3 is a local variable
print("In function - local variable num3=",num3)
func(20) #@ 20 is passed as an argument to the function
print("num1 again =",num1)#globla variable is being accessed
#Error- local variable can't be used outside the function in which it is
defined
print("num3 outside function =",num3)
PROGRAM NO 16
# program to demonstraqte the use of global statement
var="Good"
def show():
global var1
var1 = "Morning"
print("In function var is -",var)
show()
print("Outside function,var1 is-",var1)#accessible as it is
#global variable
print ("var is -",var)
Random module
In programming there are certain situations/applications that involve games or simulations which work
on non deterministic approach. In this situations random numbers are extensively used such as –
pseudorandom numbers on lottery scratch cards.
Computer games involving throwing of a dice ,picking a number, or flipping a coin, shuffling deck of
playing cards etc. in python we need to invoke random module with import statement.
import random
the various functions associated with the module are explained below-
randrange( ) – this method generates an integer between its lower and upper argument. By default, the
lower argument is 0 and upper argument is 1.
For ex.
import random
a= random.randrange(30)
print(a)
program -2
program to select a random subject from a list of subjects
import random
subjects= [“computer science”,”IP”,”physics”,”Accounts”]
ran_index=random.randrange(2)
print(subjects(ran_index)) # in this program 2 is excluded so it generates the randomly “ computer
Science”
random() – this method generates random numbers from 0 to 1 this can also generates floating point
values such as 0.56343284732342
for ex.
import random
ran_no=random.random()
print(“the random number is :”,ran_no)
output: the random number is : 0.29949466847152595
a program to calculate the sum of the digits of a random three digit number