0% found this document useful (0 votes)
7 views11 pages

07 Functions, Modules

defining functions
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views11 pages

07 Functions, Modules

defining functions
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

FUNCTIONS

A function is a named group of instructions that accomplishes some task.


Four kinds of functions can be created in python :
global functions , local functions , lambda functions , and methods.
Global objects(including functions) are accessible to any code in the same module (i.e the
same .py file) in which the object is created . Global objects can also be accessed from other
modules also
Local functions ( also called nested functions) are functions that are defined inside other
functions . These functions are visible only to the function where they are defined; they are
specifically useful for creating small helper functions that have no use else where.
Lambda functions are expressions, so they can be created at their point of use; however
they are much more limited than normal functions
Methods are functions that are associated with a particular data type and can be used only
in conjunction with the data type.
The general syntax for creating a global (or local ) function is

def functionName( parameters):


suite

The parameters are optional, and if there is more than one they are written as a sequence
of comma-separated identifiers, or as a sequence of identifier=value pairs.
Example

#program to calculate the area of a triangle using Heron’s formula


import math
def heron(a,b,c):
s=(a+b+c)/2
return math.sqrt(s*(s-a)*(s-b)*(s-c))
area= heron(3,4,5)
print(‘Area=%.2f”%area)

Inside the function , each parameter a , b and c is initialized with the corresponding value
that was passed as an argument
When the function is called we must supply all of the arguments . for example heron(3,4,5) .
if we give two few or too many arguments , a TypeError exception will be raised .
when we do a call like this we are said to be using positional arguments , because each
argument passed is set as the value of the parameter in the corresponding position . so in
this case a is set to 3, b to 4 and c to 5
Every function in python returns a value, although it is perfectly acceptable (and common)
to ignore the return value.
The return value is either a single value or a tuple of values, and the values returned can be
collections, so there are no practical limitations on what we can return.
We can leave a function at any point by using the return statement .
if we use return statement with no arguments or if we don’t have a return statement at all ,
the function will return None.
Keyword arguments
Python provides the option of calling any function by the use of keyword arguments.
A keyword argument is an argument that is specified by parameter name, rather than as
positional argument
Default arguments:
Python provides the ability to assign a default value to any function parameter allowing for
the use of default argument. A default argument is an argument that can be optionally
provided

def greet(name=’participant’):
print(‘Dear ‘,name,’welcome to this session’)
greet()
greet(‘Akash’)
greet(name=‘Akash’)

Scope of Variables
Local Scope and Local variables
A local variable is a variable that is only accessible from with in a given function . such
variables are said to have local scope.
In python, any variable assigned a value in a function becomes a local variable of the
function.
Example:

def fun1( ):
x=10
print(‘ x in fun1=’,x)
def fun2( ):
x = 20
print(‘ x in fun2 before call to fun1=’,x)
fun1( )
print(‘x in fun2 after call to fun1=x ’, x )
fun2( )

OUTPUT:

x in fun2 before call to fun1 = 20


x in fun1=10
x in fun2 after call to fun1=20

Global variables and Global scope


A global variable is a variable that is defined outside of any function definition. Such
variables are said to have global scope.

x=10 #global variable


def fun1():
print(x) #global variable x accessed
def fun2():
print(x) #global variable x accessed
fun1() #10
fun2() #10

Variable x is defined out side fun1 and fun2 and therefore “global” to each. As a result , it is
directly accessible by both functions.
global keyword
Usage of global keyword:
=> To define a global variable with inside a function
=> To reference the a global variable inside a function

x=10 #global variable


def fun1():
x=20 #local variable
print(x) #accessing local variable
def fun2():
print(x) #accessing global variable
fun1() #20
fun2() #10

x=10 #global variable


def fun1():
global x #referring the global variable
x=20 #updating the global variable
print(x)
def fun2():
print(x) #accessing global variable
fun1() #20
fun2() #20

def fun1():
x=10 #local variable
print(x)
def fun2():
print(x) #NameError: name ‘x' is not defined
fun1()
fun2()
globals() function
If global variable and local variable they have the same name , then access the global
variable inside the function using globals()

x=10 #global variable


def fun1():
x=20 #local variable
print(x)
print(globals()[‘x’] )
fun1() #20 10

Inner functions
declaring the function inside the another function.

def outer () :
i=10
def inner() :
j=20
print (i)
print (j)
inner() #calling of inner function
print (i)
outer()
nonlocal keyword
inside the inner function to represent outer function variable use nonlocal keyword.

def outer():
var_outer = 10
def inner():
nonlocal var_outer
var_outer=20
print (var_outer)
inner() #calling of inner function
print (var_outer)
outer()

i=10
def outer():
j = 20
def inner():
nonlocal j
global i
i=9999
j=30
print (j)
inner() #calling of inner function
print (j)
outer()
print(i)
ANONYMOUS FUNCTIONS
An anonymous function is a function without a name. In python, an anonymous function is
created with the lambda keyword.

def double(n):
return n*2
print(double(10))

Output: 20

double lambda n: n*2


print(double(10))

output: 20

larger=lambda a,b: a if a>b else b


print(larger(10,47)

output: 47

Lambda functions as keys to sort()

names=["Alan","Gregory","zlatan","jonas","Tom","Augustine"]
names.sort()
print(names)#names will be sorted in alphabetical order

output: ['Alan', 'Augustine', 'Gregory', 'Tom', 'jonas', 'zlatan']

#sort items according the length i


names=["Alan","Gregory","zlatan","jonas","Tom","Augustine"]
names.sort(key=lambda x:len(x))
print(names)

output: ['Tom', 'Alan', 'jonas', 'zlatan', 'Gregory', 'Augustine']


map() function: for every element present in the given sequence, apply some function and
generate new element with the required modification
map(function,sequence)
use map() to apply a function to each element of an iterable

numbers=[1,2,3,4,5]
def square(n):
return n*n
squared_numbers=list(map(square, numbers))
print(squared_numbers)

output: [1, 4, 9, 16, 25]

#lambda function as an argument


numbers=[1,2,3,4,5]
squared_numbers=list(map(lambda n:n*n, numbers))
print(squared_numbers)

output: [1, 4, 9, 16, 25]

num1=[4,5,6]
num2=[5,6,7]
result=list(map(lambda n1,n2:n1+n2, num1,num2))
print(result)

output: [9, 11, 13]

filter() function: we can use filter function to filter the values from the given sequence
based on some condition
filter(function , sequence)
The function argument performs condition checking . use filter to filter out values of an
iterable if they do not match the given condition

numbers=[234,3245,639,550,654]
even_numbers=list(filter(lambda n:n%2==0,numbers))
print(even_numbers)

output: [234, 550, 654]

reduce() function: This function is used to reduce a sequence of elements to a single value
by processing the elements according to a function supplied . It return a single value .
This function is a part of functools module so you have to import it before using
Syntax

from functools import reduce


reduce(function_name, sequence)

from functools import reduce


l=[10,20,30,40,50]
result=reduce(lambda m, n : m + n , l)
print(result)

output: 150

10 20 30 40 50

30 60 100 150

MODULES
A python module is simply a python file(.py). A module can contain any python code . All
Python source files will be contained in a single . py file, and so they are modules as well as
programs. The key difference is that programs are designed to be run, whereas modules are
designed to be imported and used by programs.

my_module.py

print('my_module')
s='python'
def find_index(to_search,target):
''' find the index of a value in a sequence'''
for i,value in enumerate(to_search):
if value==target:
return i
return -1

when we import a file it runs all of the code from the module that we import
intro.py

import my_module
courses=['History','Math','Physics','CompSci']
index=find_index(courses,'Math')
print(index)

output:
my_module
1

RANDOM MODULE
This module defines several functions to generate random numbers.
random () function: generates random numbers in the open interval (0,1)
Example:
from random import *
print(random())
randint() function: generates random integer in closed interval [ x , y ]
Example:
from random import *
print(randint(1,100))
uniform() function : returns random float value in the open interval (x,y)
randrange() function: randrange( [ start ] , stop , [ step ] )
returns a random number from range start to stop. start is inclusive stop is exclusive
start argument is optional and default value is 0
step argument is optional and default value is 1
randrange(10) generates a number from 0 to 9
randrange(1,11) generates a number from 1 to 10
randrange(1,11,2) generates a number from 1,3,5,7,9
choice() function: returns a random object from the given list or tuple
Example:
from random import *
l=["Tea","Coffee","CoolDrink","Pizza","Burger"]
print(choice(l))

PACKAGES
A package is simply a directory that contains a set of modules and a file called __int__.py.

You might also like