Chapter 4
Chapter 4
Syntax of Function
def function_name(parameters):
"""docstring"""
statement(s)
1
Above shown is a function definition that consists of the following components.
2
Data Type Conversion Built in Function
There are several built-in functions to perform conversion from one data type to
another. These functions return a new object representing the converted value.
Sr.No. Function & Description
1 int(x [,base])
Converts x to an integer. base specifies the base if x is a string.
2 long(x [,base] )
Converts x to a long integer. base specifies the base if x is a string.
3 float(x)
Converts x to a floating-point number.
4 complex(real [,imag])
Creates a complex number.
5 str(x)
Converts object x to a string representation.
6 repr(x)
Converts object x to an expression string.
3
7 eval(str)
Evaluates a string and returns an object.
8 tuple(s)
Converts s to a tuple.
9 list(s)
Converts s to a list.
10 set(s)
Converts s to a set.
11 dict(d)
Creates a dictionary. d must be a sequence of (key,value) tuples.
12 frozenset(s)
Converts s to a frozen set.
13 chr(x)
Converts an integer to a character.
14 unichr(x)
Converts an integer to a Unicode character.
15 ord(x)
Converts a single character to its integer value.
16 hex(x)
Converts an integer to a hexadecimal string.
17 oct(x) 4
Converts an integer to an octal string.
s = "10010"
5
s = '4'
# initializing tuple
tup = (('a', 1) ,('f', 2), ('g', 3))
The math module is a standard module in Python and is always available. To use
mathematical functions under this module, you have to import the module
using import.math.
Function Description
copysign(x,
Returns x with the sign of y
y)
fabs(x) Returns the absolute value of x
factorial(x) Returns the factorial of x
import math
print(math.pow(2, 3))
import math
data = 21.6
print(math.ceil(21.6))
import math
number = -21.19
print('The given number is :', number)
print('Floor value is :', math.floor(number))
print('Ceiling value is :', math.ceil(number))
print('Absolute value is :', math.fabs(number)) 13
import math
angleInDegree = 90
angleInRadian = math.radians(angleInDegree)
print('The given angle is :', angleInRadian)
print('sin(x) is :', math.sin(angleInRadian))
print('cos(x) is :', math.cos(angleInRadian))
print('tan(x) is :', math.tan(angleInRadian))
import math
# Return the remainder of x/y
print (math.remainder(9, 2))
print (math.remainder(9, 3))
print (math.remainder(18, 4))
import math
sequence = (2, 2, 2)
#Return the product of the elements
print(math.prod(sequence))
14
User Defined Functions
Syntax:
def functionname( parameters ):
"function_docstring"
function_suite
return [expression]
By default, parameters have a positional behavior, and you need to inform them in
the same order that they were defined.
Example:
def printme( str ):
"This prints a passed string function"
print str
return
15
Calling a Function
16
Function Arguments:
A function by using the following types of formal arguments::
Required arguments
Keyword arguments
Default arguments
Variable-length arguments
Required arguments:
Required arguments are the arguments passed to a function in correct positional order.
def printme( str ): "This prints a passed string"
print str;
return;
printme();
This would produce following result:
Traceback (most recent call last):
File "test.py", line 11, in <module> printme();
TypeError: printme() takes exactly 1 argument (0 given) 17
Keyword arguments:
Keyword arguments are related to the function calls. When you use keyword
arguments in a function call, the caller identifies the arguments by the
parameter name.
This allows you to skip arguments or place them out of order because the Python
interpreter is able to use the keywords provided to match the values with
parameters.
def printme( str ): "This prints a passed string"
print str;
return;
printme( str = "My string");
This would produce following result:
My string
def printinfo( name, age ): "Test function"
18
print "Name: ", name;
print "Age ", age;
Variable-length arguments:
You may need to process a function for more arguments than you specified while
defining the function. These arguments are called variable-length arguments and
are not named in the function definition, unlike required and default arguments.
The general syntax for a function with non-keyword variable arguments is this:
def functionname([formal_args,] *var_args_tuple ):
"function_docstring"
function_suite
return [expression]
Syntax:
def fun():
statements
.
. 21
return [expression]
def add(a, b):
def is_true(a):
# returning boolean of a
return bool(a)
# calling function
res = add(2, 3)
print("Result of add function is {}“,res)
res = is_true(2<5)
print("\nResult of is_true function is {}“,res)
22
Global and Local
Variables
All variables in a program may not be accessible at all locations in that program. This
depends on where you have declared a variable.
The scope of a variable determines the portion of the program where you can access a
particular identifier. 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, and those defined
outside have a global scope.
This means that local variables can be accessed only inside the function in which they are
declared whereas global variables can be accessed throughout the program body by all
functions. When you call a function, the variables declared inside it are brought into scope.
23
total = 0; # This is global variable.
def sum( arg1, arg2 ):
"Add both the parameters"
total = arg1 + arg2;
print "Inside the function local total : ", total
return total;
# Now you can call sum function
sum( 10, 20 );
print "Outside the function global total : ", total
24
Local Variable and Global Variable:
The scope of global variables is the entire program whereas the scope of local variable is
limited to the function where it is defined.
a=10
def fun():
b=20
print(a)
print(b)
fun()
a=20
print(a)
25
Pass statement
In Python programming, the pass statement is a null statement. The difference between
a comment and a pass statement in Python is that while the interpreter ignores a comment
entirely, pass is not ignored.
However, nothing happens when the pass is executed. It results in no operation (NOP)
Suppose we have a loop or a function that is not implemented yet, but we want to implement
it in the future. They cannot have an empty body. The interpreter would give an error. So, we
use the pass statement to construct a body that does nothing.
Example: Example:
def function(args): class abc:
pass pass
26
Return multiple values using commas
In Python, you can return multiple values by simply return them separated by commas
def mulvalues():
return 10, 20, 30.5 Output:
(10, 20, 30.5)
print(mulvalues())
Return list
def test_list():
Output:
return ['abc', 100]
['abc', 100]
<class 'list'>
result = test_list()
print(result) 27
print(type(result))
return Tuples
def test_list():
return ('abc',100) Output:
('abc', 100)
result = test_list() <class 'tuple'>
print(result)
print(type(result))
Return Dictionary
def test_list():
Output:
return {1:'abc',2:100}
{1: 'abc', 2: 100}
<class 'dict'>
result = test_list()
print(result)
print(type(result)) 28
Recursive Functions
A recursive function is defined as a function that calls itself to solve a smaller version of
its task until a final call is made which does not require a call to itself. Every recursive
solution has two major cases, which are as follows:
• base case, in which the problem is simple enough to be solved directly without making
any further calls to the same function.
• recursive case, in which first the problem at hand is divided into simpler sub parts.
Recursion utilized divide and conquer technique of problem solving.
Example:
29
def fact(n):
if n == 1:
return n
Output:
else:
Enter a number: 5
return n*fact(n-1)
The factorial of 5 is 120
# take input from the user
num = int(input("Enter a number: "))
# check is the number is negative
if num < 0:
print("Sorry, factorial does not exist for
negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
print("The factorial of",num,"is",fact(num)) 30
Modules in Python
• A python module can be defined as a python program file which
contains a python code including python functions, class, or
variables.
• In other words, we can say that our python code file saved with the
extension (.py) is treated as the module. We may have a runnable
code inside the python module.
• Modules in Python provides us the flexibility to organize the code in
a logical way.
• To use the functionality of one module into another, we must have
31
to import the specific module.
• In the given example, we will create a module named as file.py which
contains a function func that contains a code to print some message
on the console.
• Let's create the module named as file.py.
def displayMsg(name):
print("Hi "+name);
we need to include this module into our main module to call the
method displayMsg() defined in the module named file.
def divide(a,b):
return a/b;
from calculation import summation # Main.py
#it will import only the summation() from calculation.py
a = int(input("Enter the first number"))
b = int(input("Enter the second number"))
print("Sum = ",summation(a,b)) #we do not need to specify the module name while accessing
summation()
The from...import statement is always better to use if we know the
attributes to be imported from the module in advance. It doesn't let our
code to be heavier. We can also import all the attributes from a module
by using *.
Consider the following syntax.
from <module> import *
35
Importing object of Module
• Programmers can access the objects or the variables present in the module.
• Rather than importing the whole module you can access objects of module into
program
Syntax:
import module_name.member_name
37
Numeric Module
The numbers module defines a hierarchy of numeric abstract base classes which
progressively define more operations. None of the types defined in this module are
intended to be instantiated.
class numbers.Number
The root of the numeric hierarchy. If you just want to check if an argument x is a
number, without caring what kind, use isinstance(x, Number).
The numeric tower
class numbers.Complex
Subclasses of this type describe complex numbers and include the operations that work on the built-
in complex type. These are: conversions to complex and bool, real, imag, +, -, *, /, **, abs(),
conjugate(), ==, and !=. All except - and != are abstract.
real
Abstract. Retrieves the real component of this number.
imag 38
class numbers.Rational
Subtypes Real and adds numerator and denominator properties, which should be in lowest
terms. With these, it provides a default for float().
39
Math Module
Python math module is defined as the most famous mathematical
functions, which includes trigonometric functions, representation
functions, logarithmic functions, etc. Furthermore, it also defines two
mathematical constants, i.e., Pie and Euler number, etc.
math.log()
This method returns the natural logarithm of a given number. It is
calculated to the base e.
Example
import math
number = 2e-7 # small value of of x
print('log(fabs(x), base) is :‘),
math.log(math.fabs(number), 10))
40
math.exp()
This method returns a floating-point number after raising e to the given number.
Example
import math
number = 5e-2 # small value of of x
print('The given number (x) is :', number)
print('e^x (using exp() function) is :', math.exp(number)-1)
math.pow(x,y)
This method returns the power of the x corresponding to the value of y. If value of x is negative or y is not
integer value than it raises a ValueError.
import math
number = math.pow(10,2)
print("The power of number:",number)
math.floor(x)
This method returns the floor value of the x. It returns the less than or equal value to x.
Example:
import math
number = math.floor(10.25201) 41
43
Money = 2000
def AddMoney():
# Uncomment the following line to fix the code:
# global Money
Money = Money + 1
print Money
AddMoney()
print Money
44
Packages
• A package is a hierarchical file directory structure that defines a
single Python application environment that consists of modules and
subpackages and sub-subpackages, and so on.
• As our application program grows larger in size with a lot of
modules, we place similar modules in one package and different
modules in different packages. This makes a project (program) easy
to manage and conceptually clear.
• As a directory can contain subdirectories and files, a Python
package can have sub-packages and modules.
• A directory must contain a file named __init__.py in order for Python
45
Visualization libraries
matplotlib
Seaborn
NumPy:
introduces objects for multidimensional arrays and matrices, as well as
functions that allow to easily perform advanced mathematical and statistical
operations on those objects
SciPy:
collection of algorithms for linear algebra, differential equations, numerical
integration, optimization, statistics and more
built on NumPy
Link: https://www.scipy.org/scipylib/ 51
https://www.w3schools.com/python/scipy/
scipy_intro.php
PYTHON LIBRARIES FOR DATA SCIENCE
Pandas:
adds data structures and tools designed to work with table-like data (similar to
Series and Data Frames in R)
Link: http://pandas.pydata.org/ 52
https://www.w3schools.com/python/pandas/
default.asp
PYTHON LIBRARIES FOR DATA SCIENCE
SciKit-Learn:
provides machine learning algorithms: classification, regression, clustering,
model validation etc.
Link: http://scikit-learn.org/ 53
PYTHON LIBRARIES FOR DATA SCIENCE
matplotlib:
python 2D plotting library which produces publication quality figures in a
variety of hardcopy formats
Seaborn:
based on matplotlib
Link: https://seaborn.pydata.org/ 55