Python Theory and Practical
Python Theory and Practical
Python Theory and Practical
UNIT - 01.
INTRODUCTIONS TO PYTHON PROGRAMMING LANGUAGE :-->
What is Python?
Python is a popular programming language. It was created by Guido van Rossum, and released in
1991.
It is used for:
IL
● system scripting.
Why Python?
● Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
● Python has a simple syntax similar to the English language.
● Python has syntax that allows developers to write programs with fewer lines than some other
SA
programming languages.
● Python runs on an interpreter system, meaning that code can be executed as soon as it is
written. This means that prototyping can be very quick.
● Python can be treated in a procedural way, an object-oriented way or a functional way.
Good to know
● The most recent major version of Python is Python 3, which we shall be using in this tutorial.
However, Python 2, although not being updated with anything other than security updates, is
still quite popular.
● In this tutorial Python will be written in a text editor. It is possible to write Python in an
Integrated Development Environment, such as Thonny, Pycharm, Netbeans or Eclipse which
are particularly useful when managing larger collections of Python files.
● Python was designed for readability, and has some similarities to the English language with
influence from mathematics.
● Python uses new lines to complete a command, as opposed to other programming languages
which often use semicolons or parentheses.
● Python relies on indentation, using whitespace, to define scope; such as the scope of loops,
functions and classes. Other programming languages often use curly-brackets for this purpose
IL
ORIGIN :--> Python was conceived in the late 1980s by Guido van Rossum at Centrum Wiskunde &
Informatica (CWI) in the Netherlands as a successor to the ABC programming language, which was
inspired by SETL, capable of exception handling and interfacing with the Amoeba operating system.
Its implementation began in December 1989.
Python is easy to learn as compared to other programming languages. Its syntax is straightforward
and much the same as the English language. There is no use of the semicolon or curly-bracket, the
indentation defines the code block. It is the recommended programming language for beginners.
2) Expressive Language
Python can perform complex tasks using a few lines of code. A simple example, the hello world
program where you simply type print("Hello World"). It will take only one line to execute, while Java
or C takes multiple lines.
3) Interpreted Language
Python is an interpreted language; it means the Python program is executed one line at a time. The
advantage of being interpreted language, it makes debugging easy and portable.
3
4) Cross-platform Language
Python can run equally on different platforms such as Windows, Linux, UNIX, and Macintosh, etc.
So, we can say that Python is a portable language. It enables programmers to develop the software
for several competing platforms by writing a program only once.
Python is freely available for everyone. It is freely available on its official website www.python.org. It
has a large community across the world that is dedicatedly working towards make new python
modules and functions. Anyone can contribute to the Python community. The open-source means,
"Anyone can download its source code without paying any penny."
6) Object-Oriented Language
IL
Python supports object-oriented language and concepts of classes and objects come into existence.
It supports inheritance, polymorphism, and encapsulation, etc. The object-oriented procedure helps
programmers to write reusable code and develop applications in less code.
7) Extensible
It implies that other languages such as C/C++ can be used to compile the code and thus it can be
It provides a vast range of libraries for the various fields such as machine learning, web developer,
SA
and also for the scripting. There are various machine learning libraries, such as Tensor flow, Pandas,
Numpy, Keras, and Pytorch, etc. Django, flask, pyramids are the popular framework for Python web
development.
Graphical User Interface is used for the developing Desktop application. PyQT5, Tkinter, Kivy are the
libraries which are used for developing the web application.
10) Integrated
It can be easily integrated with languages like C, C++, and JAVA, etc. Python runs code line by line
like C,C++ Java. It makes easy to debug the code.
11. Embeddable
4
The code of the other programming language can use in the Python source code. We can use
Python source code in another programming language as well. It can embed other language into our
code.
In Python, we don't need to specify the data-type of the variable. When we assign some value to the
variable, it automatically allocates the memory to the variable at run time. Suppose we are assigned
integer value 15 to x, then we don't need to write int x = 15. Just write x = 15.
LIMITATIONS :-->
Python's main limitations include its performance and speed, memory management, support for
concurrency and parallelism, static typing, and web support. Python is an interpreted language
executed at runtime by a virtual machine or interpreter.
IL
MAJOR APPLICATIONS OF PYTHON :-->
2. Machine Learning
SA
Machine learning may be considered a branch of data science, but due to its distinctive algorithms, it
deserves its own classification. Machine learning is the process of teaching computers to learn on
their own using algorithms that are constantly updated based on input data. These systems produce
an output based on previous datasets, gradually learning to handle new situations. They then update
themselves to deal with the new variables based on the outcome of this new situation, continuously
evolving.
4. Financial Analysis
When hiring developers, FinTech companies favored Python over all other programming languages.
However, businesses outside of the fintech industry also use Python code. Because of its data
processing abilities and a variety of third-party libraries made specifically for financial analysis,
Python is widely used in the financial sector. People often neglect financial applications of Python
even though it’s libraries are meant to enhance the Fintech sector.
5. Desktop Applications
The development of desktop applications is also possible with Python. Python is used by lots of
Linux and open-source desktop programs. Additionally, Python can be used to create cross-platform
applications that work on Windows, Mac, or Linux thanks to GUI libraries like Tk, wxWidgets, and Qt.
IL
6. Business Applications
Business software like Tryton and Odoo is built on Python. These tools can handle accounting,
inventory, customer relationship management, and other tasks and are used for enterprise
development. To put it simply, Python handles labor-intensive tasks for many businesses. As a
result, Python is now being used by more and more startups due to its usability and scalability.
H
7. Scripting and Utility Software
Python was created as a language for creating utility scripts, and this is still one of its major purposes
today. Python is a programming language that is used extensively in Linux operating systems and is
preinstalled in Mac OS. This makes Python the preferred language for automating daily tasks for
engineers.
SA
8. Search Engine Optimization (SEO)
Python assists SEO experts in extracting and analyzing large amounts of data, as well as in
automating tasks. Python can be used to analyze considerable data sets to find problems with
websites, like broken links, and automate fixes to help reduce laborious tasks and eliminate human
error. It is one of the most useful applications of Python.
9. Blockchain
While Javascript, Java, C++, and other languages may be used regularly for blockchain
development, Python is demonstrating its strength. Because of its high flexibility and functionality,
which are backed up by its security, Python proposes itself well for blockchain development, just as it
does for other uses. Developing a simple blockchain using the Python Framework is one of the most
efficient applications of Python.
6
11. Automation
Beyond the applications especially, Python can be helpful to almost anyone who works with large
data sets, whether professionally or for personal reasons. It can automate arduous tasks like
reviewing data in databases, data visualizations, financial analysis, and a huge variety of other
things. Python is one of the simpler programming languages to learn, so learning it will help you save
time throughout your life. Automation is one of the applications of Python that made the language
IL
popular, along with it’s simple structure and multifunctional set of library.
GETTING :--> Python is a computer programming language often used to build websites and
software, automate tasks, and conduct data analysis.
# write a program to print hello world and also add two nos. —
print(“Hello world by sahil rauniyar”)
IL
PYTHON INTERACTIVE HELP FEATURE :-->
Python help() Method. The Python help() function invokes the interactive built-in help system. If the
argument is a string, then the string is treated as the name of a module, function, class, keyword, or
documentation topic, and a help page is printed on the console.
H
PYTHON DIFFERENCES FROM OTHER LANGUAGES :-->
compiled and statically typed. Python is an interpreted and dynamically typed language, whereas
Java is a compiled and statically typed language. Python code doesn't need to be compiled before
being run. Java code, on the other hand, needs to be compiled from code readable by humans to
SA
code readable by the machine.
PYTHON DATA TYPES AND INPUT/OUTPUT :---
IL
for:--> To create a for loop
from :--> To import specific parts of a module
global :--> To declare a global variable
if :--> To make a conditional statement
import :-->To import a module
in :--> To check if a value is present in a list, tuple, etc.
H
is :--> To test if two variables are equal
lambda :--> To create an anonymous function
None :--> Represents a null value
nonlocal :--> To declare a non-local variable
not :--> A logical operator
SA
or :--> A logical operator
pass :--> A null statement, a statement that will do nothing
raise :--> To raise an exception
return :--> To exit a function and return a value
True :--> Boolean value, result of comparison operations
try :--> To make a try...except statement
while :--> To create a while loop
with :--> Used to simplify exception handling
yield :--> To end a function, return a generator.
9
IL
There are many types of statements :--
1.) Continued statement :--> it is used to continually period to write any program without any
problems , thats are know as continued statement.
2.) Break statement :--> it is used to stop or break the program paragraph to start another
statement or way , thats are know as break statement .
statement .
H
3.) If statement :--> it is use in conditional situations to apply the conditions , that are know as if
4.) Elif statement :--> it is also use in conditional situations if more than one conditions , that are
know as elif statement .
SA
5.) While loop :--> In most computer programming languages, a while loop is a control flow
statement that allows code to be executed repeatedly based on a given Boolean condition.
The while loop can be thought of as a repeating if statement .
6.) Assignments :--> it copies a value into the variable. In most imperative programming
languages , the assignment statement is a fundamental construct .
7.) For loop :-->In computer science a for-loop or for loop is a control flow statement for specifying
iteration. Specifically, a for loop functions by running a section of code repeatedly until a
certain condition has been satisfied. For-loops have two parts: a header and a body.
8.) If else statement :--> it is use to apply in two conditions true and flase , that called if else
statement.
9.) Iteration :--> Iteration is the repetition of a process in order to generate a sequence of
outcomes. Each repetition of the process is a single iteration, and the outcome of each
10
iteration is then the starting point of the next iteration. In mathematics and computer science,
iteration is a standard element of algorithms.
10.) Nested if statement :--> In python is using "if" statements inside other if statements it is
called nested if statement. Syntax. if(condition):; {; if ...
11.) Nested IF :--> You can have if statements inside if statements, this is called nested if
statements. Example. x = 41 if x > 10: print …
12.) The pass statement :--> The pass statement in Python programming is a null statement
that can be utilized as a blank for future code. For example, assume you have an
unimplemented. ( in other word :-- if statements cannot be empty, but if you for some reason
have an if statement with no content, put in the pass statement to avoid getting an error.) .
IL
INDENTATION :-->
Indentation in Python is used to create a group of statements that are executed as a block. Many
popular languages such as C, and Java uses braces ({ }) to define a block of code, and Python uses
indentation.
To write bug-free, user-friendly and beautiful code, it is important to know many things about
indentation, like its rules, its benefits, the error you get, etc. All of which we have covered in this
H
tutorial. Let’s start with an introduction to indentation
DOCUMENTATIONS :-->
Documenting your Python code is all centered on docstrings. These are built-in strings that, when
configured correctly, can help your users and yourself with your project's documentation. Along with
SA
docstrings, Python also has the built-in function help() that prints out the objects docstring to the
console .
VARIABLES :-->
A Python variable is a symbolic name that is a reference or pointer to an object. Once an object is
assigned to a variable, you can refer to the object by that name. But the data itself is still contained
within the object. For example: >>> >>> n = 300.
Multiple assignment (also known as tuple unpacking or iterable unpacking) allows you to assign
multiple variables at the same time in one line of code. This feature often seems simple after you've
learned about it, but it can be tricky to recall multiple assignments when you need it most.
IL
DATA TYPE CONVERSION :-->
Python defines type conversion functions to directly convert one data type to another which is useful
in day-to-day and competitive programming. This article is aimed at providing information about
certain conversion functions.
H
There are two types of Type Conversion in Python:
01) Implicit Type Conversion :
In Implicit type conversion of data types in Python, the Python interpreter automatically converts one
data type to another without any user involvement. To get a more clear view of the topic see the
SA
below examples.
PROGRAM :-->
12
1. int(a, base): This function converts any data type to integer. ‘Base’ specifies the base in which
string is if the data type is a string.
2. float(): This function is used to convert any data type to a floating-point number.
IL
H
SA
PYTHON INPUT AND OUTPUT FUNCTIONS :-->
What are the input functions in Python?
In Python, we use the input() function to take input from the user. Whatever you enter as input, the
input function converts it into a string. If you enter an integer value still input() function converts it into
a string.
Import command :-
In Python, you use the import keyword to make code in one module available in another. Imports in
Python are important for structuring your code effectively. Using imports properly will make you more
productive, allowing you to reuse code while keeping your projects maintainable.
Operators in python :-
In Python, operators are special symbols that designate that some sort of computation should be
performed. The values that an operator acts on are called operands. Here is an example: >>> >>> a
IL
= 10 >>> b = 20 >>> a + b 30. In this case, the + operator adds the operands a and b together.
Expressions ➖
A combination of operands and operators is called an expression. The expression in Python
produces some value or result after being interpreted by the Python interpreter. An expression in
Python is a combination of operators and operands. An example of expression can be : x = x + 1 0 x
= x + 10 x=x+10.
Precedence ➖
H
There can be more than one operator in an expression. To evaluate these types of expressions there
is a rule of precedence in Python. It guides the order in which these operations are carried out. For
SA
example, multiplication has higher precedence than subtraction.
Associativity of Operators ➖
Associativity is the order in which an expression is evaluated that has multiple operators of the same
precedence. Almost all the operators have left-to-right associativity.
________________________________________________________________________________
____________
UNIT - 02.
Control Structures ➖
_________________________________________________________________________
Decision making statements ➖
Decision-making statements are also known as conditional statements because they specify
conditions with boolean expressions evaluated to a true or false boolean value. If the condition is
true, the block will execute; if the condition is false, the block will not execute.
IL
Python loops
Looping means repeating something over and over until a particular condition is satisfied. A for loop
in Python is a control flow statement that is used to repeatedly execute a group of statements as
long as the condition is satisfied. Such a type of statement is also known as an iterative statement.
There are three types of loops in pythons ➖
1. While Loop ➖ In while loop, a condition is evaluated before processing a body of the loop. If a
H
condition is true then and only then the body of a loop is executed.
2. Do-While Loop ➖ In a do…while loop, the condition is always executed after the body of a
loop. It is also called an exit-controlled loop.
3. For Loop ➖ In a for loop, the initial value is performed only once, then the condition tests and
compares the counter to a fixed value after each iteration, stopping the for loop when false is
SA
returned.
Lists ➖
● Some built-in Python data types are:
● Numeric data types: int, float, complex.
● String data types: str.
IL
● Sequence types: list, tuple, range.
● Binary types: bytes, bytearray, memoryview.
● Mapping data type: dict.
● Boolean type: bool.
● Set data types: set, frozenset. Python Numeric Data Type.
● And etc.
Tuples ➖
H
Tuples are used to store multiple items in a single variable. Tuple is one of 4 built-in data types in
Python used to store collections of data, the other 3 are List, Set, and Dictionary, all with different
qualities and usage. A tuple is a collection which is ordered and unchangeable.
SA
Sets ➖ Set is one of 4 built-in data types in Python used to store collections of data, the other 3 are
List, Tuple, and Dictionary, all with different qualities and usage. A set is a collection which is
unordered, unchangeable*, and unindexed. * Note: Set items are unchangeable, but you can remove
items and add new items.
Dictionary ➖
A dictionary in Python is a collection of key-value pairs. The dictionary keys must be unique. The
dictionary value may be of any type. In this blog post, we'll explore the dictionary in Python and learn
how to use it.
16
IL
____________
UNIT ➖03.
Python Functions ➖
______________________________________________________________________________
Functions ➖
In Python, the function is a block of code defined with a name. We use functions whenever we need
Python has a DRY principle like other programming languages. DRY stands for Don’t Repeat
Yourself. Consider a scenario where we need to do some action/task many times. We can define that
action only once using a function and call that function whenever required to do the same activity.
SA
Function improves efficiency and reduces errors because of the reusability of a code. Once we
create a function, we can call it anywhere and anytime. The benefit of using a function is reusability
and modularity
Advantages of Functions ➖
Some of the key benefits of using functions are:-
● Enables reusability and reduces redundancy.
● Makes a code modular.
● Provides abstraction functionality.
● The program becomes easy to understand and manage.
● Breaks an extensive program into smaller and simpler pieces.
17
Built-in Functions ➖
The built-in Python functions are predefined by the python interpreter. There are 68 built-in python
functions. These functions perform a specific task and can be used in any program, depending on
the requirement of the user. Source Code. Table of content.
● Python abs()
returns absolute value of a number
IL
● Python all()
returns true when all elements in iterable is true
● Python any()
Checks if any Element of an Iterable is True
H
● Python ascii()
Returns String Containing Printable Representation
● Python bin()
converts integer to binary string
SA
● Python bool()
Converts a Value to Boolean
● Python bytearray()
returns array of given byte size
● Python bytes()
returns immutable bytes object
● Python callable()
18
● Python chr()
Returns a Character (a string) from an Integer
● Python classmethod()
returns class method for given function
● Python compile()
Returns a Python code object
IL
● Python complex()
Creates a Complex Number
● Python delattr()
Deletes Attribute From the Object
● Python dict()
H
Creates a Dictionary
● Python dir()
SA
Tries to Return Attributes of Object
● Python divmod()
Returns a Tuple of Quotient and Remainder
● Python enumerate()
● Returns an Enumerate Object
●
● Python eval()
Runs Python Code Within Program
19
● Python exec()
Executes Dynamically Created Program
● Python filter()
constructs iterator from elements which are true
● Python float()
returns floating point number from number, string
● Python format()
IL
returns formatted representation of a value
● Python frozenset()
returns immutable frozenset object
● Python getattr()
H
returns value of named attribute of an object
● Python globals()
returns dictionary of current global symbol table
SA
● Python hasattr()
returns whether object has named attribute
● Python hash()
returns hash value of an object
● Python help()
Invokes the built-in Help System
● Python hex()
Converts to Integer to Hexadecimal
20
● Python id()
Returns Identify of an Object
● Python input()
reads and returns a line of string
● Python int()
returns integer from a number or string
IL
● Python isinstance()
Checks if a Object is an Instance of Class
● Python issubclass()
Checks if a Class is Subclass of another Class
H
● Python iter()
returns an iterator
● Python len()
Returns Length of an Object
SA
● Python list()
creates a list in Python
● Python locals()
Returns dictionary of a current local symbol table
● Python map()
Applies Function and Returns a List
● Python max()
21
● Python memoryview()
returns memory view of an argument
● Python min()
returns the smallest value
● Python next()
Retrieves next item from the iterator
IL
● Python object()
creates a featureless object
● Python oct()
returns the octal representation of an integer
● Python open()
H
Returns a file object
● Python ord()
SA
returns an integer of the Unicode character
● Python pow()
returns the power of a number
● Python print()
Prints the Given Object
● Python property()
returns the property attribute
22
● Python range()
returns a sequence of integers
● Python repr()
returns a printable representation of the object
● Python reversed()
returns the reversed iterator of a sequence
● Python round()
IL
rounds a number to specified decimals
● Python set()
constructs and returns a set
● Python setattr()
H
sets the value of an attribute of an object
● Python slice()
● returns a slice object
SA
● Python sorted()
returns a sorted list from the given iterable
● Python staticmethod()
transforms a method into a static method
● Python str()
returns the string version of the object
● Python sum()
Adds items of an Iterable
23
● Python super()
Returns a proxy object of the base class
● Python tuple()
Returns a tuple
● Python type()
Returns the type of the object
● Python vars()
IL
Returns the __dict__ attribute
● Python zip()
Returns an iterator of tuples
● Python __import__()
➖
If you define the function yourself, it is a user-defined function. On the other hand, the Python
function that come along with Python are known as in-built functions. All the functions apart from
SA
in-built functions and library functions come under the category of user-defined functions.
Anonymous functions ➖
An anonymous function in Python is a function without a name. It can be immediately invoked or
stored in a variable. Anonymous functions in Python are also known as lambda functions.
24
Pass by values ➖
IL
Pass by value – It means that the value is directly passed as the value to the argument of the
function. Here, the operation is done on the value and then the value is stored at the address. Pass
by value is used for a copy of the variable.
Pass by reference ➖
Pass by reference – It is used in some programming languages, where values to the argument of the
H
function are passed by reference which means that the address of the variable is passed and then
the operation is done on the value stored at these addresses.
While calling a function, in a programming language instead While calling a function, when we
of copying the values of variables, the address of the pass values by copying variables, it
variables is used, it is known as “Call By Reference.” is known as “Call By Values.”
25
Change in the variable also affects the value of the variable Changes made in a copy of a
outside the function. variable never modify the value of
the variable outside the function.
Allows you to make changes in the values of variables by Does not allow you to make any
using function calls. changes in the actual variables.
IL
The original value is modified. Original value not modified.
Recursion ➖
H
Python also accepts function recursion, which means a defined function can call itself. Recursion is a
common mathematical and programming concept. It means that a function calls itself. This has the
benefit of meaning that you can loop through data to reach a result.
➖
SA
Scope and Lifetime of Variables
Scope and Lifetime of variables :--->
The scopes of the variables depend upon the particular location where the variable is being
declared. Variables can be defined with the two types of scopes—
The place where we can locate a variable, and it is also accessible if needed, is named the scope of
a variable. Every variable in a program is not possible to be accessed at every location in that
program. It depends on how you have declared it in the program.
The scope of a variable defines the part of the program where you can enter an appropriate
identifier.
Local variable
Global variable
Local variables:
The local variables are declared and defined inside the function and are only accessible inside it.
Global variables:
The global type of variables is the one that is determined and declared outside any of the functions
and is not designated to any function. They are accessible in any part of the program by all the
functions. Whenever you call a function, the declared variables inside it are carried into scope. The
global variables are accessible from inside any scope, global and local.
IL
The lifetime of a variable in Python:
The variable lifetime is the period during which the variable remains in the memory of the Python
program. The variables' lifetime inside a function remains as long as the function runs. These local
types of variables are terminated as soon as the function replaces or terminates.
➖
Module definitions ➖
H Python Modules
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.
SA
For example:-
def square(num)
square = num * num
return square .
Similar to the re (regular expression) module, a module can be primarily written in C programming
language and then dynamically inserted at run-time.
A built-in module, such as the itertools module, is inherently included in the interpreter.
A module is a file containing Python code, definitions of functions, statements, or classes. An
example_module.py file is a module we will create and whose name is example_module.
We employ modules to divide complicated programs into smaller, more understandable pieces.
Modules also allow for the reuse of code.
Rather than duplicating their definitions into several applications, we may define our most frequently
IL
used functions in a separate module and then import the complete module.
Let's construct a module. Save the file as example_module.py after entering the following.
Example:
# Here, we are creating a simple Python program to show how to create a module.
# defining a function in the module to reuse it
def square( number ):
result = number ** 2
return result
H
# here, the above function will square the number passed as the input
For this, we make use of the import Python keyword. In the Python window, we add the next to
import keyword, the name of the module we need to import. We will import the module we defined
earlier example_module.
Syntax:
import example_module
28
The functions that we defined in the example_module are not immediately imported into the present
program. Only the name of the module, i.e., example_ module, is imported here.
We may use the dot operator to use the functions using the module name. For instance:
Example:
# here, we are calling the module square method and passing the value 4
result = example_module.square( 4 )
print("By using the module square of number is: ", result )
Output:
IL
By using the module square of number is: 16
H
SA
Need of Modules ➖
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.
29
Creating a module ➖
A module is simply a Python file with a .py extension that can be imported inside another Python
program. The name of the Python file becomes the module name. The module contains definitions
and implementation of classes, variables, and functions that can be used inside another program.
IL
def Sahil():
print("Sahil Rauniyar")
# Defining a variable
location = "Sitamarhi"
The above example shows the creation of a simple module named ‘gupta’ as the name of the
above Python file is gupta.py. When this code is executed it does nothing because the function
created is not invoked.
Importing modules ➖
H
★ To make use of the functions in a module, you’ll need to import the module with an import
statement.
SA
★ An import statement is made up of the import keyword along with the name of the module.
★ In a Python file, this will be declared at the top of the code, under any shebang lines or general
comments.
★ So, in the Python program file my_rand_int.py we would import the random module to
generate random numbers in this manner:
my_rand_int.py
import random
When we import a module, we are making it available to us in our current program as a separate
namespace. This means that we will have to refer to the function in dot notation, as in
[module].[function].
30
In practice, with the example of the random module, this may look like a function such as:
my_rand_int.py
import random
IL
for i in range(10):
print(random.randint(1, 25))
This small program first imports the random module on the first line, then moves into a for loop which
will be working with 10 elements. Within the loop, the program will print a random integer within the
range of 1 through 25 (inclusive). The integers 1 and 25 are passed to random.randint() as its
parameters.
H
When we run the program with python my_rand_int.py, we’ll receive 10 random integers as output.
Because these are random you’ll likely get different integers each time you run the program, but
they’ll generate something like this:
SA
Output
6
9
1
14
3
22
10
1
15
9
31
If you would like to use functions from more than one module, you can do so by adding multiple
import statements:
my_rand_int.py
import random
import math
You may see programs that import multiple modules with commas separating them — as in import
random, math — but this is not consistent with the PEP 8 Style Guide.
IL
To make use of our additional module, we can add the constant pi from math to our program, and
decrease the number of random integers printed out:
my_rand_int.py
import random
import math
for i in range(5):
H
print(random.randint(1, 25))
print(math.pi)
SA
Now, when we run our program, we’ll receive output that looks like this, with an approximation of pi
as our last line of output:
Output
18
10
7
13
10
3.141592653589793
32
The import statement allows you to import one or more modules into your Python program, letting
you make use of the definitions constructed in those modules.
When the interpreter executes the above import statement, it searches for mod.py in a list of
IL
directories assembled from the following sources:
The directory from which the input script was run, or the current directory if the interpreter is being
run interactively
The list of directories contained in the PYTHONPATH environment variable, if it is set. (The format
for PYTHONPATH is OS-dependent but should mimic the PATH environment variable.)
H
An installation-dependent list of directories configured at the time Python is installed
The resulting search path is accessible in the Python variable sys.path, which is obtained from a
module named sys:
So, to ensure that your module is found, you need to do one of the following:
Put mod.py in the directory where the input script is located, or the current directory if interactive
Modify the PYTHONPATH environment variable to contain the directory where mod.py is located
before starting the interpreter. Or put mod.py in one of the directories already contained in the
PYTHONPATH variable.
Put mod.py in one of the installation-dependent directories, which you may or may not have
write-access to, depending on the OS.
There is also one additional option: You can put the module file in any directory of your choice and
then modify sys.path at run-time so that it contains that directory. For example, in this case, you
IL
could put mod.py in directory /Users/chris/ModulesAndPackages and then issue the following
statements:
>>> sys.path.append(r'/Users/chris/ModulesAndPackages')
>>> sys.path
['', '/Library/Frameworks/Python.framework/Versions/3.7/bin',
H
'/Library/Frameworks/Python.framework/Versions/3.7/lib/python37.zip',
'/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7',
'/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload',
'/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages',
'/Users/chris/ModulesAndPackages']
SA
>>> import mod
>>> mod.s
'Computers are useless. They can only give you answers.'
Once you’ve imported a module, you can determine the location where it was found with the
module’s __file__ attribute:
'/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/re.py'
The directory portion of __file__ should be one of the directories in sys.path.
Module Reloading ➖
The reload() is used to reload a previously imported module or loaded module. This comes handy in
a situation where you repeatedly run a test script during an interactive session, it always uses the
first version of the modules we are developing, even if we have made changes to the code. In that
scenario we need to make sure that modules are reloaded. The argument passed to the reload()
must be a module object which is successfully imported before.
IL
Few points to understand, when reload() is executed −
Python module’s code is recompiled and the module-level code re-executed, defining a new set of
objects which are bound to names in the module’s dictionary by reusing the loader which originally
loaded the module. However, the init function of the modules is not loaded again
❖ The old objects are only reclaimed after their reference counts comes down to zero.
H
❖ The names in the module namespace is changed to new object if any.
❖ Other references of the old objects (like names external to the module) are not necessarily
refers to the new objects and must be updated in each namespace where they occur if that is
required.
SA
How to Load a Module
Let’s first see how to load a module in Python. Use the import statement to load −
import importlib
import sys
import importlib
importlib.reload(sys).
Standard Modules ➖
The Python Standard Library is a collection of script modules that may be used by a Python
program, making it unnecessary to rewrite frequently used commands and streamlining the
development process. By "calling/importing" them at the start of a script, they can be used.
A module is a file that contains Python code; an ‘coding.py’ file would be a module with the name
IL
‘coding’.We utilise modules to divide complicated programmes into smaller, more manageable
pieces. Modules also allow for the reuse of code.
In the following example, a module called ‘coding’ contains a function called add() that we
developed. The function receives two numbers as input and outputs their sum −
H
def add(b, c):
# Adding two numbers and returning the result
add_result = b + c
return add_result
This article briefs us about most useful Python modules from the standard library.
SA
The datetime module
1. We can utilise the objects that the datetime module gives us to store information about dates
and times −
2. To generate dates without a time component, use datetime.date.
3. For times that are not related to a certain date, use datetime.time.
4. For objects that have both a date and an hour, use datetime.datetime.
5. datetime.timedelta: When we subtract one datetime from another, the outcome is a timedelta
object, which stores discrepancies between dates or datetimes.
6. Time zone changes are represented as offsets from UTC via datetime.timezone objects.
Datetime.tzinfo, of which this class is a subclass, is not intended for usage directly.
36
Example ➖
Following is an example of datetime module fo getting the current date and time −
import datetime
datetime_obj = datetime.datetime.now()
print(datetime_obj)
Output
Following is an output of the above code −
2022-08-02 11:54:17.401520
IL
The math module
A set of mathematical functions can be found in the math module. Although they can be applied to
floats or integers, their primary purpose is to be applied to floats, and they often return floats.
Use the cmath module in its place if you need to use mathematical operations on complex numbers.
There are several techniques and constants in the math module.Few of them are listed below −
Methods.
H
There are several techniques and constants in the math module.
1. math.acos() gives a number's arc cosine value.
2. The function acosh() returns the math's inverse hyperbolic cosine.
3. A number is rounded to the nearest integer using math.ceil().
SA
4. The number of distinct, non-repeating methods to select item k from item n is returned by
math.comb().
5. math.copysign() produces a float that contains the first parameter's value and the second
parameter's sign.
6. math.cosh() returns a number's hyperbolic cosine.
7. Angles are translated from radians to degrees using math.degrees().
Constants
● math.e returns the value of Euler (2.7182...).
● Return a positive floating-point infinity with math.inf.
● Return a floating-point NaN (Not a Number) value is math.nan.
37
Example
Following is an example to get pi value using math module −
import math
math.pi
Output
Following is an output of the above code −
>>> math.pi
IL
3.141592653589793
In a programming language, a regular expression (RE) is a unique text string used to provide a
search pattern. For extracting information from text, such as code, files, logs, spreadsheets, or even
documents, it is incredibly helpful.
The re module provides a set of functions that let us look for matches in a string which are as follows
−
● findall provides a list of all matching results.
● search - If there is a match anywhere in the string split, it returns a Match object.
● split provides a list that includes the string split at each match sub.
● sub replaces a string with one or more matches.
IL
Metacharacters
Characters with a specific meaning are called metacharacters. Few of them are listed below −
\ is used to indicate a specific sequence or to escape special characters.
Example
Following is an example to print a list of all the matches
import re
line = "Python coding using re module on"
l = re.findall("on", line)
print(l)
39
Output
Following is an output of the above code −
['on', 'on']
The os module
Numerous operating system functions can be carried out automatically. The OS module in Python
has functions for adding and deleting folders, retrieving their contents, changing the directory,
locating the current directory, and more.
Example
Following is an example to get the current working directory −
import os
IL
os.getcwd()
Output
Following is an output of the above code
>>> os.getcwd()
'C:\Users\Lenovo\Desktop'
The io module
H
We can control file-related input and output activities with the help of the Python I/O module. The
benefit of using the IO module is that we can enhance the capability to enable writing to the Unicode
data, thanks to the classes and functions that are available.
Example
Following is an example to open a file in the binary format for reading −
SA
import io
f = io.open("information.txt", "rb")
print(f.read())
Output
Following is an output of the above code −
b"This tutorial looks at various Python comparison techniques for two files.\r\nWe'll go over how to
perform this typical work by using the available modules\r\nreading two files, and comparing them
line by line."
The json module.
Python Packages ➖
40
A package is a container that contains various functions to perform specific tasks. For example, the
math package includes the sqrt() function to perform the square root of a number.
While working on big projects, we have to deal with a large amount of code, and writing everything
together in the same file will make our code look messy. Instead, we can separate our code into
multiple files by keeping the related code together in packages.
Now, we can use the package whenever we need it in our projects. This way we can also reuse our
code.
IL
Package Model Structure in Python Programming.
Suppose we are developing a game. One possible organization of packages and modules could be
as
H
SA
shown in the figure below.
UNIT ➖04.
Exception Handling ➖
________________________________________________________________________________
_
Exceptions ➖
Python Exceptions
When a Python program meets an error, it stops the execution of the rest of the program. An error in
Python might be either an error in the syntax of an expression or a Python exception. We will see
IL
what an exception is. Also, we will see the difference between a syntax error and an exception in this
tutorial. Following that, we will learn about trying and accepting blocks and how to raise exceptions
and make assertions. After that, we will see the Python exceptions list.
What is an Exception?
An exception in Python is an incident that happens while executing a program that causes the
H
regular course of the program's commands to be disrupted. When a Python code comes across a
condition it can't handle, it raises an exception. An object in Python that describes an error is called
an exception.
SA
When a Python code throws an exception, it has two options: handle the exception immediately or
stop and quit.
Output:
if (s != o:
^
SyntaxError: invalid syntax
The arrow in the output shows where the interpreter encountered a syntactic error. There was one
unclosed bracket in this case. Close it and rerun the program:
● BUILT - IN - EXCEPTIONS ➖
In Python, exceptions are used to handle various types of errors that can occur during program
execution. Python provides a set of built-in exceptions that cover a wide range of potential errors.
Here are some commonly used built-in exceptions in Python:
IL
1. SyntaxError: Raised when there is a syntax error in the code.
2. IndentationError: Subclass of SyntaxError, raised when there is an issue with the indentation
of code.
3. NameError: Raised when a local or global name is not found.
H
4. TypeError: Raised when an operation or function is applied to an object of inappropriate type.
5. ValueError: Raised when a function receives an argument of the correct type but with an
invalid value.
6. KeyError: Raised when a dictionary key is not found.
7. IndexError: Raised when an index is out of range.
SA
8. FileNotFoundError: Raised when a file or directory is requested but cannot be found.
9. IOError: Raised when an input/output operation fails.
10. ZeroDivisionError: Raised when division or modulo by zero is attempted.
11.AttributeError: Raised when an attribute reference or assignment fails.
12. ImportError: Raised when an import statement cannot find the module.
13. NotImplementedError: Raised when an abstract method or function is not implemented.
14. RuntimeError: A generic error raised when an error that doesn't fall under more specific
categories occurs.
15. Exception: The base class for all built-in exceptions.
43
You can catch and handle these exceptions using try-except blocks in your code to provide
appropriate error handling and prevent your program from crashing unexpectedly. For example:
try:
result = 10 / 0
except ZeroDivisionError:
print("Division by zero is not allowed.")
● EXCEPTIONS HANDLING ➖
Exception handling allows you to deal with errors and unexpected situations in your code without
causing your program to crash. The basic structure for exception handling in Python involves the try,
IL
except, else, and finally blocks:
H
SA
Here's a breakdown of the different parts of exception handling:
1. try Block: This is where you place the code that might raise an exception. If an exception
occurs within this block, the control is transferred to the corresponding except block.
2. except Block: This block is used to catch and handle specific exceptions that might occur
within the try block. You can have multiple except blocks to handle different types of
exceptions. If an exception matches the type specified in an except block, the code within that
block will be executed.
3. else Block: This block is executed only if no exceptions occurred in the try block. It's often
used to specify code that should run when the try block succeeds.
44
4. finally Block: This block is always executed, regardless of whether an exception occurred or
not. It's used to specify code that must be executed for cleanup purposes, such as closing files
or releasing resources.
Example:
IL
In this example, the program takes user input, performs a division, and handles various exceptions
that might arise. The else block prints the result if no exceptions occur, and the finally block ensures
H
that the final message is printed regardless of the outcome.
By using exception handling, you can make your code more robust and prevent unexpected errors
from crashing your program.
SA
● USER DEFINED EXCEPTIONS IN PYTHON ➖
In Python, you can create your own custom exceptions by defining new classes that inherit from the
built-in Exception class or any of its subclasses. This allows you to create specialized exception
types that make your code more organized and easier to understand. Here's how you can define and
use custom exceptions:
45
IL
In this example:
1. We define a custom exception named CustomError by creating a new class that inherits from
the Exception class. We provide an __init__ method to initialize the exception with a custom
error message.
H
2. Inside the try block, we take user input and check if it's a negative number. If it's negative, we
raise our custom exception.
3. The except CustomError block catches our custom exception and prints its error message.
4. The rest of the exception handling follows the same pattern as before.
SA
By using custom exceptions, you can provide more specific and meaningful error messages to users
or developers when certain conditions are met, making it easier to identify and resolve issues in your
code.
● FILE MANAGEMENT IN PYTHON ➖
● OPERATIONS ON FILES (OPENING, MODES , ATTRIBUTES , ENCODING, CLOSING ) ➖
Working with files in Python involves several steps, including opening, reading or writing data, and
closing the file. Let's go through these steps along with various file operations and concepts:
1. Opening a File: To open a file, you use the built-in open() function. You provide the filename
and the mode in which you want to open the file.
SA
H
IL
46
47
IL
H
SA
read() Method:-
48
The read() method is used to read data from a file. When called without any arguments, it reads the
entire contents of the file and returns them as a string. It has the following syntax:
Here, "filename" is the name of the file you want to read from, and "mode" specifies the mode in
which the file is opened (e.g., "r" for read). After calling read(), the entire content of the file is stored
in the content variable. Make sure to close the file using the close() method after you're done
reading.
IL
Example:
H
SA
SA
H
IL
49
50
IL
● TELL() & SEEK() METHODS ➖
H
In Python, the tell() and seek() methods are used for navigating and managing the current position
within a file when performing file I/O operations. They are often used to read or manipulate data at
specific positions within a file. Let's delve into how these methods work:
tell() Method:
SA
The tell() method is used to determine the current file position, which is the byte offset from the
beginning of the file. It returns an integer indicating the current position in the file.
Syntax:
SA
H
IL
51
52
IL
H
● RENAMING & DELETING FILES IN PYTHON ➖
SA
In Python, you can use the os module to rename and delete files. The os module provides functions
to interact with the operating system, including managing files and directories. Here's how you can
rename and delete files using Python:
Renaming Files:-
You can use the os.rename() function to rename a file. This function takes two arguments: the
current filename and the new filename.
SA
H
IL
53
54
IL
H
● DIRECTORIES IN PYTHON ➖
In Python, you can work with directories (also known as folders) using the built-in os and os.path
modules. The os module provides various functions for interacting with the operating system,
SA
including creating, deleting, and navigating directories. Here are some common directory-related
operations you can perform using these modules:
Creating a Directory:
You can use the os.mkdir() function to create a new directory. This function takes a single argument,
which is the path of the directory you want to create.
EX:-
import os
new_directory = "new_folder"
os.mkdir(new_directory)
55
Replace "new_folder" with the name of the directory you want to create.
IL
Replace "parent_folder/child_folder" with the desired nested directory path.
Listing Contents of a Directory:
You can use the os.listdir() function to get a list of filenames and subdirectories within a directory.
EX:-
import os
directory_path = "my_directory"
H
contents = os.listdir(directory_path)
EX:-
import os
path_to_check = "my_folder"
if os.path.isdir(path_to_check):
print(f"{path_to_check} is a directory.")
else:
print(f"{path_to_check} is not a directory.")
IL
Replace "my_folder" with the path you want to check.
These are just a few of the directory-related operations you can perform using the os and os.path
modules in Python. Always ensure that you have the necessary permissions to create, delete, or
modify directories, and handle exceptions appropriately in your code.
H ● CLASSES AND OBJECTS ➖
● THE CONCEPT OF OOPS IN PYTHONS ➖
SA
Object-Oriented Programming (OOP) is a programming paradigm that revolves around the concept
of "objects." In Python, as well as many other modern programming languages, OOP is a core
principle. It offers a structured and efficient way to design, model, and organize code. OOP promotes
the idea of bundling data (attributes) and the operations (methods) that manipulate that data into a
single unit called an "object."
IL
4. Inheritance:
❖ Inheritance is a mechanism that allows a new class (subclass/derived class) to inherit
attributes and methods from an existing class (superclass/base class). This promotes code
reuse and allows you to create specialized classes based on existing ones.
5. Polymorphism:
H
❖ Polymorphism means the ability of different classes to be treated as instances of the same
class through a common interface. It allows you to write code that can work with objects of
multiple classes without needing to know their specific types.
6. Abstraction:
SA
❖ Abstraction involves representing complex real-world entities using simplified models. It allows
you to focus on the essential features of an object while ignoring the irrelevant details.
In Python, you create classes using the class keyword and define methods within them. Here's a
simple example:
58
IL
In this example, Dog is a class, and dog1 and dog2 are objects of that class. The class has attributes
(name and age) and a method (bark).
H
OOP promotes modular and organized code, making it easier to manage complex systems and
collaborate on projects. It encourages code reusability, extensibility, and maintainability.
● DESIGNING CLASSES ➖
Designing classes in Python involves defining the attributes and methods that will constitute the
SA
behavior and structure of objects created from those classes. A well-designed class should
accurately represent the real-world entity it models and adhere to the principles of Object-Oriented
Programming (OOP). Let's go through the steps of designing classes in Python:
IL
and manipulate the attributes.
In this example, the Person class has attributes (name and age) and methods (say_hello and
have_birthday) that represent the behavior of a person.
60
As you design classes, keep in mind the Single Responsibility Principle (SRP), which suggests that a
class should have a single, well-defined responsibility. This promotes maintainability and reusability.
Additionally, consider using docstrings to provide documentation for your class, attributes, and
methods. Well-documented code helps others (and yourself) understand the purpose and usage of
your classes.
Remember that class design might involve iterative development and refinement as you gain a better
understanding of the problem you're trying to solve and the requirements of your application.
IL
● ACCESSING ATTRIBUTES ➖
In Python, you can access attributes of an object using dot notation. Dot notation involves using the
object's name followed by a dot (.) and the attribute's name. This allows you to retrieve and modify
the values stored in the attributes of the object. Here's how you can access attributes in Python:
H
Assuming we have a class Person with attributes name and age:
SA
SA
H
IL
61
62
IL
● EDITING CLASS ATTRIBUTES ➖
In Python, you can edit class attributes by directly assigning new values to them using the dot
H
notation. Class attributes are attributes that are shared among all instances of the class. Any change
made to a class attribute will affect all instances of that class. Here's how you can edit class
attributes:
IL
In this case, car1 has an instance attribute named top_speed, while Car still has the class attribute
top_speed.
H
Keep in mind that class attributes are usually used for constants, default values, or shared data
across instances. If you want to have attributes that are specific to each instance and can vary
independently, you should use instance attributes defined within the __init__ constructor.
➖
SA
● BUILT IN CLASS ATTRIBUTES
In Python, there are several built-in class attributes that provide useful information about classes.
These attributes are accessible using dot notation with the class name. Here are some commonly
used built-in class attributes:
__doc__:
This attribute holds the docstring (documentation string) associated with the class. The docstring is a
multi-line string that provides information about the purpose and usage of the class.
__name__:
This attribute holds the name of the class as a string. It's the actual name used to define the class.
64
__module__:
This attribute holds the name of the module where the class is defined. If the class is defined in the
main program, this attribute will be "__main__".
__dict__:
This attribute is a dictionary containing the class's namespace. It maps attribute names to their
corresponding values for the class. This includes all attributes, methods, and class variables.
__bases__:
This attribute is a tuple containing the base classes from which the class is derived. If the class
IL
inherits from multiple base classes, they are listed in the order they were specified in the class
definition.
● GARBAGE COLLECTION
IL ➖
H
Garbage collection in Python is the automatic process of identifying and freeing up memory that is no
longer being used by the program. Python uses a reference counting mechanism as well as a cyclic
garbage collector to manage memory and reclaim resources efficiently.
objects that are part of cyclic reference cycles and are therefore not reachable by reference
counting.
3. gc Module:
Python's garbage collection can be managed and controlled using the gc module. Although the
garbage collector usually works automatically in the background, the gc module provides functions
that allow you to manually trigger garbage collection, disable or enable it, and inspect garbage
collection statistics.
Here's an example of how you can use the gc module to manually control garbage collection:
IL
EX:-
import gc
# Manually trigger garbage collection
gc.collect() H
# Disable automatic garbage collection
gc.disable()
It's important to note that for most Python programs, you don't need to manually manage garbage
collection. The Python interpreter takes care of memory management for you. However,
understanding how garbage collection works can help you write more memory-efficient code,
especially when working with large data structures or long-running applications.
67
Keep in mind that memory management and garbage collection specifics may vary based on the
Python implementation you're using (e.g., CPython, Jython, IronPython) and the version of Python.
● DESTROYING OBJECTS ➖
In Python, objects are automatically destroyed and their memory is released when they are no longer
referenced. Python uses a combination of reference counting and garbage collection to manage
memory and destroy objects that are no longer needed. You generally don't need to explicitly destroy
objects like you might in languages that require manual memory management (e.g., C++ or C#).
IL
1. Reference Counting:
The primary mechanism for destroying objects in Python is reference counting. When an object's
reference count drops to zero, it means there are no more references pointing to that object, and it's
considered unreferenced. When this happens, Python's memory manager automatically reclaims the
memory associated with the object.
H
2. Garbage Collection:
While reference counting works well for most cases, there are situations where circular references
can prevent objects from being destroyed even when they're no longer reachable. To handle these
cases, Python employs a cyclic garbage collector that periodically identifies and collects objects
involved in circular reference cycles.
SA
3. __del__ Method (Destructor):
Python provides a special method called __del__ that you can define in your classes. This method is
called when an object is about to be destroyed. However, it's important to note that using __del__ for
resource cleanup isn't recommended in most cases, as it can lead to unexpected behavior due to the
order of destruction.
IL
While Python's automatic memory management takes care of most memory cleanup, there might
H
be cases where you're working with external resources (e.g., files, network connections) that
require explicit cleanup. In such cases, it's recommended to use context managers (with
statements) or explicit cleanup methods rather than relying on __del__. !
SA
69
IL
H
SA