Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
19 views

Module - 5 Functions

The document discusses functions, modules, and packages in Python. It defines what functions and modules are, how to define and call functions, and how to organize code using modules and packages. Some key points covered include defining functions, passing arguments to functions, global and local variables, anonymous functions, and using functions with lists and filtering.

Uploaded by

Patel Bhagirath
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Module - 5 Functions

The document discusses functions, modules, and packages in Python. It defines what functions and modules are, how to define and call functions, and how to organize code using modules and packages. Some key points covered include defining functions, passing arguments to functions, global and local variables, anonymous functions, and using functions with lists and filtering.

Uploaded by

Patel Bhagirath
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

Functions, Module and Packages in Python

▪ A block of code that performs a specific task

▪ They are useful to organise your script, in particular if you


need to repeat actions (e.g. a complex calculation) several
times

▪ A function can be accessed from different parts of a script or


even from different scripts
In order to use a function, you have first to define it and then to call it

definition arguments (optional)

def MyFunction(arg1, arg2,…):


“documentation”
<instructions> optional

MyFunction(3,5,…)

call
may or may not include a return statement
def triangle_area(b, h):
A = (b*h)/2.0
function
return A body

print triangle_area(2.28, 3.55)

def triangle_area(b, h):


return (b*h)/2.0

print triangle_area(2.28, 3.55)


▪ The statement to define a function is def
▪ A function must be defined and called using brackets
▪ The body of a function is a block of code that is initiated by a colon character
followed by indented instructions
▪ The last indented statement marks the end of a function definition
▪ You can insert in the body of a function a documentation string in quotation marks.
This string can be retrieved using the __doc__ attribute of the function object
▪ You can pass arguments to a function
▪ A function may or may not return a value
1. Define a function with two arguments:
get_values(arg1, arg2)
it should returns the sum, the difference, and the product of arg1 and arg2.

def get_values(arg1, arg2):


s = arg1 + arg2
d = arg1 - arg2
p = arg1 * arg2
return s, d, p

print get_values(15, 8)
The statement return exits a function, optionally passing back a value to the
caller.

A return statement with no arguments is the same as returning None.

The returned value can be assigned to a variable

>>> def j(x,y):


... return x + y
...
>>> s = j(1, 100)
>>> print s
101
>>>
▪ Basically, we can divide functions into the following two types:
▪ Built in Functions:
Functions that are built into Python.
▪ User-Defined Functions:
Functions defined by the users themselves.
▪ Information can be passed into functions as arguments.
▪ Arguments are specified after the function name, inside the parentheses. You can add as many
arguments as you want, just separate them with a comma.
▪ The following example has a function with one argument (fname). When the function is called, we
pass along a first name, which is used inside the function to print the full name:

def my_function(fname): Output:


print(fname + " Raj") Mitul Raj
Vaani Raj
my_function(“Mitul") Veeha Raj
my_function(“Vaani") Dirghayu Raj
my_function(“Veeha")
my_function(“Dirghayu")
*args
If you do not know how many arguments that will be passed into your
function, add a * before the parameter name in the function definition.
This way the function will receive a tuple of arguments, and can access the
items accordingly:

def my_function(*person):
print("The youngest child is " + person[3])

my_function(“Mitul", “Vaani", “Veeha“, “Dirghayu”)


▪ You can also send arguments with the key = value syntax.
▪ This way the order of the arguments does not matter.

def my_function(child2, child1):


print("The youngest child is " )

my_function(child1 = “Veeha", child2 = “Dirghayu")


▪ An anonymous function is a function that is defined without a name.
▪ While normal functions are defined using the def keyword, anonymous functions
are defined using the lambda keyword.
▪ Hence, anonymous functions are also called lambda functions.
Lambda function has following syntax
lambda arguments: expression
Lambda functions can have any number of arguments but only one expression.
The expression is evaluated and returned.
Lambda functions can be used wherever function objects are required.
# Program to show the use of lambda functions
double = lambda x: x * 2
print(double(5)) // Output: 10

In the above program, lambda x: x * 2 is the lambda function. Here x is the argument and x * 2 is the
expression that gets evaluated and returned.
This function has no name. It returns a function object which is assigned to the identifier double. We
can now call it as a normal function.
The statement double = lambda x: x * 2 is nearly the same as:

def double(x):
return x * 2
Use of Lambda function with
▪ We use lambda functions when we require a nameless function for a short period of time.
▪ It is generally use as an argument to a higher-order function (a function that takes in other
functions as arguments).
Example use with filter()
▪ The filter() function in Python takes in a function and a list as arguments.
▪ The function is called with all the items in the list and a new list is returned which contains items
for which the function evaluates to True.

# Program to filter out only the even items from a list


my_list = [1, 5, 4, 6, 8, 11, 3, 12]
new_list = list(filter(lambda x: (x%2 == 0) , my_list))
print(new_list) # Output: [4,6,8,12]
Example use with map()
▪ The map() function in Python takes in a function and a list.
▪ The function is called with all the items in the list and a new list is returned which
contains items returned by that function for each item.
▪ Here is an example use of map() function to double all the items in a list.

# Program to double each item in a list using map()


my_list = [1, 5, 4, 6, 8, 11, 3, 12]
new_list = list(map(lambda x: x * 2 , my_list))
print(new_list) #Output: [2, 10, 8, 12, 16, 22, 6, 24]
▪ Global Variables
▪ A variable declared outside of the function or in global scope is known as a global variable.
▪ Global variable can be accessed inside or outside of the function.
Example:

x = "global"
def foo(): Output:
print("x inside:", x) x inside: global
foo() x outside: global
print("x outside:", x)

You can change value inside function….


Example:
x = "global"
UnboundLocalError: local variable 'x' referenced
def foo():
before assignment
global x
x=x*2 The output shows an error because Python treats x as
print(x) a local variable and x is also not defined inside foo().
foo()
Local Variables
▪ A variable declared inside the function's body or in the local scope is
known as a local variable.
▪ Example: Accessing local variable outside scope

def foo():
y = "local"

foo()
print(y) #Output: NameError: name 'y' is not defined
Global and local variables
Example: Using Global and Local variables in the same code
x = "global " Output:
def foo(): global global
global x local
y = "local In the above code, we declare x as a global and y as a local
x=x*2 variable in the foo(). Then, we use multiplication
operator * to modify the global variable x and we print
print(x) both x and y.
print(y) After calling the foo(), the value of x becomes global
foo() global because we used the x * 2 to print two times global.
After that, we print the value of local variable y i.e local.
Global and local variables with same name
Example:
x=5 Output:
def foo(): local x: 10
x = 10 global x: 5
print("local x:", x)
In the above code, we used the same name x for both
foo() global variable and local variable.
The local scope inside foo() and global scope outside foo().
print("global x:", x)
▪ Nonlocal variables are used in nested functions whose local scope is not defined.
This means that the variable can be neither in the local nor the global scope.
▪ Let's see an example of how a global variable is created in Python.
▪ We use nonlocal keywords to create nonlocal variables.

Example: def outer(): Output:


x = "local" inner: nonlocal
def inner(): outer: nonlocal
nonlocal x We use nonlocal keywords to create a
x = "nonlocal" nonlocal variable.
print("inner:", x) The inner() function is defined in the
scope of another function outer().
inner() Note : If we change the value of a
print("outer:", x) nonlocal variable, the changes appear
outer() in the local variable.
▪ Modules refer to a file containing Python statements and definitions.
▪ A file containing Python code, for example: example.py, is called a module, and
its module name would be example.
▪ We use modules to break down large programs into small manageable and
organized files.
▪ Modules provide reusability of code.
▪ We can define our most used functions in a module and import it, instead of
copying their definitions into different programs.
▪ Let us create a module by creating file as example.py

# Python Module example


def add(a, b):
"""This program adds two
numbers and return the result"""
result = a + b
return result

▪ Here, we have defined a function add() inside a module named example. The
function takes in two numbers and returns their sum.
▪ We can import the definitions inside a module to another module or the interactive interpreter in
Python.
▪ We use the import keyword to do this. To import our previously defined module example, we type
the following in the Python prompt.

>>> import example


This does not import the names of the functions defined in example directly in the current symbol
table. It only imports the module name example there.
Using the module name we can access the function using the dot . operator. For example:

>>> example.add(4,5.5)
9.5
▪ check for Python standard modules
▪ We can import a module using the import statement and access the definitions inside it using the
dot operator as described above. Here is an example.
import math Import all names
print("The value of pi is", math.pi)
from math import *
#Output: The value of pi is 3.141592653589793 print("The value of pi is", pi)
Import module by renaming
#Output: The value of pi is
import math as m 3.141592653589793
print("The value of pi is", m.pi)
from...import statement
We can import specific names from a module without importing the module as a
whole. Here is an example.
from math import pi
print("The value of pi is", pi)
dir() built-in function

▪ We can use the dir() function to find out names that are defined inside a module.
▪ For example, we have defined a function add() in the module example that we had in
the beginning.
▪ We can use dir in example module in the following way:
▪ dir() built-in function
we can see a sorted list of names (along with add). All other names that
>>> dir(example)
begin with an underscore are default Python attributes associated with the
['__builtins__', module (not user-defined).
'__cached__',
For example, the __name__ attribute contains the name of the module.
'__doc__',
>>> import example
'__file__', >>> example.__name__
'__initializing__', 'example'
'__loader__', All the names defined in our current namespace can be found
'__name__', out using the dir() function without any arguments.
>>> a = 1
'__package__',
>>> b = "hello“
'add'] >>> import math
>>> dir()
['__builtins__', '__doc__', '__name__', 'a', 'b', 'math', 'pyscripter']
▪ We don't usually store all of our files on our computer in the same location. We use a well-
organized hierarchy of directories for easier access.
▪ Similar files are kept in the same directory, for example, we may keep all the songs in the
"music" directory. Analogous to this, Python has packages for directories and modules for files.
▪ As our application program grows larger in size with a lot of modules, we place similar modules
in one package and different modules in different packages. This makes a project (program) easy
to manage and conceptually clear.
▪ Similarly, as a directory can contain subdirectories and files, a Python package can have sub-
packages and modules.
▪ A directory must contain a file named __init__.py in order for Python to consider it as a package.
This file can be left empty but we generally place the initialization code for that package in this
file.
Here is an example. Suppose we are developing a game. One possible
organization of packages and modules could be as shown in the figure
below.

Package Module Structure in Python Programming


▪ We can import modules from packages using the dot (.) operator.
▪ For example, if we want to import the start module in the above example, it can be
done as follows:
import Game.Level.start
Now, if this module contains a function named select_difficulty(), we must use the
full name to reference it.
Game.Level.start.select_difficulty(2)
If this construct seems lengthy, we can import the module without the package
prefix as follows:
from Game.Level import start
We can now call the function simply as follows:
start.select_difficulty(2)
▪ Numerical python
▪ NumPy is a general-purpose array-processing package
▪ provides a high-performance multidimensional array
object, and tools for working with these arrays
▪ Fundamental package for scientific computing
▪ useful linear algebra, Fourier transform, and random
number capabilities
▪ Numpy installation
▪ pip install numpy
import numpy as np
Output
# Creating array object
Array is of type: numpy array
arr = np.array( [[ 1, 2, 3],
[ 4, 2, 5]] ) No. dimensions: 2
Shape of array: (2,3)
# Printing type of arr object
print("Array is of type: ", type(arr)) Size of array:6
Array stores element of type : int
# Printing array dimensions (axes)
print("No. of dimensions: ", arr.ndim)

# Printing shape of array


print("Shape of array: ", arr.shape)

# Printing size (total number of elements) of array


print("Size of array: ", arr.size)

# Printing type of elements in array


print("Array stores elements of type: ", arr.dtype)
▪ Slicing:
As arrays can be multidimensional, you need to specify a slice for each
dimension of the array.
import numpy as np

# An array
arr = np.array([[-1, 2, 0, 4],
[4, -0.5, 6, 0],
[2.6, 0, 7, 8],
[3, -7, 4, 2.0]]
temp = arr[:2, ::2]
print ("Array with first 2 rows and alternate"
"columns(0 and 2):\n", temp)
Output: [-1,0],[4,6]]
▪ In this method, lists are passed for indexing for each dimension.
arr = np.array([[-1, 2, 0, 4],
[4, -0.5, 6, 0],
[2.6, 0, 7, 8],
[3, -7, 4, 2.0]]

temp = arr[[0, 1, 2, 3], [3, 2, 1, 0]]


print(temp)

Output :
elements at (0, 3), (1, 2), (2, 1),(3, 0): [ 4. 6. 0. 3.]
▪ This method is used when we want to pick elements from array which
satisfy some condition.
arr = np.array([[-1, 2, 0, 4],
[4, -0.5, 6, 0],
[2.6, 0, 7, 8],
[3, -7, 4, 2.0]]
Cond=arr>1
temp=arr[cond]
Print(temp)

Output: [2,4,4,6,2.6,7,8,3,4,2.0]
We can use overloaded arithmetic operators to do element-wise operation on array
to create a new array. Output:
import numpy as np Adding 1 to every element: [2 3 6
4] Subtracting 3 from each element:
a = np.array([1, 2, 5, 3]) [-2 -1 2 0]
Multiplying each element by 10: [10
# add 1 to every element 20 50 30]
print ("Adding 1 to every element:", a+1) Squaring each element: [ 1 4 25 9]
# subtract 3 from each element Doubled each element of original
print ("Subtracting 3 from each element:", a-3) array: [ 2 4 10 6]
# multiply each element by 10 Original array: [[1 2 3]
print ("Multiplying each element by 10:", a*10) [3 4 5]
# square each element [9 6 0]]
print ("Squaring each element:", a**2) Transpose of array: [[1 3 9]
# modify existing array [2 4 6]
a *= 2 [3 5 0]]
print ("Doubled each element of original array:",a)
# transpose of array
a = np.array([[1, 2, 3], [3, 4, 5], [9, 6, 0]])
print ("\nOriginal array:\n", a)
print ("Transpose of array:\n", a.T)
▪ Many unary operations are provided as a method of ndarray class. Includes max, min, sum, cumsum
import numpy as np
arr = np.array([[1, 5, 6],
[4, 7, 2],
[3, 1, 9]])
# maximum element of array
print ("Largest element is:", arr.max()) //9
print ("Row-wise maximum elements:", arr.max(axis = 1)) //[6 7 9]
# minimum element of array
print ("Column-wise minimum elements:",arr.min(axis = 0)) //[1 1 2]
# sum of array elements
print ("Sum of all array elements:", arr.sum()) //38
# cumulative sum along each row
print ("Cumulative sum along each row:\n", arr.cumsum(axis = 1)) // [1 6 12]
[4,11,13]
[3,4,13]
▪ A=[1,2,3]
▪ B=[4,5,6]
▪ A+B //array addition

▪ A-B // array subtraction

▪ A.dot(B) // array multiplication


▪ There is a simple np.sort method for sorting NumPy arrays

import numpy as np Output:


Array elements in sorted order:
a = np.array([[1, 4, 2], [-1 0 1 2 3 4 4 5 6]
[3, 4, 6],
[0, -1, 5]])

# sorted array
print ("Array elements in sorted order:\n",
np.sort(a, axis = None))
Row-wise sorted array:
# sort array row-wise [[ 1 2 4] [ 3 4 6] [-1 0 5]]
print ("Row-wise sorted array:\n",
np.sort(a, axis = 1))
arr = np.array([[-1, 2, 0, 4],
[4, 5, 6, 0],
[2, 0, 7, 8],
[3, -7, 4, 2],
[45,5,2,9]]
Arr.ndim
Arr.shape
Arr.size
arr[0:2]
arr[0,2]
Arr[[1,2],[1]]
c=arr>3
Temp=arr[c]
arr+=1

You might also like