1. Dr. A. B. Shinde
Assistant Professor,
Electronics and Computer Science,
P V P Institute of Technology, Sangli
Python Functions, Modules
and Packages
2. Dr. A. B. Shinde
Contents…
• Python built-in functions,
– Math Function,
– Python user-defined functions,
• Arguments:
– Actual & Formal,
– Default Argument,
– Positional Argument,
– Variable Length Argument,
• Function returning value/s,
• Anonymous Functions.
• Scope of variable: Global and Local.
• Creating modules,
• import statement,
• Import statement, name spacing,
• Python packages, Introduction to PIP,
• Installing & Uninstalling Packages via PIP, Using Python Packages.
2
4. Dr. A. B. Shinde
Function
• Python Functions is a block of statements that return the specific task.
• The idea is to put some commonly or repeatedly done tasks together
and make a function.
• Instead of writing the same code again and again for different inputs,
call the function to reuse code contained in it.
• Benefits of Using Functions
• Increase Code Readability
• Increase Code Reusability
4
5. Dr. A. B. Shinde
Function
• Types of Functions in Python
• Built-in library function: These are Standard functions in Python that
are available to use.
• User-defined function: We can create our own functions based on our
requirements.
5
6. Dr. A. B. Shinde
Function
• Creating a Function
• We can define a function in Python, using the def keyword.
• We can add any type of functionalities and properties to it as we
require.
6
# A simple Python function
def fun():
print("Welcome to PVPIT Budhgaon")
8. Dr. A. B. Shinde
Python Built in Functions
• Python provides a lot of built-in functions that ease the writing of code.
8
abs() Function Return the absolute value of a number
aiter() Function
It takes an asynchronous iterable as an argument and returns an
asynchronous iterator for that iterable
all() Function
Return true if all the elements of a given iterable( List, Dictionary,
Tuple, set, etc) are True else it returns False
any() Function
Returns true if any of the elements of a given iterable( List, Dictionary,
Tuple, set, etc) are True else it returns False
anext() Function used for getting the next item from an asynchronous iterator
ascii() Function Returns a string containing a printable representation of an object
bin() Function Convert integer to a binary string
bool() Function Return or convert a value to a Boolean value i.e., True or False
breakpoint() Function
It is used for dropping into the debugger at the call site during runtime
for debugging purposes
9. Dr. A. B. Shinde
Python Built in Functions
Python bytearray
() Function
Returns a byte array object which is an array of given bytes
Python bytes() Function
Converts an object to an immutable byte-represented object of a given size
and data
Python callable() Functio
n
Returns True if the object passed appears to be callable
Python chr() Function
Returns a string representing a character whose Unicode code point is an
integer
Python classmethod() F
unction
Returns a class method for a given function
Python compile() Functio
n
Returns a Python code object
Python complex() Functi
on
Creates Complex Number
Python delattr() Function Delete the named attribute from the object
Python dict() Function Creates a Python Dictionary
9
10. Dr. A. B. Shinde
Python Built in Functions
Python bytearray() Functi
on
Returns a byte array object which is an array of given bytes
Python bytes() Function
Converts an object to an immutable byte-represented object of a given size
and data
Python callable() Functio
n
Returns True if the object passed appears to be callable
Python chr() Function
Returns a string representing a character whose Unicode code point is an
integer
Python classmethod() Fu
nction
Returns a class method for a given function
Python compile() Functio
n
Returns a Python code object
Python complex() Functio
n
Creates Complex Number
Python delattr() Function Delete the named attribute from the object
Python dict() Function Creates a Python Dictionary
10
11. Dr. A. B. Shinde
Python Built in Functions
Python getattr() Function Access the attribute value of an object
Python globals() Function Returns the dictionary of the current global symbol table
Python hasattr() Function
Check if an object has the given named attribute and return true if
present
Python hash() Function Encode the data into an unrecognizable value
Python help() Function Display the documentation of modules, functions, classes, keywords, etc
Python hex() Function Convert an integer number into its corresponding hexadecimal form
Python id() Function Return the identity of an object
Python input() Function Take input from the user as a string
Python int() Function Converts a number in a given base to decimal
Python isinstance() Function Checks if the objects belong to a certain class or not
Python issubclass() Function Check if a class is a subclass of another class or not
Python iter() Function Convert an iterable to an iterator
11
12. Dr. A. B. Shinde
Python Built in Functions
Python len() Function Returns the length of the object
Python list() Function Creates a list in Python
Python locals() Function Returns the dictionary of the current local symbol table
Python map() Function
Returns a map object(which is an iterator) of the results after applying
the given function to each item of a given iterable
Python max() Function
Returns the largest item in an iterable or the largest of two or more
arguments
Python memoryview
() Function
Returns memory view of an argument
Python min() Function
Returns the smallest item in an iterable or the smallest of two or more
arguments
Python next() Function Receives the next item from the iterator
Python object() Function Returns a new object
Python oct() Function returns an octal representation of an integer in a string format.
Python open() Function Open a file and return its object
12
13. Dr. A. B. Shinde
Python Built in Functions
Python ord() Function Returns the Unicode equivalence of the passed argument
Python pow() Function Compute the power of a number
Python print() Function Print output to the console
Python property() Function Create a property of a class
Python range() Function Generate a sequence of numbers
Python repr() Function Return the printable version of the object
Python reversed() Function
Returns an iterator that accesses the given sequence in the reverse
order
Python round() Function
Rounds off to the given number of digits and returns the floating-point
number
Python set() Function
Convert any of the iterable to a sequence of iterable elements with
distinct elements
Python setattr() Function Assign the object attribute its value
Python slice() Function Returns a slice object
13
14. Dr. A. B. Shinde
Python Built in Functions
Python sorted() Function
Returns a list with the elements in a sorted manner, without modifying
the original sequence
Python staticmethod() Function Converts a message into the static message
Python str() Function Returns the string version of the object
Python sum() Function Sums up the numbers in the list
Python super() Function Returns a temporary object of the superclass
Python tuple() Function Creates a tuple in Python
Python type() Function Returns the type of the object
Python vars() Function
Returns the __dict__ attribute for a module, class, instance, or any
other object
Python zip() Function Maps the similar index of multiple containers
Python __import__() Function Imports the module during runtime
14
15. Dr. A. B. Shinde
Python Built in Functions
• bin():
• bin() function returns the binary string of a given integer.
• bin() function is used to convert integer to binary string.
15
• bool():
• bool() function is used to return or convert a value to a Boolean value
i.e., True or False, using the standard truth testing procedure.
16. Dr. A. B. Shinde
Python Built in Functions
• __import__() function
• We can import modules by using a single-line code in Python.
• One can use Python’s inbuilt __import__() function.
• It helps to import modules in runtime also.
16
Syntax: __import__(name, globals, locals, fromlist, level)
Parameters:
• name : Name of the module to be imported
• globals and locals: Interpret names
• formlist : Objects or submodules to be imported (as a list)
• level : Specifies whether to use absolute or relative imports.
The default is -1(absolute and relative).
17. Dr. A. B. Shinde
Python Built in Functions
• __import__() function
17
18. Dr. A. B. Shinde
Math Module (Function)
• Math Module
• Math Module consists of mathematical functions and constants.
• It is a built-in module made for mathematical tasks.
• The math module provides the math functions to deal with basic
operations such as addition(+), subtraction(-), multiplication(*),
division(/), and advanced operations like trigonometric, logarithmic, and
exponential functions.
• Importing Math Module
18
19. Dr. A. B. Shinde
Math Module (Function)
• Constants in Math Module
• The Python math module provides various values of
various constants like pi, and tau.
• We can easily write their values with these constants.
• The constants provided by the math module are :
– Euler’s Number
– Pi
– Tau
– Infinity
– Not a Number (NaN)
19
20. Dr. A. B. Shinde
Math Module (Function) 20
Euler’s Number Pi
Example:
21. Dr. A. B. Shinde
Math Module (Function) 21
tau Infinity
NaN Values
22. Dr. A. B. Shinde
Math Module (Function)
• List of Mathematical function in Math Module
22
ceil(x)
Returns the smallest integral value greater
than the number
copysign
(x, y)
Returns the number with the value of ‘x’ but
with the sign of ‘y’
fabs(x) Returns the absolute value of the number
factorial(x) Returns the factorial of the number
floor(x)
Returns the greatest integral value smaller
than the number
gcd(x, y)
Compute the greatest common divisor of 2
numbers
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)
fsum(iterable
)
Returns the precise floating-point value of
sum of elements in an iterable
isfinite(x)
Check whether the value is neither infinity not
Nan
isinf(x) Check whether the value is infinity or not
isnan(x)
Returns true if the number is “nan” else
returns false
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 the value of e raised to the power x(e**x)
expm1(x) Returns the value of e raised to the power a (x-1)
log(x[, b]) Returns the logarithmic value of a with base b
log1p(x) Returns the natural logarithmic value of 1+x
log2(x) Computes value of log a with base 2
log10(x) Computes value of log a with base 10
pow(x, y) Compute value of x raised to the power y (x**y)
sqrt(x) Returns the square root of the number
acos(x) Returns the arc cosine of value passed as argument
asin(x) Returns the arc sine of value passed as argument
atan(x) Returns the arc tangent of value passed as argument
atan2(y, x) Returns atan(y / x)
cos(x) Returns the cosine of value passed as argument
hypot(x, y) Returns the hypotenuse of the values passed in
arguments
sin(x) Returns the sine of value passed as argument
tan(x) Returns the tangent of the value passed as argument
degrees(x) Convert argument value from radians to degrees
radians(x) Convert argument value from degrees to radians
acosh(x)
Returns the inverse hyperbolic
cosine of value passed as
argument
asinh(x)
Returns the inverse hyperbolic
sine of value passed as argument
atanh(x)
Returns the inverse hyperbolic
tangent of value passed as
argument
cosh(x)
Returns the hyperbolic cosine of
value passed as argument
sinh(x)
Returns the hyperbolic sine of
value passed as argument
tanh(x)
Returns the hyperbolic tangent of
value passed as argument
erf(x) Returns the error function at x
erfc(x)
Returns the complementary error
function at x
gamma(x)
Return the gamma function of the
argument
lgamma(x)
Return the natural log of the
absolute value of the gamma
function
24. Dr. A. B. Shinde
User-defined Function
• A function is a set of statements that take inputs, do some specific
computation, and produce output.
• The idea is to put some commonly or repeatedly done tasks together
and make a function.
• Python provides built-in functions like print(), etc.
• We can also create your own functions.
• These functions are known as user defined functions.
24
25. Dr. A. B. Shinde
User-defined Function
• All the functions that are written by any of us come under the category
of user-defined functions.
• In Python, a def keyword is used to declare user-defined functions.
• An indented block of statements follows the function name and
arguments which contains the body of the function.
• Syntax:
25
def function_name():
statements
.
.
26. Dr. A. B. Shinde
User-defined Function
• Parameterized Function
• The function may take arguments(s) also called parameters as input
within the opening and closing parentheses, just after the function
name followed by a colon.
• Syntax:
26
def function_name(argument1,
argument2, ...):
statements
.
.
27. Dr. A. B. Shinde
User-defined Function
• Arguments: Actual & Formal
• Formal arguments, are placeholders defined in the function signature
or declaration.
• They represent the data that the function expects to receive when
called.
• Formal parameters serve as variables within the function's scope and
are used to perform operations on the input data.
• Actual arguments, are the values or expressions provided to a
function or method when it is called.
• They correspond to the formal parameters in the function's definition
and supply the necessary input data for the function to execute.
• Actual parameters can be constants, variables, expressions, or even
function calls.
27
28. Dr. A. B. Shinde
User-defined Function
• Arguments: Actual & Formal
28
function Fnc(name) {
// Function body
}
// Actual Parameter
Fnc(“ECS");
Syntax of Actual Argument
// Here, 'name' is the formal parameter
function Fnc(name) {
// Function body
}
Syntax of Formal Argument
29. Dr. A. B. Shinde
User-defined Function
• Formal and Actual Arguments in Python
29
30. Dr. A. B. Shinde
User-defined Function
• Default arguments
• A default argument is a parameter that assumes a default value if a
value is not provided in the function call for that argument.
• Example: We call myFun() with the only argument.
30
31. Dr. A. B. Shinde
User-defined Function
• Keyword arguments
• The idea is to allow the caller to specify the argument name with values
so that the caller does not need to remember the order of parameters.
31
32. Dr. A. B. Shinde
User-defined Function
• Positional Arguments
• Positional arguments mean whenever we pass the arguments in the
order we have defined function parameters. If you change the argument
position then you may get the unexpected output.
• Positional Arguments should be used whenever we know the order of
argument to be passed.
32
33. Dr. A. B. Shinde
User-defined Function
• Positional Arguments
33
34. Dr. A. B. Shinde
User-defined Function
• Variable Length Arguments
• We can have both normal and keyword variable numbers of arguments.
• The special syntax *args in function definitions is used to pass a variable
number of arguments to a function.
• It is used to pass a non-keyworded, variable-length argument list.
• The special syntax **kwargs in function definitions is used to pass a
keyworded, variable-length argument list.
• We used the name kwargs with the double star. The reason is that the double
star allows us to pass through keyword arguments (and any number of them).
34
35. Dr. A. B. Shinde
User-defined Function 35
Variable Length Arguments
36. Dr. A. B. Shinde
User-defined Function
• Function with return value
• Sometimes we might need the result of the function to be used in
further processes.
• Hence, a function should also return a value when it finishes its
execution.
• 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
• Syntax
36
def fun():
statements
.
.
return
[expression]
37. Dr. A. B. Shinde
User-defined Function
• Function with return value
37
38. Dr. A. B. Shinde
User-defined Function
• Anonymous Functions
• An anonymous function in Python is one that has no name when it is
defined.
• In Python, the lambda keyword is used to define anonymous functions
rather than the def keyword.
• As we know the def keyword is used to define a normal function.
• Similarly, the lambda keyword is used to define an anonymous
function.
38
Syntax: lambda arguments : expression
39. Dr. A. B. Shinde
User-defined Function
• Anonymous Functions: Lambda
39
lambda with Condition Checking
40. Dr. A. B. Shinde
User-defined Function
• Difference Between lambda and Normal Function (def Keyword)
40
Feature lambda Function Regular Function (def)
Definition
Single expression
with lambda.
Multiple lines of code.
Name
Anonymous
(or named if assigned).
Must have a name.
Statements Single expression only.
Can include multiple
statements.
Documentation Cannot have a docstring. Can include docstrings.
Reusability
Best for short, temporary
functions.
Better for reusable and
complex logic.
41. Dr. A. B. Shinde
User-defined Function
• Example
41
Lambda with List Comprehension
42. Dr. A. B. Shinde
User-defined Function
• Lambda with if-else
42
Lambda with Multiple Statements
43. Dr. A. B. Shinde
User-defined Function
• Using lambda with filter()
43
Using lambda with map()
44. Dr. A. B. Shinde
User-defined Function
• Using lambda with reduce()
44
45. Dr. A. B. Shinde
User-defined Function
• Scope of Variables
• Variables are the containers for storing data values.
• We do not need to declare variables before using them or declare their
type.
• A variable is created the moment we first assign a value to it.
45
46. Dr. A. B. Shinde
User-defined Function
• Local variable
• Local variables are those that are initialized within a function and are
unique to that function.
• It cannot be accessed outside of the function.
46
47. Dr. A. B. Shinde
User-defined Function
• Local variable
• If we will try to use this local variable outside the function then let’s see
what will happen.
47
48. Dr. A. B. Shinde
User-defined Function
• Global variables
• Global variables are the ones that are defined and declared outside any
function and are not specified to any function.
• They can be used by any part of the program.
48
49. Dr. A. B. Shinde
User-defined Function
• Global and Local Variables with the Same Name
• Now suppose a variable with the same name is defined inside the
scope of the function as well then it will print the value given inside the
function only and not the global value.
49
The variable s is defined as
the string “I love My India”,
before we call the function
f().
The only statement in f() is
the print(s) statement.
As there are no locals, the
value from the global s is
used.
50. Dr. A. B. Shinde
User-defined Function
• To tell Python, that we want to use the global variable, we have to use
the keyword global, as can be seen in the following
50
53. Dr. A. B. Shinde
Python Module
• A Python module is a file containing Python definitions and
statements.
• A module can define functions, classes, and variables. A module can
also include runnable code.
• Grouping related code into a module makes the code easier to
understand and use. It also makes the code logically organized.
• There are many Python modules, each with its specific work.
53
54. Dr. A. B. Shinde
Python Module
• Creating modules
• To create a Python module, write the desired code and save that in a
file with .py extension.
• Simple calc.py module with two functions, add and subtract.
54
55. Dr. A. B. Shinde
Python Module
• Import module in Python:
• We can import the functions, and classes defined in a module to
another module using the import statement in some other Python
source file.
• When the interpreter encounters an import statement, it imports the
module if the module is present in the search path
• Syntax:
55
import module
56. Dr. A. B. Shinde
Python Module
• Import From Module:
• Python’s from statement lets you import specific attributes from a
module without importing the module as a whole.
56
57. Dr. A. B. Shinde
Python Module
• Import all Names:
• The * symbol used with the import statement is used to import all the
names from a module to a current namespace.
• Syntax
57
from module_name import *
If you know exactly what you will be needing from the module, it is not
recommended to use *, else do so
58. Dr. A. B. Shinde
Python Module
• Renaming the Python Module:
• We can rename the module while importing it using the keyword.
• Syntax:
58
Import Module_name as Alias_name
59. Dr. A. B. Shinde
Python Module
• Python Built-in modules
59
# importing built-in module math
import math
# using square root(sqrt) function
print(math.sqrt(25))
# using pi function contained in
math module
print(math.pi)
# 2 radians = 114.59 degrees
print(math.degrees(2))
# 60 degrees = 1.04 radians
print(math.radians(60))
# Sine of 2 radians
print(math.sin(2))
# Cosine of 0.5 radians
print(math.cos(0.5))
# Tangent of 0.23 radians
print(math.tan(0.23))
# 1 * 2 * 3 * 4 = 24
print(math.factorial(4))
# importing built in module random
import random
# printing random integer between 0
and 5
print(random.randint(0, 5))
# print random floating point number
between 0 and 1
print(random.random())
# random number between 0 and 100
print(random.random() * 100)
List = [1, 4, True, 800, "python", 27,
"hello"]
# using choice function in random
module for choosing
# a random element from a set such as
a list
print(random.choice(List))
61. Dr. A. B. Shinde
Python Package
• Python packages are a way to organize and structure code by grouping
related modules into directories.
• A package is essentially a folder that contains an __init__.py file and
one or more Python files (modules).
• Such organization helps manage and reuse code effectively, especially
in larger projects.
• Packages act like toolboxes, storing and organizing tools (functions and
classes) for efficient access and reuse.
• Key Components of a Python Package
• Module: A single Python file containing reusable code (e.g., math.py).
• Package: A directory containing modules and a special __init__.py file.
• Sub-Packages: Packages nested within other packages for deeper
organization
61
62. Dr. A. B. Shinde
Python Package
• How to create and access packages in python
• Create a Directory:
– Make a directory for your package. This will serve as the root folder.
• Add Modules:
– Add Python files (modules) to the directory, each representing specific
functionality.
• Include __init__.py:
– Add an __init__.py file (can be empty) to the directory to mark it as a
package.
• Add Sub packages (Optional):
– Create subdirectories with their own __init__.py files for sub packages.
• Import Modules:
– Use dot notation to import, e.g., from mypackage.module1.
62
63. Dr. A. B. Shinde
Python Package 63
• Example:
math_operatio
n Package
__init__.py
add.py
subtract.py
mul.py
div.py
main_code.py
65. Dr. A. B. Shinde
Python Package
• Python Packages for Web frameworks
• Flask: Flask is a lightweight Python web framework that simplifies building web
applications, APIs, and services with an intuitive interface
• Django: Django is a Python web framework that enables fast, efficient
development with features like URL routing, database management, and
authentication
• FastAPI: FastAPI is a high-performance Python framework for building modern
APIs quickly, using type hints and providing automatic interactive
documentation
• Pyramid: Pyramid is a lightweight Python web framework offering flexibility and
powerful features for HTTP handling, routing, and templating.
• Tornado: Tornado is an asynchronous Python web framework and networking
library, ideal for real-time applications and APIs with its efficient, non-blocking
architecture.
65
66. Dr. A. B. Shinde
Python Package
• Python Packages for Web frameworks
• Falcon: Falcon is a lightweight Python web framework for building fast,
minimalist RESTful APIs with a focus on simplicity and performance.
• CherryPy: CherryPy is a minimalist Python web framework that simplifies HTTP
request handling, allowing developers to focus on application logic without
server management complexities
• Bottle: Bottle is a lightweight Python web framework for building small
applications and APIs with minimal effort, ideal for prototyping and simplicity.
• Web2py: Web2py is a free open-source web framework for agile development
of secure database-driven web applications. It’s written in Python and offers
features like an integrated development environment (IDE), simplified
deployment, and support for multiple database backends.
66
67. Dr. A. B. Shinde
Python Package
• Python Packages for AI & Machine Learning
67
Statistical Analysis
NumPy
Pandas
SciPy
XGBoost
StatsModels
Yellowbrick
Arch
Dask-ML
Data Visualization
Matplotlib
Seaborn
Plotly
Bokeh
Altair
Pygal
Plotnine
Dash
68. Dr. A. B. Shinde
Python Package 68
• Python Packages for AI & Machine Learning
Statistical Analysis
Scikit-learn
TensorFlow
torch
Keras
Keras-RL
Lasagne
Fastai
Natural Language Processing
NLTK
spaCy
FastText
Transformers
fastText
AllenNLP
TextBlob
69. Dr. A. B. Shinde
Python Package 69
• Python Packages for AI & Machine Learning
Generative AI
Keras
spaCy
generative
GPy
Pillow
ImageIO
Fastai
Computer Vision
OpenCV
TensorFlow
torch
scikit-image
SimpleCV
ImageAI
imageio
Dlib
Theano
Mahotas