Chapter 4
Chapter 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)
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:
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 (,).
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.
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'>
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.
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.
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
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
def Factorial(num):
fact=1
i=1
while i<=num :
fact=fact*i
i=i+1
return fact
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.
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
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.
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.
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
delattr() Deletes the specified attribute (property or method) from the specified object
divmod() Returns the quotient and the remainder when argument1 is divided by
argument2
hasattr() Returns True if the specified object has the specified attribute
(property/method)
map() Returns the specified iterator with the specified function applied to each item
range() Returns a sequence of numbers, starting from 0 and increments by 1 (by default)
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))
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
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
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 :
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 :
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:
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
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
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.
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("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’
Output:
(3+0j)
(3.5+0j)
x = 'print(55)'
eval(x)
Output:
55
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.
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.
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.
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:
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
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 :
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.
- 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 :
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,
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.
It is also possible to import all attributes from a module into the current namespace by using the
following import statement :
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.
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.
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 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.
Example:-
from fractions import Fraction
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:-
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
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
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))
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
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))
import math
a = math.pi/2
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
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.
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']
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 choice() that returns any random element from specified sequence like list,
# tuple, dictionary or string
r4=random.choice(list1)
print("Random Value is",r4)
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.
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:
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:
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]
Python map() function is a built-in function and can also be used with other built-in functions available
in Python.
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.
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.
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.
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.
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.
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.
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.
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)
This file will be placed inside mypack directory and can be left blank or we can put some initialisation
code into it.
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: