Module - 5 Functions
Module - 5 Functions
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 get_values(15, 8)
The statement return exits a function, optionally passing back a value to the
caller.
def my_function(*person):
print("The youngest child is " + person[3])
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.
x = "global"
def foo(): Output:
print("x inside:", x) x inside: global
foo() x outside: global
print("x outside:", x)
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.
▪ 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.
>>> 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.
# 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]]
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
# 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