Functions

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

Functions

Function
A Function is a subprogram that acts on data and often returns a value.

Functions can be categorized into following three types:

i) Built-in

ii) Modules

iii) User-defined
Built-in Funcions
Built-in Functions are the predefined functions that are already available in
Python. They are always available in the standard library and we don’t have
to import any module for using them.
Some built-in functions in Python are:
A) type conversion functions [ int(), str(), float() ]
B) input()
C) eval()
D) min() and max()
E) abs()
F) type()
G) len()
H) round()
I) range()
Modules
A module is a file containing collection of related functions. They are
also known as libraries.

Some commonly used Python modules are:

i) math module
ii) string module
iii) random module
math module ( import math)
1. ceil()
2. floor()
3. pow()
4. fabs()
5. sqrt()
6. log10()
7. cos()
8. sin()
9. tan()
string module
1. isalpha() 9. isspace()
2. isdigit() 10. istitle()
3. lower() 11. join()
4. islower() 12. swapcase()
5. upper() 13. partition()
6. isupper() 14. ord()
7. lstrip() 15.chr()
8. rstrip()
random module (import random)
1. randrange() - generates an integer between lower limit and upper limit-1. By
default lower argument is 0(including 0) and upper 1.(1 not included)
eg. random.randrange(10) – generates number 0-9
2. random() – generates no between 0 and 1(including 0 excluding 1)
3. randint() – returns and integer number in the given range(both limits inclusive)
4. uniform() – returns a random floating point number in between 2 nos.(a<=x<y)
5.choice() - for making a random selection from a sequence like list, tuple or string.
random.choice(sequence)
6. shuffle() – to swap the contents of a list.
random.shuffle(list)
User – defined Functions
A Function is a subprogram or set of statements that acts on data and
often returns a value.

The use of functions improves a program’s clarity and readability and


makes programming efficient by reducing code duplication and
breaking complex tasks into more manageable pieces.
They are also known as routines,sub-programs,methods,procedures
etc.
How to define and call a Function?
Function definition

def function_name(parameters separated by comma):


statement(s)
[return <values>]

Function call
function_name(parameters if any)
or
Identifiers=function_name(parameters if any)
Functions

def fun(): # function definition


print(“Programming is fun”)

fun() # function call

Output
Programming is fun
Functions
def fun(): # function definition
print(“Programming is fun”)
for I in range(5):
fun() # function call
Output
Programming is fun
Programming is fun
Programming is fun
Programming is fun
Programming is fun
Functions
def area(l,b): # function definition
return a*b
result=area(10,5) # function call
print(result)
print(area(3.5,2))

Output
50
7.0
Functions
def fact(n): # function definition
f=1
for i in range(1,n+1):
f=f*I
return f
no=int(input(“Enter a number”))
print(“factorial=“,fact(no)) # function call

Output
factorial=24
Write a python program to enter the values of n and r and find nCr.
(Note : nCr= n!*r!/(n-r)!)
Sample Program
def fact(n): Output
f=1 enter N4
for i in range(1,n+1): enter r2
f=f*i result = 24.0
return f
N=int(input("enter N"))
r=int(input("enter r"))
print("result
=",fact(N)*fact(r)/fact(N-r))
Program to implement calculator
def calc(a,b): # function definition
Output
add=a+b
sub=a-b
7 3 10 2.5
mul=a*b
7
div=a/b
3
return add,sub,mul,div
10
# function call first method
2.5
p,q,r,s=calc(5,2)
print(p,q,r,s)
# function call second method
result=calc(5,2)
for i in result:
print(i)
Creating modules in python
Create python file calculate.py Create python file test.py as
def sum(a,b): import calculate
return a+b print(calculate.sum(5,2))
def diff(a,b): print(calculate.diff(5,2))
return a-b print(calculate.prod(5,2))
def prod(a,b): print(calculate.div(5,2))
return a*b print(calculate.rem(5,2))
def div(a,b): Output
return a/b 7
def rem(a,b): 3
return a%b 10
2.5
1
Note:
Return statement returns the value of an expression following the
keyword. In the absence of the return statement, the default value
None is returned.
Types of Arguments
There are 4 types of arguments allowed in python:

1. Positional arguments
2. Default arguments
3. Keyword arguments
4. Variable length arguments
1.Positional arguments Sample program
Positional arguments are def subtract(a,b):
arguments passed to a function in
correct positional order. return(a-b)
In this form the number and print(subtract(10,5))
position of the arguments must be print(subtract(5,10))
matched. If we change their order,
the result will be changed.
Output
5
-5
2. Default arguments Sample program
The default arguments def add(a,b=5):
assumes a default value if a value
is not provided in the function call return(a+b)
for that argument. print(add(10,2))
[ default arguments are given at print(add(10))
the right end ]
Output
12
15
Sample program
3. Keyword arguments def fun(name="Arun",msg="good
morning"):
print(name,msg)
fun()
Keyword arguments are the named
arguments with assigned values being fun(name="Kiren")
passed in the function call statement. fun(msg="bye")
fun(name="Neethu",msg="best of luck")
[ Here order of arguments is not fun(msg="All the best",name="Geethu")
important]
Output
Arun good morning
Kiren good morning
Arun bye
Neethu best of luck
Geethu All the best
Sample program
4. Variable length arguments def sum(*n):
In some situations we have to total=0
pass variable number of arguments to a
function. Such type of arguments are for i in n:
called variable length arguments. total=total+i
print(total)
They are declared with “*” before the sum()
argument
sum(10)
sum(10,20)
sum(10,20,30,40,50)

Output
0
10
30
150

You might also like