0% found this document useful (0 votes)
16 views48 pages

Chapter 4

The document provides a comprehensive overview of functions in Python, detailing their syntax, definition, and the importance of modular programming. It covers various aspects such as function calling, parameter passing, variable scope, and built-in functions. Additionally, it includes multiple examples to illustrate how to create and use functions effectively.

Uploaded by

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

Chapter 4

The document provides a comprehensive overview of functions in Python, detailing their syntax, definition, and the importance of modular programming. It covers various aspects such as function calling, parameter passing, variable scope, and built-in functions. Additionally, it includes multiple examples to illustrate how to create and use functions effectively.

Uploaded by

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

4.

1 Function
In Python, a function is a group of related statements that performs a specific task. Functions help
break our program into smaller and modular chunks.
As our program grows larger and larger, functions make it more organized and manageable.
Furthermore, it avoids repetition and makes the code reusable.

A] Syntax of Function
def function_name(parameters):
statement(s)

Above shown is a function definition that consists of the following components.


Keyword def that marks the start of the function header.
A function name to uniquely identify the function.
Function naming follows the same rules of writing identifiers in Python.
Parameters (arguments) through which we pass values to a function. They are optional.
A colon (:) to mark the end of the function header.
One or more valid python statements that make up the function body.
Statements must have the same indentation level (usually 4 spaces).
An optional return statement to return a value from the function.

Example of a function
Example 1:
def greet():
"""This function greets the person """
print("Hello")

Example 2:

1 print(“hello 1”)
2 print(“hello 2”)
3 def sayHello( ):
4 print("hello 3")
5 print(“hello 4”)
6 print("hello 5") # Ends sayHello( ) function definition. general/open statement
7 print(''hello 6" ) # general open statement
8 ------------
9 ------------

From above block, note that, line-3 starts sayHello() definition and line-4 and line-5 are two statements
that are part of sayHello() function.
These also has indent.
But line-6 ends the function definition; because it doesn't has indent and written in same vertical axis
of general/open statements in line-1, 2, and 3. Hence, line-6 and line-7 are not part of sayHello( )
function definition. - Above user-defined function sayHello() is defined only for the purpose of
discussion of creating function in Python. Similar to other programming languages, Python functions
can also receive parameters/arguments and can also return. A function can have any numbers of
statements and any logical statements or control flow statements or loops or local variables. For
example, refer following two functions :

Example 3:

def sayHello(): # function to print "Hello all from Python"


print("Hello all from Python")
def operations( ): # function to accept two values and print all arithmetic operations on them
print("Enter 2 values")
a = int (input( ))
b = int (input( ))
print("Adition is :",(a+b))
print("Subtraction is :",(a-b))
print("Multiplication is :",(a*b))
print("Division is :",(a/b))
print("Remainder is :",(a%b))
def check_even_odd( ): # function to check whether entered number is even or odd
print("Enter a number")
num = int (input())
if(num % 2 == 0):
print(num,"is even")
else:
print(num,"is odd")

For ease of understanding of indents, we applied a vertical axis line. It will clear the start and end of
function definition. In similar way, we can define any numbers of functions in a program for above
discussed purposes. But remember that, a function never execution if we don't call it.
B] Function Calling
We know that, to use a function we have to call it. To call a function, simply write that function's name
followed by parenthesis ( ), and by placing required arguments within the parenthesis.
Example,
def sayHello(): # function to print "Hello all from Python"
print("Hello all from Python")
def operations( ): # function to accept two values and print all arithmetic operations on them
print("Enter 2 values")
a = int (input( ))
b = int (input( ))
print("Adition is :",(a+b))
print("Subtraction is :",(a-b))
print("Multiplication is :",(a*b))
print("Division is :",(a/b))
print("Remainder is :",(a%b))
def check_even_odd( ): # function to check whether entered number is even or odd
print("Enter a number")
num = int (input())
if(num % 2 == 0):
print(num,"is even")
else:
print(num,"is odd")
print("Main area starts");
sayHello()
operations()
check_even_odd( )
print("Main area Ends")

Output:
Main area starts
Hello all from Python
Enter 2 values
45
3
Adition is : 48
Subtraction is : 42
Multiplication is : 135
Division is : 15.0
Remainder is : 0
Enter a number
13
13 is odd
Main area Ends
C] Function Arguments and Parameter Passing –
Information can be passed to functions as parameter (also called as argument). These parameters are
specified to function name, but inside the parenthesis. We can add as many parameters as you want,
just separate them with, comma (,).

Example 1: Function with 1 argument


def check_even_odd(num):
if (num%2==0):
print(num,"is even")
else:
print(num,"is odd")
print("main area starts")
check_even_odd(15)
check_even_odd(20)
print("main area ends")

Output:
main area starts
15 is odd
20 is even
main area ends

Note that, the function check_even_odd( ) contains one parameter "num" and we called this function
two time provided one parameter on each calling.
Note that, while calling a function, the numbers of passed parameters must match with declared
parameters.

Example 2: Function with 2 arguments


def operations(a,b): # function to accept two values and print all arithmetic operations on them

print("Addition is :",(a+b))
print("Subtraction is :",(a-b))
print("Multiplication is :",(a*b))
print("Division is :",(a/b))
print("Remainder is :",(a%b))
operations(3,5)

Output:
Addition is : 8
Subtraction is : -2
Multiplication is : 15
Division is : 0.6
Remainder is : 3
Example 3: Function with list as arguments

We can also pass any sequence like List, Tuple, Dictionary and Set to a function and perform any
operations on them.

def show_list_elements(a):
print("List contains")
for i in a:
print(i)

list1 = [10,20,30,40,50]
list2 = [5,15,25,35,45]
print("Passing listl as parameter")
show_list_elements(list1)
print("Passing list2 as parameter")
show_list_elements(list2)
In above code, list1 and 1ist2 are passed as parameter to formal parameter 'a' in two individual calls.
Hence, in first call 'a' receives list1 and in second call 'a' receives list2.

Output:
Passing listl as parameter
List contains
10
20
30
40
50
Passing list2 as parameter
List contains
5
15
25
35
45

Example 4: Function parameters don’t have data types. It automatically considers its data type
based on passed value.

def sample_function(value):
print("Received parameter is" ,value,"and its type is", type(value))
sample_function(10)
sample_function(15.7)
sample_function(True)
sample_function('A')
sample_function("Akshay")
sample_function([10,20,30])
sample_function((40,50,60))
sample_function({"A":"APPLE","B":"BALL"})

Ouput:
Received parameter is 10 and its type is <class 'int'>
Received parameter is 15.7 and its type is <class 'float'>
Received parameter is True and its type is <class 'bool'>
Received parameter is A and its type is <class 'str'>
Received parameter is Akshay and its type is <class 'str'>
Received parameter is [10, 20, 30] and its type is <class 'list'>
Received parameter is (40, 50, 60) and its type is <class 'tuple'>
Received parameter is {'A': 'APPLE', 'B': 'BALL'} and its type is <class 'dict'>

Example 5: Function with default/optional Argument

A default argument is a parameter that assumes a default value if a value is not provided in the function
call for that argument. Any number of arguments in a function can have a default value. But once we
have a default argument, all the arguments to its right must also have default values.

# Python program to demonstrate default arguments


def sample(x=50):
print("x: ",x )

sample () # We call sample() without argument


sample(10) # We call sample() with one arguments, here 10 will update default argument 50

Output:
x: 50
x: 10

Here the first call to sample( ) will print the default value of x i.e. 50 as the argument is not passed.
Second call to sample(10) will update the default value 50 to 10 and value of x which becomes 10 gets
printed.
Example 6: Keyword arguments or kwargs

The keyword argument allows to pass the parameters irrespective of their orders/sequence in
function definition.
The idea is to allow caller to specify argument name with values so that caller does not need to
remember order/sequence of parameters.

#Python program to demonstrate Keyword Arguments


def student(firstname,midname, lastname):
print("First Name is",firstname)
print("Middle name is",midname)
print("Last Name is", lastname)

student(firstname ='Akshay', midname='Anil', lastname ='Somwanshi') # Keyword arguments


student(lastname ='Somwanshi', firstname ='Akshay', midname='Anil') # Keyword arguments

Output:
First Name is Akshay
Middle name is Anil
Last Name is Somwanshi
First Name is Akshay
Middle name is Anil
Last Name is Somwanshi

Example 7: Variable length arguments


We can have variable length arguments to a function, where we can pass different numbers of
arguments on each call.
Syntax:
def func(*args):
#
# here is the body of the function
#

Where func denotes the function's name, the argument args denotes a list of variable-length
parameters.

def sample(*args):
for i in args:
print(i)
print("Main area starts")
print("Calling sample first time with one argument")
sample("Akshay")
print("Calling sample second time with two arguments")
sample("Akshay","Somwanshi")
print("Calling sample third time with three arguments")
sample("Akshay","Anil", "Somwanshi")
print("Calling sample fourth time with one arguments")
sample("Priyanka Akshay Somwanshi")

Output:
Main area starts
Calling sample first time with one argument
Akshay
Calling sample second time with two arguments
Akshay
Somwanshi
Calling sample third time with three arguments
Akshay
Anil
Somwanshi
Calling sample fourth time with one arguments
Priyanka Akshay Somwanshi

Program of Addition using Variable length arguments


def Addition(*args):
sum = 0
for i in args: #beginning of for loop
sum = sum + i
return sum
#printing the values
print(Addition(10, 20)) # 30
print(Addition(10, 20, 30)) # 60
print(Addition(10, 20, 2)) # 32

D] Function Returning Values


Example 1:

def Factorial(num):
fact=1
i=1
while i<=num :
fact=fact*i
i=i+1
return fact

print("Enter the Number")


num= int(input())
a=Factorial(num)
print("Factorial is ", a)

Output:
Enter the Number
5
Factorial is 120

Here factorial () function calculate the factorial of num which is passed as argument and returned
result is received in a.

Example 2: Returning multiple values

def square_cube(num):
sq=num*num
cu=num*num*num
return(sq,cu)
print("Enter the number")
num=int (input())
s,c=square_cube(num)
print("Square is ", s)
print("Cube is ", c)

Output:
Enter the number
5
Square is 25
Cube is 125

E] Scope of Variables
The scope of a variable determines the area of the program where you can access a particular variable.
There are two basic scopes of variables in Python −
Global variables
Local variables

Global vs. Local variables


Variables that are defined inside a function body have a local scope.
This means that local variables can be accessed only inside the function in which they are declared.
A variable declared outside function definition is called Global Variable.
Global variables can be accessed throughout the program body by all functions.
Example:
a=10 # a is global variable
def sample():
b=20 #b is local variable inside function sample
print("Local variable is b =",b)
print("Global Variable is a =",a)

print("Global Variable a=", a)


sample()

Output

Global Variable a= 10
Local variable is b = 20
Global Variable is a = 10

In above example, variable a is global variable and its scope is everywhere in the program. Means we
can access it inside as well as outside the function. But variable b is local variable to sample () function.
Hence its scope is only within the function. So it is accessible only inside sample () and not outside it.

Note:
If you operate with the same variable name inside and outside of a function, Python will treat them as
two separate variables, one available in the global scope (outside the function) and one available in the
local scope (inside the function).

x = 300
def myfunc():
x = 200
print(x)

myfunc()
print(x)

The function will print the local x, and then the code will print the global x.
global keyword
In order to modify the value of a global variable inside a function, refer to the variable by using the
global keyword.

Example : Using global keyword


a=10
def change():
global a # indicates reference to global variable
a=20
print("Initial value of a is",a)
change()
print("Changed value of a is",a)

Output:
Initial value of a is 10
Changed value of a is 20

In above example global keyword is used for a, so its value gets changed.

Differences between Local and Global variables:


Parameter Local Global

Scope It is declared inside a function. It is declared outside the function.

Lifetime It is created when the function starts It is created before the program's
execution and lost when the functions global execution starts and lost when
terminate. the program terminates.

Data sharing Data sharing is not possible as data of Data sharing is possible as multiple
the local variable can be accessed by functions can access the same global
only one function. variable.

Modification of When the value of the local variable is When the value of the global variable
variable value modified in one function, the changes is modified in one function changes
are not visible in another function. are visible in the rest of the program.

Accessed by Local variables can be accessed with You can access global variables by any
the help of statements, inside a statement in the program.
function in which they are declared.

Memory storage It is stored on the stack unless It is stored on a fixed location decided
specified. by the compiler.
4.2 Built in Functions
Python has a set of built-in functions.

Function Description

Data type and object related

abs() Returns the absolute value of a number

all() Returns True if all items in an iterable object are true

any() Returns True if any item in an iterable object is true

ascii() Returns a readable version of an object. Replaces none-ascii characters with


escape character

bin() Returns the binary version of a number

bool() Returns the boolean value of the specified object

bytearray() Returns an array of bytes

bytes() Returns a bytes object

callable() Returns True if the specified object is callable, otherwise False

chr() Returns a character from the specified Unicode code.

classmethod() Converts a method into a class method

compile() Returns the specified source as an object, ready to be executed

complex() Returns a complex number

delattr() Deletes the specified attribute (property or method) from the specified object

dict() Returns a dictionary (Array)

dir() Returns a list of the specified object's properties and methods

divmod() Returns the quotient and the remainder when argument1 is divided by
argument2

enumerate() Takes a collection (e.g. a tuple) and returns it as an enumerate object

eval() Evaluates and executes an expression


exec() Executes the specified code (or object)

filter() Use a filter function to exclude items in an iterable object

float() Returns a floating point number

format() Formats a specified value

frozenset() Returns a frozenset object

getattr() Returns the value of the specified attribute (property or method)

globals() Returns the current global symbol table as a dictionary

hasattr() Returns True if the specified object has the specified attribute
(property/method)

hash() Returns the hash value of a specified object

help() Executes the built-in help system

hex() Converts a number into a hexadecimal value

id() Returns the id of an object

input() Allowing user input

int() Returns an integer number

isinstance() Returns True if a specified object is an instance of a specified object

issubclass() Returns True if a specified class is a subclass of a specified object

iter() Returns an iterator object

len() Returns the length of an object

list() Returns a list

locals() Returns an updated dictionary of the current local symbol table

map() Returns the specified iterator with the specified function applied to each item

max() Returns the largest item in an iterable

memoryview() Returns a memory view object

min() Returns the smallest item in an iterable


next() Returns the next item in an iterable

object() Returns a new object

oct() Converts a number into an octal

open() Opens a file and returns a file object

ord() Convert an integer representing the Unicode of the specified character

pow() Returns the value of x to the power of y

print() Prints to the standard output device

property() Gets, sets, deletes a property

range() Returns a sequence of numbers, starting from 0 and increments by 1 (by default)

repr() Returns a readable version of an object

reversed() Returns a reversed iterator

round() Rounds a numbers

set() Returns a new set object

setattr() Sets an attribute (property/method) of an object

slice() Returns a slice object

sorted() Returns a sorted list

@staticmethod() Converts a method into a static method

str() Returns a string object

sum() Sums the items of an iterator

super() Returns an object that represents the parent class


tuple() Returns a tuple

type() Returns the type of an object

vars() Returns the __dict__ property of an object

zip() Returns an iterator, from two or more iterators


4.2.1 Datatype and Object Related Functions
1. type( ) : Returns the type (Datatype) of parameter value/object.
a= 10
b = True
c= 16.55
d = [10,20,30]
print("Type of a is :",type(a))
print("Type of b is :",type(b))
print("Typee of c is :",type(c))
print("Typee of d is :",type(d))

Output:
Type of a is : <class 'int'>
Type of b is : <class 'bool'>
Typee of c is : <class 'float'>
Typee of d is : <class 'list'>

2. abs( ) : Returns the absolute value of provided number. A negative value's absolute value results
positive. Refer following example statements :

print(abs(15))
print(abs(-15))

Output:
15
15

3. all( ) : The python all() function accepts an iterable object (such as list, dictionary, etc.).
It returns true if all items in passed iterable are true. Otherwise, it returns False.
If the iterable object is empty, the all() function returns True.
An empty string results Boolean false.

list1= [1, 3, 4, 6] #will return true, because all values are True
list2= [0, 1, 2] #will return false, because 0 is False
list3= [True,True] # will return True, because all values are True
list4=[True,False] # will return False, because one value is False
list5 = [False, False] #will return False, because both values are False
list6 = ["Hi",""] #will return False, empty String is considered as False

print(all(list1))
print(all(list2))
print(all(list3))
print(all(list4))
print(all(list5))
print(all(list6))

Simply, it is like logical AND operator.

4. any( ): Return True if any element of the iterable(List, Tuple, String, etc) is true, otherwise returns
False. If the iterable is empty, return False.

list1= [1, 3, 4, 6] #will return true, because all values are True
list2= [0, 1, 2] #will return true, because two values are is True
list3= [True,True] # will return True, because all values are True
list4=[True,False] # will return True, because one value is True
list5 = [False, False] #will return False, because both values are False

print(any(list1))
print(any(list2))
print(any(list3))
print(any(list4))
print(any(list5))

5. callable( ) : This function returns True if the the object passed is callable, otherwise False. In other
words, it returns True if specified parameter is a function name and is callable otherwise False.

Example:
print("type is callable :",callable(type)) # will return True. because type is a function and is callable
print("all is callable :",callable(all)) # Will return True, because all is a function and is callable
print("[10,20,30] is callable :",callable([10,20,30])) # will return False, because a list is not callable
print("'Ravi' is callable :",callable("Ravi")) #will return False, because a string is not callable

Output:
type is callable : True
all is callable : True
[10,20,30] is callable : False
'Ravi' is callable : False

6. isinstance( ) : This function returns True, if specified object is an instance of specified class;
otherwise returns False.

a=10
print("a is instance of int :",isinstance(a,int))
list1= [10,20,30]
print("list1 is instance of list :",isinstance(list1,list))
print("list1 is instance of tuple :",isinstance(list1,tuple))
tuple1= (10,20,30)
print("tuple1 is instance of list :",isinstance(tuple1,list))
print("tuple1 is instance of tuple :",isinstance(tuple1,tuple))

Output:
a is instance of int : True
list1 is instance of list : True
list1 is instance of tuple : False
tuple1 is instance of list : False
tuple1 is instance of tuple : True

7. id( ) : This function returns the id of an object. For example :


list1=[10,20,30]
print("ID of listl is : ",id(list1))
list2=[40,50,60]
print("ID of list2 is : ",id(list2))
tuple1 = (70,80,90)
print("ID of tuplel is : ",id(tuple1))

Output
ID of listl is : 2208845057152
ID of list2 is : 2208837914432
ID of tuplel is : 2208844867776
Above output will vary on each execution

8. hasattr( ) This function returns True if the specified object has the specified attribute (data member
or member function); otherwise returns False.

class Test:
x= 10
y= 20
def method1(self):
pass
def method2(self):
pass
print("Class Test has attribute x :",hasattr(Test,'x'))
print("class Test has attribute y :",hasattr(Test,'y'))
print("class Test has attribute z :",hasattr(Test,'z'))
print("class Test has attribute method1 :",hasattr(Test,'method1'))
print("class Test has attribute method2 :",hasattr(Test,'method2'))
print("class Test has attribute method3 :",hasattr(Test,'method3'))

Output:
Class Test has attribute x : True
class Test has attribute y : True
class Test has attribute z : False
class Test has attribute method1 : True
class Test has attribute method2 : True
class Test has attribute method3 : False

4.2.2 Data Conversion Functions


9. bin( ) : This function returns the binary conversion of specified integer parameter. For example :

print("Binary equivalent of 7 is :",bin(7))


print("Binary equivalent of 15 is :",bin(15))

Output:
Binary equivalent of 7 is : 0b111
Binary equivalent of 15 is : 0b1111

10. hex( ) : This function returns the hexa-decimal conversion of specified integer parameter. For
example :

print("Hexa-Decimal equivalent of 7 is :",hex(7))


print("Hexa-Decimal equivalent of 15 is :",hex(15))

Output:
Hexa-Decimal equivalent of 7 is : 0x7
Hexa-Decimal equivalent of 15 is : 0xf

11. oct( ) : This function returns the octal conversion of specified integer parameter. For example :

print("Octal equivalent of 7 is :",oct(7))


print("Octal equivalent of 15 is :",oct(15))

Output:
Octal equivalent of 7 is : 0o7
Octal equivalent of 15 is : 0o17

12. bool(): This function returns the Boolean equivalent of specified parameter. Any non-zero value is
considered as True and only zero(0), False and Empty string is considered false. For Example:

print("Boolean equivalent of 15 is :",bool(15))


print("Boolean equivalent of -1 is :",bool(-1))
print("Boolean equivalent of 3.66 is :",bool(3.66))
print("Boolean equivalent of 0.01 is :",bool(0.01))
print("Boolean equivalent of 'Akshay' is :",bool('Akshay'))
print("Boolean equivalent of Empty string is :",bool(""))
print("Boolean equivalent of False is :",bool(False))
print("Boolean equivalent of 0 is :",bool(0))

Output:
Boolean equivalent of 15 is : True
Boolean equivalent of -1 is : True
Boolean equivalent of 3.66 is : True
Boolean equivalent of 0.01 is : True
Boolean equivalent of 'Akshay' is : True
Boolean equivalent of Empty string is : False
Boolean equivalent of False is : False
Boolean equivalent of 0 is : False

13. float(): This function converts and returns provided parameter value into ‘float’. For Example

print("float equivalent of 3.15 is :",float(3.15))


print("float equivalent of 3 is :",float(3))
print("float equivalent of '3' is :",float("3"))
print("float equivalent of False is :",float(False))
print("float equivalent of True is :",float(True))

Output:
float equivalent of 3.15 is : 3.15
float equivalent of 3 is : 3.0
float equivalent of '3' is : 3.0
float equivalent of False is : 0.0
float equivalent of True is : 1.0

Note that, this function can also convert string containing numeric values into float. But that string
should not contain any alphabet or symbol. Otherwise it will show ’ValueError’

14. int(): This function converts and returns provided parameter value into ‘int’. For Example

print("int equivalent of 3.15 is :",int(3.15))


print("int equivalent of 3 is :",int(3))
print("int equivalent of '3' is :",int("3"))
print("int equivalent of False is :",int(False))
print("int equivalent of True is :",int(True))

Output:
int equivalent of 3.15 is : 3
int equivalent of 3 is : 3
int equivalent of '3' is : 3
int equivalent of False is : 0
int equivalent of True is : 1

Note that, his function can also convert string containing numeric values into int. But that string should
not contain any alphabet or symbol. Otherwise it will show ’ValueError’

15.list(): This function converts specified data-structure into list and returns.

tuple1=(10,20,30)
set1={40,50,60}
dict1={1:"one",2:"two",3:"three"}
str1="Akshay"
a=list(tuple1)
b=list(set1)
c=list(dict1)
d=list(str1)
print("list conversion of tuple1 is ", a , "and its type is", type(a))
print("list conversion of set1 is ", b , "and its type is", type(b))
print("list conversion of dict1 is ", c , "and its type is", type(c))
print("list conversion of str1 is ", d , "and its type is", type(d))

Output:
list conversion of tuple1 is [10, 20, 30] and its type is <class 'list'>
list conversion of set1 is [40, 50, 60] and its type is <class 'list'>
list conversion of dict1 is [1, 2, 3] and its type is <class 'list'>
list conversion of str1 is ['A', 'k', 's', 'h', 'a', 'y'] and its type is <class 'list'>

16. tuple(): This function converts specified data-structure into tuple and returns.

list1=(10,20,30)
set1={40,50,60}
dict1={1:"one",2:"two",3:"three"}
str1="Akshay"
a=tuple(list1)
b=tuple(set1)
c=tuple(dict1)
d=tuple(str1)
print("tuple conversion of list1 is ", a , "and its type is", type(a))
print("tuple conversion of set1 is ", b , "and its type is", type(b))
print("tuple conversion of dict1 is ", c , "and its type is", type(c))
print("tuple conversion of str1 is ", d , "and its type is", type(d))
Output:

tuple conversion of list1 is (10, 20, 30) and its type is <class 'tuple'>
tuple conversion of set1 is (40, 50, 60) and its type is <class 'tuple'>
tuple conversion of dict1 is (1, 2, 3) and its type is <class 'tuple'>
tuple conversion of str1 is ('A', 'k', 's', 'h', 'a', 'y') and its type is <class 'tuple'>

17. str() : This function converts and returns parameter value into string type.

a=15+15
print(a)
b=str(15)+str(15)
print(b)

Output:
30
1515

18. ord ( ) : This function returns ASCII value of specified character passed as a parameter.

print("ASCII value of A is:", ord('A'))


print("ASCII value of Z is:", ord('Z'))
print("ASCII value of 9 is:", ord('9'))
print("ASCII value of + is:", ord('+'))
print("ASCII value of @ is:", ord('@'))
print("ASCII value of $ is:", ord('$'))

Output:
ASCII value of A is: 65
ASCII value of Z is: 90
ASCII value of 9 is: 57
ASCII value of + is: 43
ASCII value of @ is: 64
ASCII value of $ is: 36

19. chr() : This function returns a related character based on provided ASCII value as parameter.

print("65 is ASCII value of :", chr(65))


print("90 is ASCII value of :", chr(90))
print("122 is ASCII value of :", chr(122))
print("48 is ASCII value of :", chr(48))
print("57 is ASCII value of :", chr(57))
print("43 is ASCII value of :", chr(43))
Output:
65 is ASCII value of : A
90 is ASCII value of : Z
122 is ASCII value of : z
48 is ASCII value of : 0
57 is ASCII value of : 9
43 is ASCII value of : +

4.2.3 Input-Output Functions


20. input() : Accepts input from the user. The default datatype of read/input value is “str ". Hence, if
required, we can change the type of input value by using any of the functions discussed in 4.2.2.

print("Enter number")
a=input()
print("Type of a is", type(a))

Above code will ask the end user to enter value and returns datatype of entered value. Output will be:
Enter number10
Type of a is <class 'str'>

Here is another example, that converts input default “str” value to “int” and prints its square.
print("Enter number")
a=int(input())
sq=a*a
print("Type of a is", type(a))
print("Square of a is", sq)

Output
Enter number
10
Type of a is <class 'int'>
Square of a is 100

We will not get square, if the input 10 did not get converted into ‘int’. It will show ‘TypeError’

21. print() : This function prints to the standard output device.


print(“Hello”)
4.2.4 Files and Expression Related
22. complex() : Returns complex number of specified parameter.
a=complex(3)
print(a)
b=complex(3.5)
print(b)

Output:
(3+0j)
(3.5+0j)

23. eval() : Evaluates and executes an expression provided as parameter string.

x = 'print(55)'
eval(x)

Output:
55

4.2.5 Class and Inheritance Related:


24. staticmethod() : This function can externally converts a non-static member function into a static
member function.

class Test:
def sayhi():
print("Hi")
Test.sayhi=staticmethod(Test.sayhi)
Test.sayhi

25. issubclass(): Takes two class names as parameter. If first specified class is a subclass of second
specified class then it returns True; otherwise returns False.

class A:
pass
class B(A):
pass
print("Class A is subclass of B :", issubclass(A,B))
print("Class B is subclass of A :", issubclass(B,A))

Output:
Class A is subclass of B : False
Class B is subclass of A : True
4.2.6 Mathematical Functions
26. sum() : Returns sum of all elements of specified sequence. This function takes sequence as
parameter.

list1=[10,20,30]
tuple1=(40,50,60)
print("Sum of elements of list 1 is", sum(list1))
print("Sum of elements of tuple 1 is", sum(tuple1))
Output:
Sum of elements of list 1 is 60
Sum of elements of tuple 1 is 150

27. max(): This function returns largest item from specified sequence.

list1=[10,20,30]
tuple1=(40,50,60)
print("Largest elements of list 1 is", max(list1))
print("Largest of elements of tuple 1 is", max(tuple1))

Output:
Largest elements of list 1 is 30
Largest of elements of tuple 1 is 60

28. min(): This function returns smallest item from specified sequence.

list1=[10,20,30]
tuple1=(40,50,60)
print("Smallest elements of list 1 is", min(list1))
print("Smallest of elements of tuple 1 is", min(tuple1))

Output:
Smallest elements of list 1 is 10
Smallest of elements of tuple 1 is 40

29. pow(): This function obtains and returns the value of base raised to power. This function requires
two parameter, first is base and second is power.

print("2 raised to 5 is ", pow(2,5))

Output:
2 raised to 5 is 32
30. range() : This function returns specific sequence of numbers based on specific start_value to
end_value-1 by processing on specified steps.

print("Range (1,10) will result as :",list (range(1,10)))


print("Range (1,10,+2) will result as :",list (range(1,10,+2)))
print("Range (1,10,+4) will result as :",list (range(1,10,+4)))
print("Range (10,1,-2) will result as :",list (range(10,1,-2)))

Output:
Range (1,10) will result as : [1, 2, 3, 4, 5, 6, 7, 8, 9]
Range (1,10,+2) will result as : [1, 3, 5, 7, 9]
Range (1,10,+4) will result as : [1, 5, 9]
Range (10,1,-2) will result as : [10, 8, 6, 4, 2]
4.3 Python Modules
A module is a file, containing functions, classes and global variables.
A module contains Python definitions and statements.
Grouping related code into a module makes the code easier to understand and we can use it by using
simple import statement.

A] Writing Modules
We don't require any additional effort or syntax of keyword to define a module. Just save your code in a
Python file with extension .py

def add(x,y):
return(x+y)
def sub(x,y):
return(x-y)
def mult(x,y):
return(x*y)
def div(x,y):
return(x/y)
def power(x,y):
return(x**y)
Save above code as "arith_operations.py". After saving above code, the file arith_operotions will behave
as a module and can be imported anytime by using simple import statement.

B] Importing Modules
After defining required module, it can be used in other Python file or other Python module.
Use keyword import to do this.
Ways to import and use a module.

1. Simple import Statement


We can import a module using import statement and access its entities by using the dot operator.
To import, general syntax is :

import module_name

Note that, this simple import statement will not make the entities of modules directly accessible.
Technically, it will only create a separate namespace and link it with current Python file.
To use the entities of imported module, we have use following syntax.

module_name . entity_name

Here is a Python file that imports above module arith_operations and uses its entities.
Example:

import arith_operations # will import above module arithoperations.py


print("Addition of 5 and 7 is :",arith_operations.add(5,7))
print("Subtraction of 5 and 7 is :",arith_operations.subtr(5,7))
print("Multiplication of 5 and 7 is :",arith_operations.mult(5,7))
print("Division of 5 and 7 is :",arith_operations.div(5,7))
print("Result of 5 raised to 7 is :",arith_operations.power(5,7))
Let's call above Python file as "testing_module.py". Note the statements from line-2 to line-6. The
functions defined in module arith_operations are called and used by using dot operator (.).

Output
Addition of 5 and 7 is : 12
Subtraction of 5 and 7 is : -2
Multiplication of 5 and 7 is : 35
Division of 5 and 7 is : 0.7142857142857143
Result of 5 raised to 7 is : 78125

2. Import with Renaming

In above testing_module.py line-1 imports the module arith_operations and used its functions. But if
the name of a module is too large, then we can also import an entire module under an alternate name.
To do this, syntax is :

import module_name as alt_name

Use the keyword 'as' to rename it.


Here is an alternate of above testing_module.py with renamed module.
import arith_operations as a # module arithoperations.py is renamed as a
print("Addition of 5 and 7 is :",a.add(5,7))
print("Subtraction of 5 and 7 is :",a.subtr(5,7))
print("Multiplication of 5 and 7 is :",a.mult(5,7))
print("Division of 5 and 7 is :",a.div(5,7))
print("Result of 5 raised to 7 is :",a.power(5,7))

Output
Addition of 5 and 7 is : 12
Subtraction of 5 and 7 is : -2
Multiplication of 5 and 7 is : 35
Division of 5 and 7 is : 0.7142857142857143
Result of 5 raised to 7 is : 78125
Easy and short name 'a' is used for module arith_operations. Also note the function calling statements
from line-2 to line-6. They are also using new name 'a' to call module's functions. We can use any name
to rename a module, but prefer to make it short and easy, as we did in above example.

3. The from...import Statement / Importing Objects from Modules / Importing


Individual Object

- It is also possible to import specific attribute/member from a module without importing the module
as a whole. The from...import has the following syntax :

from module_name import name-1,name-2,...,name-n

For example, if we want to import only multiplication function from module arith_operations, then it
can be done and used as follows:

from arith_operations import mult # only importing mult( ) from module arith_operation
print(“Multiplication of 8 and 7 is :",mult(8,7))

Note that, in line-1 only mult() is imported from module arith_operations. And line-2 shows the calling
and use of imported mult() function. The difference between this type of import statement and
previous import statements can be seen in line-2, the way how mult() were called. (Means
arith_operations . is not used ). Also read and understand following statement,

from arith_operations import mult, power

As a conclusion, Python's from...import statement lets us import specific attribute(s) from a module
into the current namespace, and makes its part/member of current namespace.

4. Import everything using *

It is also possible to import all attributes from a module into the current namespace by using the
following import statement :

from module_name import *

This provides an easy way to import all the items from a module into the current namespace; however,
the statement should be used carefully. To import all attributes/members of module arith_operations,
we have following is example.

from arith_operations import*


print("Addition of 8 and 7 is :",add(8,7))
print("Subtraction of 8 and 7 is :",subtr(8,7))
print("Multiplication of 8 and 7 is :",mult(8,7))
print("Division of 8 and 7 is :",div(8,7))
print("Result of 8 raised to 7 is :",power(8,7))

This will show following output :


Addition of 8 and 7 is : 15
Subtraction of 8 and 7 is : 1
Multiplication of 8 and 7 is : 56
Division of 8 and 7 is : 1.1428571428571428
Result of 8 raised to 7 is : 2097152

C] Python built-in Modules


Python also provides built-in modules that are used to provide many built-in facilities for ease of
programming. By the way, we can get their list by performing following task in windows command
prompt.
1] Numeric and Mathematical Modules

To perform numeric and mathematical operations Python provides following built-in modules.
1. decimal 2. fractions 3. itertools 4. math 5. operator 6. random

a) decimal

The decimal module provides support for fast correctly rounded decimal floating point arithmetic. It
offers several advantages over the float datatype.
A Decimal instance can represent any number exactly, round up or down, and apply a limit to the
number of significant digits.

Following is an example that demonstrates some of the attributes/functions of this module.

x = 0.1
y = 0.1
z = 0.1
s=x+y+z
print(s)

Output:
0.30000000000000004
To solve this problem, you use the Decimal class from the decimal module as follows:

#import decimal
from decimal import Decimal

x = Decimal('0.1')
y = Decimal('0.1')
z = Decimal('0.1')
s=x+y+z
print(s)

Output:
0.3

The output is as expected.

The Python decimal module supports arithmetic that works the same as the arithmetic you learn at
school.
Unlike floats, Python represents decimal numbers exactly.
• Use the Python decimal module when you want to support fast correctly-rounded decimal
floating-point arithmetic.
• Use the Decimal class from the decimal module to create Decimal object from strings, integers,
and tuples.

log10() : log10() is a Decimal class method which returns the base ten logarithm of the Decimal value.

Example
import decimal
# A string floating point value can be converted into an object of class Decimal, by using its constructor
d1=decimal.Decimal('3.14')
print("Object d1 contains :",d1 )
print( )
# to deal with log10
d2= decimal.Decimal(100)
print("Object d2 is :",d2)
print(d2,"log 10 :",d2.log10( ))

Output:
Object dl contains : 3.14

Object d2 is : 100
100 log 10 : 2
b) fractions

This module provides support for rational number arithmetic. It allows to create a Fraction instance
from integers, floats, numbers, decimals and strings.
Fraction Instances : A Fraction instance can be constructed from a pair of integers, from another
rational number, or from a string.
The default value of the numerator is 0 and denominator is 1. It raises ZeroDivisionError when the
denominator is 0.

creating fraction instance:-

class fractions.Fraction(numerator=0, denominator=1) :

Example:-
from fractions import Fraction

print (Fraction(11, 35))


# returns Fraction(11, 35)

print (Fraction(10, 18))


# returns Fraction(5, 9)

print (Fraction())
# returns Fraction(0, 1)

Output:-
11/35
5/9
0

class fractions.Fraction(decimal) :- This method takes the decimal instance and returns fraction the
instance with the same value.
Example:-

from fractions import Fraction


print (Fraction('1.13'))
# returns Fraction(113, 100)

print(Fraction('5.44'))

Output:-
113/100
136/25
c) itertools

This module includes set of functions for working with iterable (sequences) like Lists, Tuples, etc.
Following is an example that demonstrates some of the attributes/functions of this module.

itertools.chain( ) function takes multiple sequences as parameters and returns a single sequence that
produces the contents of all of them as though they came from a single sequence

import itertools
list1 = [10,20,30,40]
tuple1 = ("A","B","C","D")
set1={"x1","x2","x3","x4"}
print("Result of chain( ) function is")
res_list= list(itertools.chain(list1,tuple1,set1))
print(res_list)

Output:
Result of chain( ) function is
[10, 20, 30, 40, 'A', 'B', 'C', 'D', 'x2', 'x4', 'x3', 'x1']

itertools.combinations(iterable, r)
It is used to print all the possible combinations (without replacement) of the iterable which is passed
as argument in the specified group size r in sorted order.
If the input elements are unique, there will be no repeated values in each combination.

import itertools
res_list = list(itertools.combinations([1, 2, 3], 2))
print(res_list)

Output:-
[(1, 2), (1, 3), (2, 3)]

itertools.permutations(iterable, r=None)
A permutation is a collection or a combination of objects from a iterable where the order or the
arrangement of the chosen objects does matter.
permutations() accepts a single iterable and produces all possible permutations (rearrangements) of
its elements.
If r is not specified or is None, then r defaults to the length of the iterable and all possible full-length
permutations are generated.

Example
import itertools
res_list = list(itertools.permutations([1, 2, 3], 2))
print(res_list)
Output:-
[(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]

d) math

This module provides access to the mathematical functions

Euler’s Number
The math.e constant returns the Euler’s number: 2.71828182846.

import math
# Print the value of Euler e
print (math.e)

Output:
2.718281828459045

Pi
You all must be familiar with pi. The pi is depicted as either 22/7 or 3.14. math.pi provides a more
precise value for the pi.

Syntax:
math.pi
import math
# Print the value of pi
print (math.pi)

Output:
3.141592653589793

Numeric Functions

ceil(x) Returns the smallest integer greater than or equal to x.


floor(x) Returns the largest integer less than or equal to x

import math
a = 2.3
print (math.ceil(a))
print (math.floor(a))
Output:-
3
2
factorial()

Using the factorial() function we can find the factorial of a number in a single line of the code.
An error message is displayed if number is not integral.

import math
a=5
print("The factorial of 5 is : ", end="")
print(math.factorial(a))

GCD

gcd() function is used to find the greatest common divisor of two numbers passed as the
arguments.

import math
a = 15
b=5
# returning the gcd of 15 and 5
print ("The gcd of 5 and 15 is : ")
print (math.gcd(a,b))

The gcd of 5 and 15 is : 5

fabs() function returns the absolute value of the number.


import math

a = -10
# returning the absolute value.
print ("The absolute value of -10 is : ", end="")
print (math.fabs(a))

Output:
The absolute value of -10 is : 10.0

Finding the Logarithm

 log(a,b) function returns the logarithmic value of a with base b. If the base is not
mentioned, the computed value is of the natural log.
 log2(a) function computes value of log a with base 2.
 log10(a) function computes value of log a with base 10.
import math
print ("The value of log 2 with base 3 is : ", end="")
print (math.log(2,3))
print ("The value of log2 of 16 is : ", end="")
print (math.log2(16))
print ("The value of log10 of 10000 is : ", end="")
print (math.log10(10000))

Finding the Square root


sqrt() function returns the square root of the number.
print(math.sqrt(4)) #print 2.0

Finding sine, cosine, and tangent


sin(), cos(), and tan() functions returns the sine, cosine, and tangent of value passed as the
argument. The value passed in this function should be in radians.

import math
a = math.pi/2

print ("The value of sine of pi/2 is : ", end="")


print (math.sin(a))

a = math.pi/3
# returning the value of cosine of pi/3
print ("The value of cosine of pi/3 is : ", end="")
print (math.cos(a))

a = math.pi/4
# returning the value of tangent of pi/4
print ("The value of tangent of pi/6 is : ", end="")
print (math.tan(a))

Output:-
The value of sine of pi/2 is : 1.0
The value of cosine of pi/3 is : 0.5000000000000001
The value of tangent of pi/6 is : 0.9999999999999999

Converting values from degrees to radians and vice versa

 degrees() function is used to convert argument value from radians to degrees.


 radians() function is used to convert argument value from degrees to radians.
e) operator
Python has predefined functions for many mathematical, logical, relational, bitwise etc
operations under the module “operator”.

1. add(a, b) :- This function returns addition of the given arguments.


Operation – a + b.

2. sub(a, b) :- This function returns difference of the given arguments.


Operation – a – b.

3. mul(a, b) :- This function returns product of the given arguments.


Operation – a * b.

4. truediv(a,b) :- This function returns division of the given arguments.


Operation – a / b.

5. floordiv(a,b) :- This function also returns division of the given arguments. But the value is
floored value i.e. returns greatest small integer.
Operation – a // b.

6. pow(a,b) :- This function returns exponentiation of the given arguments.


Operation – a ** b.

7. mod(a,b) :- This function returns modulus of the given arguments.


Operation – a % b.

8. lt(a, b) :- This function is used to check if a is less than b or not. Returns true if a is less than
b, else returns false.
Operation – a < b.

9. le(a, b) :- This function is used to check if a is less than or equal to b or not. Returns true if a
is less than or equal to b, else returns false.
Operation – a <= b.

10. eq(a, b) :- This function is used to check if a is equal to b or not. Returns true if a is equal
to b, else returns false.
Operation – a == b.

11. gt(a,b) :- This function is used to check if a is greater than b or not. Returns true if a is
greater than b, else returns false.
Operation – a > b.
12. ge(a,b) :- This function is used to check if a is greater than or equal to b or not. Returns
true if a is greater than or equal to b, else returns false.
Operation – a >= b.

13. ne(a,b) :- This function is used to check if a is not equal to b or is equal. Returns true if a is
not equal to b, else returns false.
Operation – a != b.

Example:
import operator
list1=[10,20,30,40,50]
list2=['x','y','z','p','q','r']

# Use of contains() to check presence of element in list


print("list1 contains 20:",operator.contains(list1,20))

# Use of add(),sub(),mul(),truediv(),floordiv() to perform basic arithmetic operations


print("Addition of 10 and 20 is",operator.add(10,20))
print("Subtraction of 10 and 20 is",operator.sub(10,20))
print("Multiplication of 10 and 20 is",operator.mul(10,20))
print("True Division of 10 and 20 is",operator.truediv(10,20))
print("Floor Division of 10 and 20 is",operator.floordiv(10,20))

# Use of concat() to concatenate 2 lists


list3=operator.concat(list1,list2)
print("Final list after concatenation is : ",list3)

Output
list1 contains 20: True
Addition of 10 and 20 is 30
Subtraction of 10 and 20 is -10
Multiplication of 10 and 20 is 200
True Division of 10 and 20 is 0.5
Floor Division of 10 and 20 is 0
Final list after concatenation is : [10, 20, 30, 40, 50, 'x', 'y', 'z', 'p', 'q', 'r']

f) random
This module generate fast pseudorandom number generated based on ‘ Mersenne Twister Algorithm’ .
import random
list1=[5,15,25,35,45,55]
# Use of randint() that returns random number from given range
r1=random.randint(1,10)
print("Random Value is",r1)

# Use of randrange() that returns random number from given range


# It will exclude range’s end value
r2=random.randrange(1,10)
print("Random Value is",r2)

# Use of random() that returns any random floating point value


r3=random.random()
print("Random Value is",r3)

# Use of choice() that returns any random element from specified sequence like list,
# tuple, dictionary or string
r4=random.choice(list1)
print("Random Value is",r4)

Output for first run :


Random Value is 10
Random Value is 1
Random Value is 0.5488994017793088
Random Value is 25

Output for second run :


Random Value is 4
Random Value is 7
Random Value is 0.842618646768368
Random Value is 35
Note: Output varies as the module generates random numbers.
2] Functional Programming Module

Functional Programming is a popular programming paradigm that is closely related to computer


science’s mathematical foundations. Actually, there is no strict definition of a functional programming
but however, we consider them to be language that uses functions to transform data.

Functional programming is a programming paradigm in which code is structured primarily in the form
of functions.
It uses functions to transform data.
Python is not a functional programming language but it includes some of its concepts along with other
programming concepts.
With Python, it's easy to write code in a functional style, which may provide the best solution for the
task at hand.

In this section we will discuss four very famous and commonly used functions.
1. lambda expression 2. map function 3. filter function 4. reduce function

a) lambda expression

In Python, a lambda function is a special type of function without the function name.
In general, we use keyword 'def' to define a function and similarly keyword 'lambda' is used to create
lambda expressions.
It is also called as Anonymous Functions.

To create lambda expression,

lambda parameter : expression

A lambda function is a one line function that solves and returns expression result based on
provided parameter.
Let us make one comparison between a function and lambda expression, defined for obtaining cube of
parameter.

def get_cube(num):
return num*num*num
print(get_cube(5)) # prints 12.5

A user-defined function get_cube( ) is defined (line-1 and line-2) with one parameter 'num' that returns
cube of num. Line-3 calls get_cube with parameter and prints.
For the same, lambda expression can be written as 4:

res = lambda num:num*num*num


print(res(5))
Lambda definition does not include a ‘return’ statement; it always contains an expression which is
returned. We can also put a lambda definition anywhere a function is expected, and we don't have to
assign it to a variable at all. This is the simplicity of lambda functions. A lambda statement can have any
numbers of parameters.
Following are simple single lambda expression statements with output.

Example1 : Python lambda Function without parameter


# declare a lambda function
greet = lambda : print('Hello World')
# call lambda function
greet()

Output: Hello World

Example 2: Python lambda Function with an Argument

addition =lambda x, y : x + y
print("Addition of 10 and 20 is :",addition(10 20))

Will result as :
Addition of 10 and 20 is : 30

Example 3 :
pwr = lambda x, y: x ** y
print("2 raised to 5 is :",pwr(2, 5))

Will result as :
2 raised to 5 is 32

Example 4:

is_even = lambda m : m%2==0


print("15 is even : ",is even(15))
print("20 is even :",is even(20))
Will result as :
15 is even False
20 is even : True
b) map Function
The map() function takes two inputs as a function and an iterable object.
The function that is given to map() will iterate over all the values present in the iterable object given.
Syntax
map(function, iterables)

function The function to execute for each item


iterable A sequence, collection or an iterator object.

Examples: map()function to get the square of each of the items in list1.

def squares(n):
return (n*n)

list1 = [1,2,3,4,5]

res = map(squares,list1)
print("After mapping squares( ) with list1 ")
print("resulting list is :", list(res))

Output
After mapping squares( ) with list1
resulting list is : [1, 4, 9, 16, 25]

Using map() with Python built-in functions

Python map() function is a built-in function and can also be used with other built-in functions available
in Python.

Example:- Using map() with sqrt() of math module


from math import sqrt
list1 = [1,4,9,16,25]
res = map(sqrt,list1)
print("After mapping sqrt with list1 ")
print("resulting list is :", list(res))

map( ) function is can also be used with two lists and one function.

def addition(x,y):
return (x+y)
list1 = [10,20,30,40,50,60]
list2 = [5,15,25,35,45,55]
res_list = map(addition, list1, list2)
print(list(res_list))
Output
[15, 35, 55, 75, 95, 115]

The numbers of list depends on numbers of parameter of function. In above example, the addition( )
function has two parameters; therefore we passed two lists in map( ). The co-ordination of list
elements are based on index numbers. Hence, both lists must be of same size.

We can also use lambda expressions with map.


Example 1:-
# Double all numbers using map and lambda

numbers = (1, 2, 3, 4)
result = map(lambda x: x + x, numbers)
print(list(result))

Output:
[2, 4, 6, 8]

Example 2:-
numbers = (1, 2, 3, 4)
result = map(lambda num:num*num*num, numbers)
print(list(result))

c) Filter Function

The filter() function selects elements from an iterable (list, tuple etc.) based on the output of a function.
The function is applied to each element of the iterable and if it returns True, the element is selected by
the filter() function.
Syntas:-
filter(function, sequence)
Parameters:
function: function that tests if each element of a sequence true or not.
sequence: sequence which needs to be filtered, it can be sets, lists, tuples, or containers of any
iterators.
Returns:
returns an iterator that is already filtered.
Example
def odd_elements(num):
if(num%2 !=0):
return True

list1 = [5,7,22,97,54,62,77,23,61]
res_list = list(filter(odd_elements,list1))
print(res_list)
Output
[5,7,97,77,23,61]
Line 5 calls odd_elements() function and passes elements oflist1, one by one and generates resulting
list of elements only for which the odd_elements() returned True.
It is normally used with Lambda functions to separate list, tuple, or sets.
# a list contains both even and odd numbers.
seq = [0, 1, 2, 3, 5, 8, 13]
# result contains odd numbers of the list
result = filter(lambda x: x % 2 != 0, seq)
print(list(result))
# result contains even numbers of the list
result = filter(lambda x: x % 2 == 0, seq)
print(list(result))

Output:-
[1, 3, 5, 13]
[0, 2, 8]

d) Reduce Function

The built-in module functools provides reduce( ) function. The reduce() function takes a function name
and a iterable as argument.
It take an existing function, apply it cumulatively to all the items in an iterable, and generate a single
final value.

How reduce function works in python:


The function passed as an argument is applied to the first two elements of the iterable.
After this, the function is applied to the previously generated result and the next element in the
iterable.
This process continues until the whole iterable is processed.
The single value is returned as a result of applying the reduce function on the iterable.

from functools import reduce


list1 = [47,11,42,13,17]
res = reduce(lambda x , y : x+y, list1 )
print(res)

Output:-
130
Explaination:-The lambda expression is having two parameters, therefore first two parameters are
passed to lambda expression (i.e. 47 and 11) and their result is added to the third element (i.e. 58 + 42)
and their result to the fourth element (i.e. 100 + 13) , and this goes on till the end of the list.
4.4 Namespaces and Scoping
A namespace is a system that has a unique name for each and every object in Python and will
not lead to conflict..
An object might be a variable or a method.

Python implements namespaces in the form of dictionaries.


It maintains a name-to-object mapping where names act as keys and the objects as values.
Multiple namespaces may have the same name but pointing to a different variable.

Types of namespace:-
Local Namespace
This namespace covers the local names inside a function.
Python creates a new namespace whenever a function is called and executed in a program. That
namespace is local to the function and remains in existence until the function terminates.

Global Namespace
This namespace covers the names from various imported modules used in a project. Python creates
this namespace for every module included in your program. It’ll last until the program ends.

Built-in Namespace
This namespace covers the built-in functions and built-in exception names. Python creates it as the
interpreter starts and keeps it until you exit.
A lifetime of a namespace depends upon the scope of objects, if the scope of an object ends, the lifetime
of that namespace comes to an end. Hence, it is not possible to access the inner namespace’s objects
from an outer namespace.

4.5 Python Packages


A python package is a collection of modules. Modules that are related to each other are mainly put in
the same package. When a module from an external package is required in a program, that package can
be imported and its modules can be put to use. Similar, as a directory can contain sub-directories and
files, a Python package can have sub-packages and modules.

Creating and Exploring Packages

To create a particular directory is a package, we create a file named __init__.py inside it and then it is
considered as a package and we may create other modules and sub-packages within it.
This __init__.py file can be left blank or can be coded with the initialization code for the package.

To create a package in Python, we need to follow these three simple steps:

 First, we create a directory and give it a package name, preferably related to its operation.
 Then we put the classes and the required functions in it.
 Finally we create an __init__.py file inside the directory, to let Python know that the directory is a
package.

Example of Creating Package

Let’s look at this example and see how a package is created. Let’s create a package named mypack and
build two modules in it namely, module1 and module2.

 First we create a directory and name it mypack


 Then we need to create modules

To do this we need to create a file with the name module1.py and create its content by putting this
code into it.

def add(x,y):
print("you accessing module 1")
return(x+y)

Then we create another file with the name module2.py and add the similar type of code to it with
different members.
def mul(x,y):
print("you accessing module 2 ")
return(x*y)

 Finally we create the __init__.py file

This file will be placed inside mypack directory and can be left blank or we can put some initialisation
code into it.

Accessing the Packages using ‘from…import’ in Packages


Whenever we want to access the modules from the package we can use ‘from….import…’ line.

Example:
from mypack import module1, module2
Now we can call the function inside module1 and module2 anywhere.

Now, let’s use the package that we created. To do this make a test.py file in the same directory where
mypack package is located and add the following code to it:

from mypackage import module1,module2


a1=module1.add(10,20)
print(a1)
b1=module2.mul(5,6)
print(b1)

You might also like