0% found this document useful (0 votes)
13 views

Chapter 4

Uploaded by

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

Chapter 4

Uploaded by

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

Python Functions

 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.

Syntax of Function

def function_name(parameters):
"""docstring"""
statement(s)

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

1. Keyword def that marks the start of the function header.


2. A function name to uniquely identify the function. Function naming follows the same
rules for writing identifiers in python.
3. Parameters (arguments) through which we pass values to a function. They are
optional.
4. A colon (:) to mark the end of the function header.
5. Optional documentation string (docstring) to describe what the function does.
6. One or more valid python statements that make up the function body. Statements must
have the same indentation level (usually 4 spaces).
7. An optional return statement to return a value from the function

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"

# printing string converting to int base 2


c = int(s,2)
print ("After converting to integer base 2 : ", end="")
print (c)

# printing string converting to float


e = float(s)
print ("After converting to float : ", end="")
print (e)

5
s = '4'

# printing character converting to integer


c = ord(s)
print ("After converting character to integer : ",end="")
print (c)

# printing integer converting to hexadecimal string


c = hex(56)
print ("After converting 56 to hexadecimal string : ",end="")
print (c)

# printing integer converting to octal string


c = oct(56)
print ("After converting 56 to octal string : ",end="")
print (c)
6
s = ‘Bharati'

# printing string converting to tuple


c = tuple(s)
print ("After converting string to tuple : ",end="")
print (c)

# printing string converting to set


c = set(s)
print ("After converting string to set : ",end="")
print (c)

# printing string converting to list


c = list(s)
print ("After converting string to list : ",end="")
print (c)
7
a=1
b=2

# initializing tuple
tup = (('a', 1) ,('f', 2), ('g', 3))

# printing integer converting to complex number


c = complex(1,2)
print ("After converting integer to complex number : ",end="")
print (c)

# printing integer converting to string


c = str(a)
print ("After converting integer to string : ",end="")
print (c)

# printing tuple converting to expression dictionary


c = dict(tup) 8
print ("After converting tuple to dictionary : ",end="")
print (c)
s = ‘Bharati'

# printing string converting to tuple


c = tuple(s)
print ("After converting string to tuple : ",end="")
print (c)

# printing string converting to set


c = set(s)
print ("After converting string to set : ",end="")
print (c)

# printing string converting to list


c = list(s)
print ("After converting string to list : ",end="")
print (c)
9
Math Built in Function

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

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

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

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

fmod(x, y) Returns the remainder when x is divided by y

frexp(x) Returns the mantissa and exponent of x as the pair (m, e) 10


fsum(iterable) Returns an accurate floating point sum of values in the iterable

isfinite(x) Returns True if x is neither an infinity nor a NaN (Not a Number)

isinf(x) Returns True if x is a positive or negative infinity

isnan(x) Returns True if x is a NaN


ldexp(x, i) Returns x * (2**i)

modf(x) Returns the fractional and integer parts of x

trunc(x) Returns the truncated integer value of x

exp(x) Returns e**x


expm1(x) Returns e**x - 1

log(x[, b]) Returns the logarithm of x to the base b (defaults to e)

log1p(x) Returns the natural logarithm of 1+x

log2(x) Returns the base-2 logarithm of x 11


log10(x) Returns the base-10 logarithm of x

pow(x, y) Returns x raised to the power y


sqrt(x) Returns the square root of x
acos(x) Returns the arc cosine of x
asin(x) Returns the arc sine of x
atan(x) Returns the arc tangent of x
atan2(y, x) Returns atan(y / x)
cos(x) Returns the cosine of x

hypot(x, y) Returns the Euclidean norm, sqrt(x*x + y*y)

sin(x) Returns the sine of x


tan(x) Returns the tangent of x

degrees(x) Converts angle x from radians to degrees

radians(x) Converts angle x from degrees to radians

acosh(x) Returns the inverse hyperbolic cosine of x 12


import math
data = 21.6
print('The floor of 21.6 is:', math.floor(data))

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

Following is the example to call printme() function:


def printme(str): "This is a print function“
print str;
return;

printme("I'm first call to user defined function!");


printme("Again second call to the same function");

This would produce following result:


I'm first call to user defined function!
Again second call to the same 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]

def printinfo( arg1, *vartuple ):


"This is test"
print "Output is: "
print arg1
for var in vartuple:
print var
return;
printinfo( 10 );
printinfo( 70, 60, 50 ); 19
Default arguments:
 A default argument is an argument that assumes a default value if a value is not
provided in the function call for that argument.
 Following example gives idea on default arguments, it would print default age if it
is not passed:
def printinfo( name, age = 35 ): “Test function"
print "Name: ", name;
print "Age ", age;
return;
printinfo( age=50, name="miki" );
printinfo( name="miki" );
 This would produce following result:

Name: miki Age 50 Name: miki Age 35


20
Return Statement
• A return statement is used to end the execution of the function call and “returns”
the result (value of the expression following the return keyword) to the caller.
• The statements after the return statements are not executed. If the return
statement is without any expression, then the special value None is returned.
• Return statement can not be used outside the function.

Syntax:

def fun():
statements
.
. 21

return [expression]
def add(a, b):

# returning sum of a and b


return 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

This would produce following result:


Inside the function local total : 30
Outside the function global total : 0

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.

We need to load the module in our python code to use its


functionality. Python provides two types of statements as defined
below.
 The import statement 32

 The from-import statement


The import statement
• The import statement is used to import all the functionality of one
module into another. Here, we must notice that we can use the
functionality of any python source file by importing that file as the
module into another python source file.
• We can import multiple modules with a single import statement, but a
module is loaded once regardless of the number of times, it has been
imported into our file.
The syntax to use the import statement is given below.
import module1,module2,........ module n
Hence, if we need to call the function displayMsg() defined in the file
file.py, we have to import that file as a module into our module as
33

shown in the example below.


import file;
The from-import statement
• Instead of importing the whole module into the namespace, python
provides the flexibility to import only the specific attributes of a
module.
• This can be done by using from import statement.
The syntax to use the from-import statement is given below.
from < module-name> import <name 1>, <name 2>..,<name n>
Consider the following module named as calculation which contains
three functions as summation, multiplication, and divide.
def summation(a,b): # Place this code in Calculation.py
return a+b
def multiplication(a,b):
return a*b; 34

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

• Math class is imported, and its variables can be accessed by considering it to be a


class and pi as its object.
• The value of pi is returned by __import__().
• pi as a whole can be imported into our initial code, rather than importing the
whole module.

from math import pi


print(pi); 36

from module_name import *


Built in Modules in Python

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

Abstract. Retrieves the imaginary component of this number.


class numbers.Real
To Complex, Real adds the operations that work on real numbers.
In short, those are: a conversion to float, math.trunc(), round(), math.floor(),
math.ceil(), divmod(), //, %, <, <=, >, and >=.
Real also provides defaults for complex(), real, imag, and conjugate().

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

print("The floor value is:",number)


Namespaces and Scoping
• Variables are names (identifiers) that map to objects.
• A namespace is a dictionary of variable names (keys) and their
corresponding objects (values).
• A Python statement can access variables in a local namespace and in
the global namespace. If a local and a global variable have the same
name, the local variable shadows the global variable.
• Each function has its own local namespace. Class methods follow the
same scoping rule as ordinary functions.
• Python makes educated guesses on whether variables are local or
global. It assumes that any variable assigned a value in a function is
42
local. Therefore, in order to assign a value to a global variable within
a function, you must first use the global statement.
• The statement global VarName tells Python that VarName is a global variable. Python
stops searching the local namespace for the variable.
For example, we define a variable Money in the global namespace. Within the
function Money, we assign Money a value, therefore Python assumes Money as a local
variable. However, we accessed the value of the local variable Money before setting it, so
an UnboundLocalError is the result. Uncommenting the global statement fixes the
problem.

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

to consider it as a package. This file can be left empty but we


46
Importing module from a package
• We can import modules from packages using the dot (.) operator.
• For example, if we want to import the start module in the above example, it can be
done as follows:
import Game.Level.start
• If this module contains a function named select_difficulty(), we must use the full
name to reference it.
Game.Level.start.select_difficulty(2)
• We can import the module without the package prefix as follows:
from Game.Level import start 47
Creating and Exploring Packages
To tell Python that 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:
1. First, we create a directory and give it a package name, preferably related to its
operation.
2. Then we put the classes and the required functions in it.
3. Finally we create an __init__.py file inside the directory, to let Python know that the
directory is
a package. 48
PYTHON LIBRARIES FOR DATA SCIENCE

Many popular Python toolboxes/libraries:


 NumPy
 SciPy All these libraries
 Pandas are installed on
the SCC
 SciKit-Learn

Visualization libraries
 matplotlib
 Seaborn

and many more …


49
PYTHON LIBRARIES FOR DATA SCIENCE

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

 provides vectorization of mathematical operations on arrays and matrices


which significantly improves the performance

 many other python libraries are built on NumPy


Link: http://www.numpy.org/ 50
https://www.w3schools.com/python/numpy/numpy_intro.asp
PYTHON LIBRARIES FOR DATA SCIENCE

SciPy:
 collection of algorithms for linear algebra, differential equations, numerical
integration, optimization, statistics and more

 part of SciPy Stack

 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)

 provides tools for data manipulation: reshaping, merging, sorting, slicing,


aggregation etc.

 allows handling missing data

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.

 built on NumPy, SciPy and matplotlib

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

 a set of functionalities similar to those of MATLAB

 line plots, scatter plots, barcharts, histograms, pie charts etc.

 relatively low-level; some effort needed to create advanced visualization


Link: https://matplotlib.org/ 54
https://www.w3schools.com/python/
matplotlib_pyplot.asp
PYTHON LIBRARIES FOR DATA SCIENCE

Seaborn:
 based on matplotlib

 provides high level interface for drawing attractive statistical graphics

 Similar (in style) to the popular ggplot2 library in R

Link: https://seaborn.pydata.org/ 55

You might also like