Functions in Python ST
Functions in Python ST
Functions in
Python
Need of Function
1. Dividing the program into separate well defined modules .
2. Code reuse is one of the most prominent reason to use functions.
3. Large program follows the DRY principle, that is “Don’t Repeat Yourself “.
4. Onces a function is written , it can be called multiple times within the same
or by a different program.
5. Correspondingly , a bad repetitive code abides by WET principle that is
“Write Everything Twice “ or “We Enjoy Typing”.
6. Function provide better modularity for your application and a high degree
of code reuse .
Function Introduction
Function is a block of organized and reusable program code
that performs a single , specific and well- defined task .
1. Built-in Function
2. User defined function
1
2/17/2023
Python.
Output:
Absolute value of -20 is: 20
users themselves.
def add_numbers(x,y):
sum = x + y
return sum
def function_name():
Statement block
return [expression ]
2
2/17/2023
print('After calling')
Example:
def add(a,b): #function definition
#here a and b are parameters
return a+b
result=add(12,13) #12 and 13 are
arguments
print(result)
Output:25
def add_sub(x,y):
c=x+y
d=x-y
return c,d
print(add_sub(10,5))
Output:
(15, 5)
● The return statement is used to exit a function and go back to the place from
where it was called. This statement can contain expression which gets
evaluated and the value is returned.
● If there is no expression in the statement or the return statement itself is not
present inside a function, then the function will return the None object.
3
2/17/2023
10
result=cube(num)
1000
print(“Cube of “, num , “=” , result)
result=1000
EXAMPLE
def calculete(a,b):
total=a+b
diff=a-b
prod=a*b
div=a/b
mod=a%b
return total,diff,prod,div,mod
4
2/17/2023
a=int(input("Enter a value"))
b=int(input("Enter b value"))
#function call
s,d,p,q,m = calculete(a,b)
print("Sum= ",s,"diff= ",d,"mul= ",p,"div= ",q,"mod= ",m)
Output:
Enter a value 5
Enter b value 6
Sum= 11 diff= -1 mul= 30 div= 0.8333333333333334 mod= 5
● are those variables which are defined in the main body of the program .
● They are visible throughout the program file.
Local Variable:
5
2/17/2023
6
2/17/2023
OUTPUT
Global Variable is 10
In function Local Variable 20
in Function Local Variable 30
Print Global Variable Again 10
Local Variable Again 30
>
1. Required Arguments
2. Keyword Arguments
3. Default Arguments
4. Variable Length Arguments
Required Arguments
● The arguments are passed to a function in correct
position order .
● The number of arguments in the function call
should exactly match with the number of
arguments specified in the function definition .
7
2/17/2023
pankaj
print(“The roll no is”, roll_no) 10
rl=10
mymarks=68.90
display(name1, rl,mymarks)
#Keyword Arguments
● When we call a function with some values, these values get assigned to the
arguments according to their position.
● Python allows functions to be called using keyword arguments. When we call
functions in this way, the order (position) of the arguments can be changed.
(Or)
● If you have some functions with many parameters and you want to specify
only some of them, then you can give values for such parameters by naming
them - this is called keyword arguments -
● we use the name (keyword) instead of the position (which we have been
using all along) to specify the arguments to the function.
8
2/17/2023
EXAMPLE
Output:
a is 3 and b is 7 and c is 10
a is 25 and b is 5 and c is 24
a is 100 and b is 5 and c is 50
Default Arguments
● Python allows users to specify function arguments that can have default values.
● This means that a function can be called with fewer arguments that it is defined
to have.
● If the function accepts three parameters , but function call provide only two
arguments , then the third parameter will be assigned the default ( already
specified) Value
● The default value to an argument is provided by using the assignment
operator(=)
● User can specify default value for one or more argument
9
2/17/2023
display(roll_no=10,name="Pankaj”)
Variable-length arguments
● Sometimes you may need more arguments to process function than you mentioned in
the definition. If we don’t know in advance about the arguments needed in function, we
can use variable-length arguments also called arbitrary arguments.
● For this an asterisk (*) is placed before a parameter in function definition which can
hold non-keyworded variable-length arguments and a double asterisk (**) is placed
before a parameter in function which can hold keyworded variable-length arguments.
● If we use one asterisk (*) like *var, then all the positional arguments from that point till
the end are collected as a tuple called ‘var’ and
● if we use two asterisks (**) before a variable like **var, then all the positional
arguments from that point till the end are collected as a dictionary called ‘var’.
10
2/17/2023
OUTPUT
Ganesh likes to read
Math
PPS
Data Structure
Example
def display(farg,**kwargs):
print('formal argument =',farg)
for x,y in kwargs.items(): #items will give key value pair
print('Key = ',x, ':', 'value = ', y)
display(5, rno = 10)
print()
display(5, rno =10,name = 'Prakash')
Output
formal argument = 5
Key = rno : value = 10
formal argument = 5
Key = rno : value = 10
Key = name : value = Prakash
11
2/17/2023
Example
def display(farg,**kwargs):
print('formal argument =',farg)
for x,y in kwargs.items(): #items will give key value pair
print('Key = ',x, ':', 'value = ', y)
sct = {'A':'hi', 'B':'Hello'}
display(5,**sct)
Output
formal argument = 5
Key = A : value = hi
Key = B : value = Hello
print(“Sum=”, sum(3,5))
12
2/17/2023
Write a Python function that takes two lists and returns True if they have at least
one common member.
output
True
True
None
13
2/17/2023
def display(fun):
return ‘Hi’ + fun
def message()
return ‘How are you?’
print(display(message()))
OUTPUT
Hi How are you?
Documentation String
● Docstring (Documentation String) serve the same purpose as that of comments,
as they are designed to explain code.
Output:
Hello world !!!
def func() The program just print a message.
It will dislay Hello world!!!
“””The program Just prints a message .
print(“Hello world!!!”)
14
2/17/2023
IMPORTANT
● In Python integers, floats, strings and tupes are immutable i.e their data cannot
be modified
● when we try to change their values a new objec is created with the modified
value
● on the other hand lists and dictionaries are mutable
● when we change their data same object is modified and new object is not
created
15
2/17/2023
RECURSIVE FUNCTIONS
#recusive function to calculate Factorial
def factorial(n):
if n == 0:
result = 1
else:
result = n * factorial(n-1)
return result
for i in range(1,11):
print(i, ' ', factorial(i))
OUTPUT
1 1
2 2
3 6
4 24
5 120
6 720
7 5040
8 40320
9 362880
10 3628800
GENERATORS
• Are Functions that return a sequence of values
• It is written like an ordinary function but it uses
‘yield’ statement
16
2/17/2023
Example
def gennum(x,y): def gennum(x,y):
while x<= y: while x<= y:
yield x yield x
x+=1
x+=1
g = gennum(10,20)
g = gennum(10,20)
lst = list(g)
for i in g: for i in lst:
print(i, end =' ') print(i, end =' ')
Introduction to Modules
● Modules allows you to reuse one or more function in your programs, even in the
program in which those functions have not defined .
● Function helps us to reuse a particular piece of code.
● Module is a file with .py extension that has definition of all functions and
variable that you would like to use even in other programs .
● The program in which you want to use functions and variables that defined in
the module will simply import that particular module( or .py file).
● The basic way to use module is to add import module_Name as the first
line of your program then adding module_name.var to access and values
with the name var in the module .
● In above code , we import the sys module using the import statement to
use its functionality related to the python .
17
2/17/2023
print(“PI=”, +pi)
Output :
100
200
18
2/17/2023
localtime = time.asctime(time.localtime(time.time()))
print(calendar.moth(2020,10)
19
2/17/2023
Packages in Python
● Package is a hierarchical file directory structure that has modules and other
packages within it .
● Like modules you can easily create packages in python .
● Every package in python is a directory which must have a special file called
_init_.py.
● This file may not have single line of code.
● It is simply added to indicate that this directory is not an ordinary directory and
contains a python package .
● In your programs you can import a package in the same way as you import any
module .
Program on Package
● To create a package called mypackage , create a directory called
mypackage having the module mymodule.py and the _init_.py file.
● Now to use mymodule in a program you must import it . This can
be two ways
● 1. import mypackage.mymodule
● 2. from mypackage import mymodule
20