100% found this document useful (1 vote)
49 views307 pages

Python Complete Material

Uploaded by

2002svinfotech
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
100% found this document useful (1 vote)
49 views307 pages

Python Complete Material

Uploaded by

2002svinfotech
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 307

PYTHON

COURSE
MATERIAL

# 7-20, 4th Floor, Beside Konark Theater,


Dilsukhnagar, Hyderabad,
Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377.
+91-406625 2272 / 73 / 74

Kesa Pavan Kumar


Sr. Faculty

https://svinfotech.in/
22+ Years of Excellence in IT Training

Python Tutorials For


Beginners & Professionals
Python – Basics
Introduction to Python
In this Python Tutorials For Beginners and Professionals article series, we
covered all the basic and advanced concepts of Python using simple as well as
real-time examples. Each concept will explain using simple as well as real-time
examples.
This Python Tutorial is designed for students, beginners as well as professional
developers who want to learn Python step by step from the very basic to the
advanced concept using real-time examples. These tutorials provide a hands-on
approach to the subject with step-by-step program examples that will assist
you to learn and put the acquired knowledge into practice.
What is python?
Before knowing about the python language, let’s make ourselves familiar with
some terms which will help us in understanding Python better.
High-level language vs low-level language
High-level programming languages are those which are programmer-friendly.
Humans can easily understand it which helps in easy maintaining and
debugging of the code. These types of languages need a compiler or interpreter
for execution. High-level languages are the most commonly used languages.
Examples – Java, C, C++, Python
Low-level programming languages are those which are machine-friendly.
Humans can’t understand such languages. In other words, low-level languages
are not human readable. So these languages, comparatively, are complex to
debug. An assembler is required to debug these types of languages. Examples –
Assembly language, Machine language.
Compiler vs Interpreter
All the programming languages are converted to machine understandable
language for execution. The conversion is taken care of by compilers and
interpreters.
Let us consider an example of an Italian movie. For a person, who doesn’t
understand Italian and can understand English, there will be two ways to
watch the movie. The first way is to watch an English dubbed version of the
movie, if available. The second way is to watch the Italian movie with English
subtitles. In the second way, the subtitles are displayed scene by scene
separately whereas in the first way all the scenes are converted to English. We
can compare the first scenario with the compiler and the second one with the
interpreter.
A compiler is one that takes the source code and converts it into machine-
executable code at once. The processor takes the executable and executes it.
The languages which use a compiler are called compiled languages. Compiled
languages are faster and more efficient comparatively. Examples – Java, C++

1
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
An interpreter is one that runs the code line by line and executes instruction by
instruction. The languages which use interpreters are called Interpreted
languages. Such languages are slower in terms of execution and less efficient.
Examples – PHP, Python, Ruby
Scripting language
A scripting language is a programming language that is interpreted. These types
of languages are used in automation, etc. These languages use interpreters and
are executed line by line.

Definition of Python:
Python is a general-purpose, interpreted, high-level programming language, a
Wikipedia definition. In clear terms, Python
1. High-level language – It is a human-readable language which easily
understandable and easy to debug
2. Interpreted as well as compiled – Python is basically called an
interpreted language, but can also be called a compiled interpreted
language. In Python, first, all the source code is at once converted to byte
code which is the action of the compiler, and then the byte code is
executed by the compiler.
3. Python is also called a scripting language.
Why the name Python?
There was a TV show by the name Monty Python’s Flying Circus which was a
very much popular fun show in the 1970s. While creating Python, Guido also
used to read this show’s published scripts. Guido needed a short and a
different name for this language, hence he named it “Python”.
Python Versions
1. Python 1.0V introduced in Jan 1994
2. Python 2.0V introduced in October 2000
3. Python 3.0V introduced in December 2008.
4. The current version is 3.8
Note: Python 3 won’t provide backward compatibility to Python2 i.e. there is no
guarantee that Python2 programs will run in Python3.
Features of Python
Simple: Python syntax is very easy. Developing and understanding python is
very easy than others. The below comparison illustrated how simple python
language is when compared to other languages.

2
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Open Source – We can download freely and customize the code as well
Dynamically typed – Dynamically type will be assigned to data.
Platform independent: Python programs are not dependent on any specific
operating systems. We can run on all operating systems happily.
Portable: If a program gives the same result on any platform then it is a
portable program. Python used to give the same result on any platform.
Huge library – Python has a big library to fulfill the requirements.
Database connectivity – Python provides interfaces to connect with all major
databases like oracle, MySQL
Batteries included – Python provides inbuilt libraries called batteries. Some of
them are below
1. Boto – amazon web services library
2. MySQL-connector-python – To connect with MySQL
3. NumPy – To process arrays
4. Pandas – powerful data structures for data analysis, time series, and
statistics
Where all python is used?
Python is being used to develop:
1. Standalone applications: An application that needs to install on every
machine to work with that application.
2. Web applications: An application that follows a client-server
architecture. The client is a program, which sends requests to the server.
The server is a program, mainly it can do three things. Captures the
request from the client, Process the request, and Sends the response to
the client
3. Database applications.
4. To process huge amounts of data. Ex Hadoop, Spark.
5. Machine learning.
6. Artificial Intelligence.
7. Data science.
8. Network servers.
9. IoT
10.Application scripting etc.
Python supports
1. Functional programming as well as Object-oriented programming
approach.
2. Initial languages like C, Pascal, or FORTRAN follow functional
approaches.
3. C++, Java, and dot net follow an object-oriented approach.
4. Python follows both functional and object-oriented approaches.
Python an interpreted language
An interpreter is very different from a compiler. An interpreter executes the
statements of code “one-by-one” whereas the compiler executes the code
entirely and lists all possible errors at a time. That’s why python shows only
one error message even though your code has multiple errors. This will help
you to clear errors easily.

3
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Keywords in Python
All keywords in python contain only alphabet symbols. All of them are in lower
case except True, False, and None. To see all the keywords –
1. import keyword;
2. keyword.kwlist
Keywords – [‘False’, ‘None’, ‘True’, ‘and’, ‘as’, ‘assert’, ‘break’, ‘class’, ‘continue’,
‘def’, ‘del’, ‘elif’, ‘else’, ‘except’, ‘finally’, ‘for’, ‘from’, ‘global’, ‘if’, ‘import’, ‘in’, ‘is’,
‘lambda’, ‘nonlocal’, ‘not’, ‘or’, ‘pass’, ‘raise’, ‘return’, ‘try’, ‘while’, ‘with’, ‘yield’]
Keyword is a module in python
S.No Flow ControlException Handling Class Functions and methods
Variable Object Module Membership Build-in Constants
Logical
1 if try class def global del import is True and

2 else except with nonlocal from in False or


3 elif raise lambda as None not
4 for finally
5 while assert
6 break
7 continue
8 return
9 yield
10 pass
Different flavors of python
Flavors of python refer to the different types of python compilers. These are
useful to integrate various programming languages.
1. CPython: Standard python compiler implemented in C language. This is
the python software being downloaded and used by the programmers
directly.
2. Jython: Initially called as JPython, later renamed to Jython. Designed to
run on a Java program.
3. IronPython: Designed for .NET framework.
4. PyPy: The main advantage of PyPy is performance will be improved
because the JIT compiler is available inside PVM.
5. RubyPython: This is a bridge between Ruby and Python interpreters. It
encloses a python interpreter inside the Ruby application.
6. AnacondaPython: Anaconda is a free and open-source Python
programming language. This is mainly for data science and machine
learning-related applications (large-scale data processing, predictive
analytics, scientific computing). This aims to simplify package
management and deployment.

4
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Python Coding Instructions
Installation procedure For Windows:
You can download a python installer
from https://www.python.org/downloads/
depending upon the operating system and the version (32-bit or 64-bit version)
your system has. Download the latest stable version. (The current version is
3.x.x.x)
After downloading the installer from the above site you have to run the installer
and follow the instructions in order to get the Python installed in your system.
During the setup, window make sure to click on “Add Python 3.6 to PATH” or
‘Add Python to your environment variables” checkbox before clicking on Install
Now.
Note: Don’t forget to check the box as mentioned above. If not checked then
you have to add the Python to your environment variables.
Installation procedure For For Linux:
For Linux, the python will come pre-installed. You can check the version of it
with the command “python3 –version”. If you don’t have python installed then
you can follow depending on the Linux distribution.
1. For Ubuntu: sudo apt install python3
2. For Fedora: sudo dnf install python3
3. For SUSE: sudo zypper install python3
Ways to write a python program
All the programs written in python should be saved using the ‘.py’ or ‘.python’
extension. Files can be executed using the command prompt or terminal (based
on OS). For writing the python programs we can use the following things
1. By using a text editor like notepad++, VI Editor, etc…
2. You can use IDEs available online like VS Code, Atom, PyCharm, etc.
3. Python has a special feature of interactive mode where the python code
can be executed line by line. In the command prompt/terminal if you
type ‘python’ then the interactive mode comes as shown below
4. $ python
Python 3.5.2 (default, Apr 16 2020, 17:47:17)
[GCC 5.4.0 20160609] on linux
Type “help”, “copyright”, “credits” or “license” for more
information.
>>> print(“Hello World”)
Hello World
>>>exit()
5. Note: In interactive mode, we type the instructions line by line. exit() is
used to quit from the interactive mode.
Python IDLE:
An IDLE is automatically installed while installing the python. If you have
python installed on the system then search for it using ‘IDLE’. You can use that
IDLE for both interactive modes as well as the normal mode of executing the
python file using the command. For this tutorial, it is suggested to follow the
below steps for execution.

5
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Program execution steps
1. First write the code in notepad or IDE (Initially, it would be better to write
the code in notepad if you are new to IDEs)
2. Save the file with .py or .python extension.
3. Run or execute the program (For windows execute the file from command
prompt and for linux from terminal)
4. Command for execution – “python filename.py” or “py filename.py”
Program to print hello world
Code:
print(“HELLO WORLD”)
Output: HELLO WORLD
Understanding demo1.py
print(“HELLO WORLD”): print() is a predefined function/method in python. It
takes strings values as input parameters. It prints the output on the console.
Python Program Execution Flow
The below flow is followed during the execution

First, we need to write a code and save the file with a .py extension. Then we
need to run the program. When the program is running, the Internal python
compiler takes the source code and creates the corresponding compiled python
file, which is not visible to the user The compiled file is saved in the computer
cache. If you want to see the file, then you can run the below command
python -m py_compile demo.py
Here, the -m argument states that it’s a module, and the module name
is py_complile. This is the module that creates the compiled file which is
stored as __pycache__ in the same directory.
Now the compiled file contains byte code instructions that are not
understandable by the microprocessor to generate output. So, the Python
Virtual Machine comes into the picture and takes the responsibility of
converting the byte code instructions to machine-understandable format and it
does this line by line. Finally, we will see the output
PVM uses an interpreter which converts line by line, which is very slow. To
resolve this, some flavors like PyPy use compilers like JIT(Just in Time) which
convert very fast.

6
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Naming Conventions in Python
What is an identifier in Python?
A Python identifier is a name used to identify a variable, function, class,
module, or other objects. This name can be
1. class name
2. package name
3. variable name
4. module-name
5. function name
6. method name
Python developers made some suggestions to the programmers regarding how
to write identifiers in a program.
Rules to define identifiers in Python:
The only allowed characters to write identifier in python are,
1. Alphabets can be either lowercase or uppercase.
2. Digits (0 to 9)
3. Underscore symbol (_)
4. Usage of any other symbol (like $,!,#, @) apart from these will result in
Syntax Error.
Identifiers allow digits, but identifiers should not start with digits. Identifiers
are case-sensitive. We cannot use keywords as identifiers. Spaces are not
allowed between identifiers.
Example: Program to print variable name
Code:
emp_id = 11
print(emp_id)
Output: 11
Example: Variable name with symbols
Code:
$tudent_id = 23
print($tudent_id)
Output: SyntaxError: invalid syntax
Example: Variable name with digits
Code:
student1 = 12
print(student1)
Output: 12
Example: Variable name starts with digits
Code:
1stundent = 12
print(student1)
Output: SyntaxError: invalid syntax
Example: Case sensitive
Code:
a = 10
7
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
b = 20
print(A+B)
Output: NameError: name ‘A’ is not defined
Example: Keyword as variable name
Code:
if = 10
Output: SyntaxError: invalid syntax
Example: Space in variable name
Code:
student id = 10
print(student id)
Output: SyntaxError: invalid syntax
Examples of Identifiers in Python:
1. 435student → invalid (Should not start with a digit)
2. student564 → valid
3. student565info → valid
4. $tudent → invalid (Should not start with symbol)
5. _student_info → valid (Can start with underscore )
6. class → invalid (Keyword can’t be used as identifier)
7. def → invalid (Keyword can’t be used as identifier)
Identifiers best practices in a table

8
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Suggestions:
Be descriptive – A variable name should depict exactly what it contains and a
function should describe exactly what it does
1. a = 10 # valid but not recommended
2. student_id = 10 # valid and highly recommended
3. abc() # valid but not recommended
4. sum() # valid and highly recommended
Don’t use abbreviations unnecessarily. Abbreviations may be ambiguous and
more difficult to read.
1. fourth_bentch_middle_student_id = 10 #valid but not recommended
2. student_id = 10 #valid and highly recommended
Indentation in Python
In Python, we need to group the statements by using indentation.
1. Indentation keeps the group of statements separate.
2. The recommended indentation is 4 spaces.
3. We must follow the order of indentation otherwise we will get
IndentationError
valid Indentation
Code:
print(“statement one”)
print(“statement two”)
print(“statement three”)
Output:
statement one
statement two
statement three
Invalid Indentation
Code:
print(“statement one”)
print(“statement two”)
print(“statement three”)
Output: IndentationError: unexpected indent
Invalid Indentation
Code:
print(“statement one”)
print(“statement two”)
print(“statement three”)
Output: IndentationError: unexpected indent

Comments in Python:
1. Comments are useful to describe the code in an easy way.
2. Python ignores comments while running the program.
3. To comment python code, we can use hash symbol #
4. For multi-line comments, we can use single/double/triple quotation
marks.

9
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Comments Example in Python:
Code:
# This is a Basic program in python
print(“Welcome to python programming”)
Output: Welcome to python programming
Why naming conventions are important in Python?
Naming conventions are a set of rules or best practices that are suggested to be
followed while naming an identifier. The benefits of following the naming
conventions are:
1. They help us in understanding what a particular identifier is.
2. When we are able to identify what is the class name, variable name, etc.
then our time and effort to understand the code will be decreased.
3. Following naming convention will increase the readability of code
4. The naming conventions will help us in debugging the code fastly.

Variables in Python
What is a variable in Python?

All the data which we create in the program will be saved in some memory
location on the system. The data can be anything, an integer, a complex
number, a set of mixed values, etc.

If we want to use the data, which is saved in the memory location, we need to
call the reference of that location, which we don’t know. What if we give some
name of our choice to that memory location? This will help us in using that
data by referring to the name which we have given to that memory location.
That name is called variable.

Variable is the name that we give to the memory location which holds some
data. With a variable, we can store the data, access the data, and also
manipulate the data. We can also refer to variables as containers which store
some information/data.

To summarize, a variable is a
1. Name
2. Refers to a value
3. Hold some data
4. Name of a memory location
Example 1: (printing variable)
Code:
emp_id = 11
print(emp_id)
Output: 11

10
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Properties of a variable in Python:

Every variable has some properties which each programmer should have some
basic idea of.

Type: Each and every programming language has data types and each variable
should belong to one of the data types. This is called the type of variable. In
Python language, the data types available are lists, tuples, dictionaries, strings,
sets, etc

Scope: In any programming language, scope refers to the place or limit or


boundaries or the part of the program within which the variable is accessible.
Generally, the two types of scopes defined are the global scope and local scope

Value: Each and every variable in a program holds the value of some type that
can be accessed or modified during the due flow of the program.

Location: As already stated, the data is stored in the memory location. The
variable is the name that we give to that location. Each memory location has
some address associated with it.
Lifetime: The lifetime of a variable refers to the time period for which the
memory location associated with the variable stores the data.

Creating a variable in Python


Generally, in many programming languages, while defining or creating a
variable, we need the data type and variable name and value. For example, in C
language variable creation
int i = 10;
Python is a dynamically typed programming language. There is no need of
specifying the data type for a variable. The program automatically takes the
data type dynamically during the creation. In python, to create a variable we
just need to specify
1. Name of the variable
2. Assign a value to the variable
Syntax to create variable in python: name_of_the_variable = value
Example 2: (creating a variable)
Code:
age = 110
print(age)
Output: 110

11
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Example 3: (creating a variable and printing with a beautiful message)
Code:
age = 16
print(“My age is sweet”, age)
Output: My age is sweet 16
Note: We can print meaningful text messages along with variables for better
understanding.
1. Text message we should keep in within double-quotes.
2. Text message and variable name should be separated by comma symbol.

Invalid cases for variables:


While defining variables in python,
1. Variable names should be on the left side.
2. The value should be on the right side.
3. Violating this will result in a syntax error
Example 4: (creating variable in wrong direction)
Code:
10 = emp_id
print(emp_id)
Output: SyntaxError: can’t assign to literal
Variable names should not be keywords, else will result in an error.

Example 5: (creating a variable with keyword name)


Code:
if = 10
print(if)
Output: SyntaxError: invalid syntax
Multiple variables in a single line in Python:
We can assign multiple variables to multiple values in a single line. During the
assignment, the variable name on the left-hand side should be equal to the
values on the right-hand side. If not it results in an error.
Example 6: (assigning multiple variables in single line)
Code:
a,b,c = 10,20,30
print(a,b,c)
Output: 10 20 30
Example 7: (unequal items on either side)
Code:
a,b,c = 10,20
print(a,b,c)
Output: ValueError: not enough values to unpack (expected 3, got 2)

Example 8: (unequal items on either side)


Code:
a,b = 10,20,30

12
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
print(a,b,c)
Output: ValueError: too many values to unpack (expected 2)
Single value for multiple variables in Python
We can assign a single value to multiple variables simultaneously.
Example 9: (assign value to multiple variables)
Code:
a = b = c = 10
print(a,b,c)
Output: 10 10 10
Re-initialize the variables in Python
We can reinitialize the variable values. The old values will be overridden or
replaced with the new values.
Example 10: (re-initializing the variables)
Code:
a = 20
print(“first assigned value: “, a)
a = 40
print(“variable is re-initialised, now value is : “, a)
print(type(a))
Output:

Note: Python has an in-built function called type() which gives the datatype of
the variable which is defined in the program. In the above example, since the
variable ‘a’ is of ‘int’ data type so type(a) gives the output as ‘int’.

Data Types in Python


What is a Data Type?
All programming languages’ aim is to create some data or to do some actions on
the data and process the data. The data can be categorized into different types
like integers, float numbers, boolean, string, etc. Categorizing the data is
important in order to perform the operations on it. That classification, which
states the type of data stored in the variable is called data type. Each and every
programming language provides certain data types such that all the types of
data can be stored in those.
Example: To print different kinds of variables

emp_id = 11
name = 'Irfan'
salary = 2000.40

13
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
print("My employee id is: ", emp_id)
print("My name is: ", name)
print("My salary is: ", salary)
Output:

type() function in Python:


type() is an in-built or pre-defined function in python that is used to check the
data type of the variables. The following example depicts the usage.
Example: To print different kinds of variables and their types

emp_id = 11
name = 'Irfan'
salary = 2000.40
print("My employee id is: ", emp_id)
print("My name is: ", name)
print("My salary is: ", salary)
print("emp_id type is: ", type(emp_id))
print("name type is: ", type(name))
print("salary type is: ", type(salary))
Output:

Different types of data types in Python with Examples


Generally, data types can be classified into two types:
1. Built-in data types: Data types that are already available in python are
called built-in data types
2. User-defined data types: Data types that are created by the programmer
Built-in data types in Python:
1. Numeric types (int, Float, Complex)
2. bool
3. None
4. Str
5. Bytes

14
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
6. Bytearray
7. Tuple
8. List
9. Range
10.Set
11.dict
Numeric types in Python:
int: The int data type represents values or numbers without decimal values. In
python, there is no limit for the int data type. It can store very large values
conveniently.
Example: to print integer value

emp_id = 11
print(emp_id)
print(type(emp_id))
Output:
11
<class ‘int’>
Note: In Python 2nd version long data type was existing but in python 3rd
version long data type was removed
Float Data Type in Python:
The float data type represents a number with decimal values. floating-point
numbers can also be written in scientific notation. e and E represent
exponentiation. where e and E represent the power of 10. For example, the
number 2 * 10pow2 is written as 2E2, such numbers are also treated as
floating-point numbers.
Example: To print float value

salary = 50.5
print(salary)
print(type(salary))
Output:
50.5
<class ‘float’>
Example: Print float values

a = 2e2
b = 2E2
c = 2e3
print(a)
print(b)
print(c)
print(type(a))

15
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Output:
200.0
200.0
2000.0
<class ‘float’>
Complex Data Type in python:
The complex data type represents the numbers that are written in the form of
a+bj or a-bj, here a is representing a real part of the number and b is
representing an imaginary part of the number. The suffix small j or upper J
after b indicates the square root of -1. The part “a” and “b” may contain integers
or floats.
Example: To print the complex value

a = 3+5j
b = 2-5.5j
c = 3+10.5j
print(a)
print(b)
print(c)
print()
print(a+b)
print(b+c)
print(c+a)
Output:
(3+5j)
(2-5.5j)
(3+10.5j)
(5-0.5j)
(5+5j)
(6+15.5j)
If we compare two complex values with <, <=, >, >= operators then we will get
TypeError
Example: Comparing two complex numbers

a = 2 + 1j
b = 100 + 10j
print(a>b)
Output: TypeError: ‘>’ not supported between instances of ‘complex’ and
‘complex’
Bool Data Type (boolean data type) in Python:
The bool data type represents boolean values in python. bool data type having
only two values are, True and False. Python internally represents, True as
1(one) and False as 0(zero). An empty string (“ ”) represented as False.
16
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Example: Printing bool values

a = True
b = False
print(a)
print(b)
print(a+a)
print(a+b)
Output:
True
False
2
1
None data type in Python:
None data type represents an object that does not contain any value. If any
object has no value, then we can assign that object with None type.
Example: Printing None data type:

a = None
print(a)
print(type(a))
Output:
None
<class ‘NoneType’>
If any function and method are not returning anything then that method can
return None data type.
Sequences in python:
Sequences in Python are objects that can store a group of values. The below
data types are called sequences.
1. Str
2. Bytes
3. Bytearray
4. List
5. Tuple
6. Range
str data type in python:
A group of characters enclosed within single quotes or double quotes or triple
quotes is called a string. We will discuss more in the string chapter.
Example: Printing string data type

name1 = "nireekshan"
name2 = """nireekshan"""
print(name1)
17
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
print(name2)
Output:
nireekshan
nireekshan
Bytes Data Type in Python:
Bytes data type represents a group of numbers just like an array. It can store
values that are from 0 to 256. The bytes data type cannot store negative
numbers. To create a byte data type. We need to create a list. The created list
should be passed as a parameter to the bytes() function. The bytes data type is
immutable means we cannot modify or change the bytes object. We can iterate
bytes values by using for loop.
Example: creating a bytes data type

x = [10, 20, 100, 40, 15]


y = bytes(x)
print(type(y))
Output: <class ‘bytes’>
Example: Accessing bytes data type elements using index

x = [10, 20, 30, 40, 15]


y = bytes(x)
print(y[0])
print(y[1])
print(y[2])
print(y[3])
print(y[4])
Output:
10
20
30
40
15
Example: Printing the byte data type values using for loop

x = [10, 20, 100, 40, 15]


y = bytes(x)
for a in y:
print(a)
Output:
10
20
30

18
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
40
15
Example: To check Values must be in range 0,256

x = [10, 20, 300, 40, 15]


y = bytes(x)
Output: ValueError: bytes must be in range(0, 256)
Example: To check Byte data type is immutable

x = [10, 20, 30, 40, 15]


y = bytes(x)
y[0] = 30
Output: TypeError: ‘bytes’ object does not support item assignment
bytearray data type in python:
The bytearray data type is the same as the bytes data type, but bytearray is
mutable means we can modify the content of bytearray data type. To create a
bytearray
1. We need to create a list
2. Then pass the list to the function bytearrray().
3. We can iterate bytearray values by using for loop.
Example: Creating bytearray data type

x = [10, 20, 30, 40, 15]


y = bytearray(x)
print(type(y))
Output: <class ‘bytearray’>
Example: Accessing bytearray data type elements using index

x = [10, 20, 30, 40, 15]


y = bytearray(x)
print(y[0])
print(y[1])
print(y[2])
print(y[3])
print(y[4])
Output:
10
20
30
40
15

19
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Example: Printing the byte data type values using for loop

x = [10, 20, 00, 40, 15]


y = bytearray(x)
for a in y:
print(a)
Output:
10
20
30
40
15
Example: Values must be in the range 0, 256

x = [10, 20, 300, 40, 15]


y = bytearray(x)
Output: ValueError: bytes must be in range(0, 256)
Example: Bytearray data type is mutable

x = [10, 20, 30, 40, 15]


y = bytearray(x)
print("Before modifying y[0] value: ", y[0])
y[0] = 30
print("After modifying y[0] value: ", y[0])
Output:
Before modifying y[0] value: 10
After modifying y[0] value: 30

List Data Type in Python:


We can create a list data structure by using square brackets []. A list can store
different data types. The list is mutable.
Tuple Data Type in Python:
We can create a tuple data structure by using parenthesis (). A tuple can store
different data types. A tuple is immutable.
Range Data Type in Python:
We can create a range of values by using the range() function. The range data
type represents a sequence of numbers. The range data type is immutable
means we cannot modify it once it is created. Range data type values can be
printed by using for loop.
Example: Creating a range of values using a range

a=range(5)

20
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
print(a)
for x in a:
print(x)
Output:
range(0, 5)
0
1
2
3
4
Note: A list of values can be created using the range.
Example: Creating a list

a=list(range(1, 10))
print(a)
Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Example: Accessing values using index

a=range(1, 10)
print(a[0])
print(a[1])
Output:
1
2
Example: Accessing elements out of range

a=range(1, 10)
print(a[0])
print(a[20])
Output: IndexError: range object index out of range

Set Data Type:


We can create a set data structure by using parentheses symbols (). The set can
store the same type and different types of elements
Dictionary Data Type in Python:
We can create dictionary types by using curly braces {}. The dict represents a
group of elements in the form of key-value pairs like a map
User-defined Data Types in Python:
The data type which is created by the programmers is called “user-defined” data
types in python. Examples are class, module, array, etc.

21
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Fundamental Data Types in Python:
In Python, the following data types are considered as Fundamental Data types,
1. Int
2. Float
3. Complex
4. Bool
5. Str
Conversion of Data Types in Python:
Based on requirements, developers can convert from one data type into another
data type explicitly, this is called type conversion. Python provides inbuilt
functions to convert from one type to another type.
1. int() : convert from other type into int type
2. float() : convert from other type into float type
3. complex() : convert from other type into complex type
4. bool() : convert from other type into bool type
5. str() : convert from other type into str type

Operators in Python
What is an Operator?
In programming languages, an operator is a symbol that is applied to some
operands (usually variables), to perform certain actions or operations. For
example,

In the above example, first, we assigned values to two variables ‘a’ and ‘b’ and
then we added both the variables and stored the result in variable ‘c’. The
operations we performed are:
1. Assignment Operation using ‘=’ operator. We assigned the values to
variables ‘a’, ‘b’, ‘c’ using the operator ‘=’ which is called the assignment
operator.
2. Addition Operation using ‘+’ operator. The values in variables are added
using the ‘+’ operator.
Note: The symbols + and = are called operators and the variables a,b,c on
which operation is being performed are called operands.
BASIC CLASSIFICATION OF OPERATORS IN PYTHON
Unary Operator – If the operator acts on a single operand then it’s called the
unary operator. For example, in ‘-5’ the operator ‘-’ is used to make the (single)
operand ‘5’ a negative value hence called the unary operator.

22
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Binary Operator – If the operator acts on two operands then it’s called a binary
operator. For example, + operators need two variables(operands) to perform
some operation, hence called binary operator.
Ternary Operator – If the operator acts on three operands then it’s called a
ternary operator. In general, the ternary operator is a precise way of writing
conditional statements. The concept behind this will be understood in the later
chapters. For now, just consider the simple syntax shown below.
x = true_value if condition else false_value

The three operands here are :


1. condition
2. true_value
3. False_value
Here if the condition is evaluated to true then the value in true_value will be in
x else the value in false_value.
Types Of Operators in Python:
1. Arithmetic Operators: The operators which are used to perform
arithmetic operations like addition, subtraction, division etc. They are: +,
-, *, /, %, **, //
2. Relational Operators: The operators which are used to check for some
relation like greater than or less than etc.. between operands are called
relational operators. They are: <, >, <=, >=, ==, !=
3. Logical Operators: The operators which do some logical operation on the
operands and return True or False are called logical operators. The
logical operations can be ‘AND’, ‘OR’ etc.
4. Assignment Operators: The operators which are used for assigning
values to variables. ‘=’ is the assignment operator.
5. Unary Minus Operator: The operator ‘-’ is called the Unary minus
operator. It is used to negate the number.
6. Membership Operators: The operators that are used to check whether a
particular variable is part of another variable or not. They are ‘in’ and
‘not in’
7. Identity Operators: The operators which are used to check for identity.
They are ‘is’ and ‘is not’.

ARITHMETIC OPERATORS IN PYTHON:


As stated above, these are used to perform that basic mathematical stuff as
done in every programming language. Let’s understand them with some
examples. Let’s assume, a = 20 and b = 12

23
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training

Note: Division operator / always performs floating-point arithmetic, so it


returns a float value. Floor division (//) can perform both floating-point and
integral as well,
1. If values are int type, the result is int type.
2. If at least one value is float type, then the result is of float type.
Example: Arithmetic Operators in Python

a = 20

b = 12

print(a+b)

print(a-b)

print(a*b)

print(a/b)

print(a%b)

print(a**b)

print(a//b)

24
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Output:

Example: Floor division

print(12//5)

print(12.0//5)
Output:
2
2.0
RELATIONAL OPERATORS IN PYTHON:
These are used to compare two values for some relation and return True or
False depending on the relation. Let’s assume, a = 13 and b = 5

Relational operators are used, in general, for construction simple conditions.


Example: Relational Operators in Python

a = 13

b=5

print(a>b)

print(a>=b)

print(a<b)

print(a<=b)

25
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
print(a==b)

print(a!=b)
Output:

LOGICAL OPERATORS IN PYTHON


In python, there are three types of logical operators. They are and, or, not.
These operators are used to construct compound conditions, combinations of
more than one simple condition. Each simple condition gives a boolean value
which is evaluated, to return the final boolean value.
Note: In logical operators, False indicates 0(zero) and True indicates non-zero
value. Logical operators on boolean types
1. and: If both the arguments are True then only the result is True
2. or: If at least one argument is True then the result is True
3. not: the complement of the boolean value
Example: Logical operators on boolean types in Python

a = True

b = False

print(a and b)

print(a or b)

print(not a)

print(a and a)
Output:

Logical operators on non-boolean types


Please understand the below statements carefully,
and operator:
‘A and B’ returns A if A is False
‘A and B’ returns B if A is not False

26
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Examples: ( 0 means False and non-zero means True)
1. 0 and 4 returns 0
2. 5 and 7 returns 7
3. 21 and 0 returns 0
4. 15 and 8 returns 8
Example: Logical and operators on non-boolean types in Python

print(0 and 4)

print(5 and 7)

print(21 and 0)

print(15 and 8)
Output:
0
7
0
8
Example: Logical and operators on non-boolean types in python

x=0

y=4

a=4

b=7

print(x and y)

print(a and b)
Output:
0
7
Example: Logical and operators on non-boolean types in python

x = 21

y=0

a = 15

b=8

print(x and y)

print(a and b)
27
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Output:
0
8
Or Operator in Python:
‘A or B’ returns A if A is True
‘A or B’ returns B if A is not True
Examples: (0 means False and non-zero means True)
1. 0 or 4 returns 4
2. 5 or 7 returns 7
3. 21 or 0 returns 21
4. 15 or 8 returns 8
Example: Logical OR operators on non-boolean types in python

print(0 or 4)

print(5 or 7)

print(21 or 0)

print(15 or 8)
Output:

Example: Logical or operators on non-boolean types in python

x=0

y=4

a=5

b=7

print(x or y)

print(a or b)
Output: 4 5
Example: Logical or operators on non-boolean types in python

x = 21

y=0

a = 15

28
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
b=8

print(x or y)

print(a or b)
Output: 21 15
Not Operator in Python:
not A returns False if A is True
not B returns True if A is False
Examples, (0 means False and non-zero means True)
1. not 5 returns False
2. not 0 returns True
Example: Logical not operator on non-boolean types in python

print(not 5)

print(not 0)
Output:
False
True
Example: Logical not operator on non-boolean types in python

x=5

y=0

print(not x)

print(not y)
Output:
False
True
Conclusion

ASSIGNMENT OPERATORS IN PYTHON


By using these operators, we can assign values to variables. ‘=’ is the
assignment operator used in python. There are some compound operators
which are the combination of some arithmetic and assignment operators (+=, -
=, *=, /=, %=, **=, //= ). Assume that, a = 13 and b = 5
29
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training

Example: Assignment Operators in Python

a=13

print(a)

a+=5

print(a)
Output:
13
18
UNARY MINUS OPERATOR(-) IN PYTHON:
This operator operates on a single operand, hence unary operator. This is used
to change a positive number to a negative number and vice-versa.
Example: Unary Minus Operators in Python

a=10

print(a)

print(-a)
Output:
10
-10
MEMBERSHIP OPERATORS IN PYTHON
Membership operators are used to checking whether an element is present in a
sequence of elements are not. Here, the sequence means strings, list, tuple,
dictionaries, etc which will be discussed in later chapters. There are two
membership operators available in python i.e. in and not in.
1. in operator: The in operators returns True if element is found in the
collection of sequences. returns False if not found
2. not in operator: The not-in operator returns True if the element is not
found in the collection of sequence. returns False in found
Example: Membership Operators in Python

text = "Welcome to python programming"

print("Welcome" in text)

30
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
print("welcome" in text)

print("nireekshan" in text)

print("Hari" not in text)


Output:

Example: Membership Operators in Python

names = ["Ramesh", "Nireekshan", "Arjun", "Prasad"]

print("Nireekshan" in names)

print("Hari" in names)

print("Hema" not in names)


Output:

IDENTITY OPERATOR IN PYTHON


This operator compares the memory location( address) to two elements or
variables or objects. With these operators, we will be able to know whether the
two objects are pointing to the same location or not. The memory location of the
object can be seen using the id() function.
Example: Identity Operators in Python

a = 25

b = 25

print(id(a))

print(id(b))
Output:

Types of Identity Operators in Python:


There are two identity operators in python, is and is not.

31
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
is:
1. A is B returns True, if both A and B are pointing to the same address.
2. A is B returns False, if both A and B are not pointing to the same
address.
is not:
1. A is not B returns True, if both A and B are not pointing to the same
object.
2. A is not B returns False, if both A and B are pointing to the same object.
Example: Identity Operators in Python

a = 25

b = 25

print(a is b)

print(id(a))

print(id(b))
Output:

Example: Identity Operators

a = 25

b = 30

print(a is b)

print(id(a))

print(id(b))
Output:

Note: The ‘is’ and ‘is not’ operators are not comparing the values of the objects.
They compare the memory locations (address) of the objects. If we want to
compare the value of the objects, we should use the relational operator ‘==’.
Example: Identity Operators

a = 25

b = 25
32
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
print(a == b)
Output: True
Example: Identity Operators

a = 25

b = 30

print(a == b)
Output: False

Input and Output in Python


Why the Input and Output chapter in Python?
In the previous chapters, all the coding examples were having values hardcoded
within the code itself. Let’s have a look at the example below which checks if
the person is in their teenage or not.
Example: Hardcoded values to a variable

age = 16
if age >= 13 and age <= 19:
print("Teenage")
Output: Teenage
In the above program, we have hard-coded the age value as 16. If we want to
check for other ages then we need to open the file, change the value of age and
then execute it again. This is not a good practice.
In real-time passing the values to the variables during runtime or dynamically
is a good practice. So, it’s very necessary and important for us to know about
all the functions or methods available in python to take the input during
runtime.
INPUT and OUTPUT in Python
A predefined function input() is available in python to take input from the
keyboard during runtime. This function takes a value from the keyboard and
returns it as a string type. Based on the requirement we can convert from string
to other types.
Example: input() method in Python

name = input("Enter the name: ")


print("You entered name as: ", name)
Output:

33
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Example: Checking return type of input() method in python

name = input("Enter the name: ")


age = input("Enter the age: ")
print("You entered name as: ", name)
print("You entered age as:", age)
print(type(age))
Output:

In the above example, the type of age is a string but not an integer. If we want
to use it as an integer then we need to do type conversion on it and then use it.
Let’s understand that through our teenager program.

Example: Checking return type of input() method in python

age = input("Enter the age: ")


if int(age) >= 13 and int(age) <= 19:
print("Teenage")
Output:

Convert to other data types from a string in Python


We can convert the string to other data types using some inbuilt functions. We
shall discuss all the type conversion types in the later chapters. As far as this
chapter is concerned, it’s good to know the below conversion functions.
1. string to int – int() function
2. string to float – float() function
Example: Converting string type to int() in Python
Output:

34
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Example: Converting string type to float() in Python

salary = input("Enter your salary: ")


print("Your salary is: ", salary)
print("salary type is: ", type(salary))
x = float(salary)
print("After converting from string to float your salary is: ", x)
print("now salary type is: ", type(x))
Output:

Example: Taking int value at run time in Python

age = int(input("Enter your age: "))


print("Your age is: ", age)
print("age type is: ",type(age))
Output:

Example: Taking int value and print their sum in Python

x = int(input("Enter first number: "))


y = int(input("Enter second number: "))
print("Sum of two values: ", x+y)
Output:

eval() function in python


This is an in-built function available in python, which takes the strings as an
input. The strings which we pass to it should, generally, be expressions. The
35
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
eval() function takes the expression in the form of a string and evaluates it and
returns the result.
Examples,
 eval(’10 + 10′) → 20
 eval(’10 * 10′) → 100
 eval(’10 and 10′) → 10
 eval(’10 or 10′) → 10
 eval(‘0 and 10’) → 0
 eval(’10 or 0′) → 10
 eval(’10 / 10′) → 1.0
 eval(’10 // 10′) → 1
 eval(’10 >= 10′) → True
Example: eval() function example in python

sum = eval(input("Enter expression: "))


print(sum)
Output:

Example: eval() function example in Python

output = eval(input("Enter expression: "))


print(output)
Output:

Command Line Arguments in Python:


The command which we are using for running the python file for all the
examples in this tutorial is “python filename.py”. This command we are
executing thorough is command prompt/terminal. The script is invoked with
this command and the execution starts. While invoking the script we can pass
the arguments to it, which are called command-line arguments. Arguments are
nothing but parameters or values to the variables.
The command with the arguments will look like: python filename.py 10 20
Our command is ‘python’ and the ‘filename.py’ ‘10’ ‘20’ are arguments to it. In
order to use these arguments in our script/code, we should do the following
import
from sys import argv
After including the above import statement in our file, the arguments which we
pass from the command are available in an attribute called ‘argv’. argv will be a
list of elements that can be accessed using indexes.
1. argv[0] will always be the filename.py
36
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
2. argv[1] will be 10 in this case
3. argv[2] will be 20 in this case
Example: Command line arguments in python
demo11.py
from sys import argv
print(argv[0])
print(argv[1])
print(argv[2])
Command: python demo11.py 30 40
Output:

IndexError in Python:
If we are passing 2 elements as arguments to the script (excluding the default
argument filename), then the script has three arguments passed to it. But in
the script, if we are trying to access the 10th argument with argv[9], then we get
an IndexError. We can understand it from demo12.py
Example: Command line arguments
demo12.py
from sys import argv
print(argv[10])
Command: python demo12.py 30 40
Output:

Note: Command-line arguments are taken as strings elements, which means


argv[0], argv[1], etc.. returns string type. (‘argv’ is a list as mentioned above and
each individual element in it will be a string). Based on the requirement we can
convert from string type to another type.
Example: Command line arguments
demo13.py
from sys import argv
first_name = argv[1]
last_name=argv[2]
print("First name is: ", first_name)
print("Last name is: ", last_name)
print("Type of first name is", type(first_name))
print("Type of last name is", type(last_name))
37
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Command: python demo13.py Ram Pothineni
Output:

Example: Command line arguments


demo14.py
from sys import argv
item1_cost = argv[1]
item2_cost =argv[2]
print("First item cost is: ", item1_cost)
print("Second item cost is: ", item2_cost)
print("Type of item1_cost is : ", type(item1_cost))
print("Type of item2_cost is : ", type(item2_cost))
total_items_cost= item1_cost + item2_cost
print("Total cost is: ", total_items_cost)
Command: python demo14.py 111 223
Output:

Example: Command line arguments


demo15.py
from sys import argv
item1_cost = argv[1]
item2_cost =argv[2]
x=int(item1_cost)
y=int(item2_cost)
print("First item cost is: ", x)
print("Second item cost is: ", y)
print("Type of item1_cost is : ", type(x))
print("Type of item2_cost is : ", type(y))
total_items_cost= x + y
print("Total cost is: ", total_items_cost)

38
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Command: python demo15.py 111 223
Output:

In the demo14.py example, the requirement is to take the cost of the items and
return the sum of it. For adding the two values we have used the ‘+’ operator
which adds the two operands if they are integers and combines the two
operands if they are strings. Since argv[1] and agrv[2] are taken as strings, the
output is the addition of two strings ‘111’ and ‘223’ i.e ‘111223’.
In the demo15.py, we see that argv[1] and agrv[2] are converted to integer types
and then the ‘+’ operator is applied to them. Hence the output in demo15.py is
334 i.e 111+223
len() function in python:
len() is an in-built function available in python, which can be applied on certain
data types like lists, tuples, strings, etc in python to know how many elements
are present in it. Since ‘argv’ is a list we can apply this len() function to it to
know how many arguments have been passed.
Example: Command line arguments with len function in python
demo16.py
from sys import argv
print("The length of values :", len(argv))
Command: python demo16.py 10 20 30
Output:

Note: By default, space is the separator between two arguments while passing.
If we want space in the argument itself, then we need to pass that argument
enclosed in double-quoted( not in single quotes)
Example: Command line arguments
demo17.py
from sys import argv
print(argv[1])
Command: python demo17.py hello good morning
Output: hello

Example: Command line arguments


demo18.py
from sys import argv
print(argv[1])

39
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Command: python demo18.py “hello good morning”
Output: hello good morning

Control Flow Statements in Python


Why should we learn about flow control?
In programming languages, flow control means the order in which the
statements or instructions, that we write, get executed. In order to understand
a program, we should be aware of what statements are being executed and in
which order. So, understanding the flow of the program is very important. There
are, generally, three ways in which the statements will be executed. They are,
1. Sequential
2. Conditional
3. Looping
Flow control graphs

Sequential: In this type of execution flow, the statements are executed one
after the other sequentially. By using sequential statements, we can develop
simple programs
Conditional: Statements are executed based on the condition. As shown above
in the flow graph, if the condition is true then one set of statements are
executed, and if false then the other set. Conditional statements are used much
in complex programs.
Looping(iteration): A set of statements are executed repeatedly until the
condition becomes false. Once the condition becomes false then the execution
comes out of that loop.
SEQUENTIAL STATEMENTS IN PYTHON:
As stated above the sequential statements are executed line by line.
Example: Sequential statements (demo1.py)

print("one")

40
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
print("two")
print("three")
Output:

CONDITIONAL STATEMENTS IN PYTHON


Conditional statements are also called decision-making statements. Let’s
discuss some conditions making statements in detail. There are three types of
conditional statements in python. They are as follows:
1. if statement
2. if-else statement
3. if elif else
if statement in python:

The if statement contains an expression/condition. As per the syntax colon (:) is


mandatory otherwise it throws a syntax error. The condition gives the result as
a bool type, either True or False. If the condition result is True, then if block
statements will be executed. If the condition result is False, then if block
statements won‟t execute.
Example: if statement (demo2.py)

num = 1
print("num==1 condition gives: ", (num==1))
if num == 1:
print("if block statements executed")
Output:

Example: if statement (demo3.py)

num = 1
print("num==2 condition gives: ", (num==1))
if num == 2:
print("if block statements executed")
print("out of if block statements")

41
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Output:

The statements that should be executed if the condition is true, should have
one level indentation with respect to the if clause. In the demo2.py the
condition ‘num == 1’ is evaluated to True, hence the print function inside the if
the condition is executed. In the demo3.py the condition ‘num == 2’ is evaluated
to False, hence the print function outside the if the condition is executed.
if-else statement in python:

The if statement contains an expression/condition. As per the syntax colon (:) is


mandatory after the condition and after the else otherwise it throws a syntax
error. The condition gives the result as bool type, which means either True or
False. If the condition result is True, then if block statements will be executed.
If the condition result is False, then else block statements will be executed.
Example: if-else statement (demo4.py)

num = 1
print("num==1 condition gives: ", (num==1))
if num == 1:
print("if block statements executed")
else:
print("else block statements executed")
Output:

Example: if-else statement (demo5.py)

num = 1
print("num==2 condition gives: ", (num==1))
if num == 2:
print("if block statements executed")
else:
print("else block statements executed")

42
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Output:

The if block statements and else block statements should have one level
indentation. (highlighted with blue color). In the demo4.py the condition ‘num
== 1’ is evaluated to True, hence the print function inside the if the condition is
executed. In the demo5.py the condition ‘num == 2’ is evaluated to False, hence
the print function inside the else is executed.
if elif else statement in python:

The if statement contains an expression/condition. As per the syntax colon (:) is


mandatory after each condition and after the else otherwise it throws a syntax
error. The condition gives the result as bool type, which means either True or
False. The conditions are evaluated in the order written. If one condition
becomes True then the set of statements associated with that particular
condition are executed and the execution comes out without checking other
conditions.
Example: if elif statement (demo6.py)

print("Please enter the values from 0 to 4")


x=int(input("Enter a number: "))
if x==0:
print("You entered:", x)
elif x==1:
print("You entered:", x)
elif x==2:
print("You entered:", x)
elif x==3:
print("You entered:", x)
elif x==4:
print("You entered:", x)
else:
print("Beyond the range than specified")

43
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Output1:

Output2:

Example: Checking number is positive or negative using if-else statement


(demo7.py)

x=int(input("Enter a number: "))


if x<0:
print("The number is negative number")
else:
print("The number is positive number")
Output1:

Output2:

Example: Validating the name entered with the username we have (demo8.py)

user_name = 'rahul'
x=input("Enter a name: ")
if user_name == x:
print("The name is valid")
else:
print("The name is invalid")
Output1:

Output2:

Example: Finding the biggest number among entered two numbers (demo9.py)

x=int(input("Enter First Number: "))


y=int(input("Enter Second Number: "))
if x>y :
44
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
print("Biggest Number is: ", x)
else :
print("Biggest Number is: ", y)
Output:

Example: Finding the biggest number among entered three numbers


(demo10.py)

x=int(input("Enter First Number: "))


y=int(input("Enter Second Number: "))
z=int(input("Enter Third Number: "))
if x>y and x>z:
print("Biggest Number is: ", x)
elif y>z :
print("Biggest Number is: ", y)
else:
print("Biggest Number is: ", z)
Output:

Looping Statements in Python


LOOPING (Iterations) Statement in Python
If we want to execute a group of statements multiple times, then we should go
for a looping kind of execution. There are two types of loops available in python.
They are:
1. while loop
2. for loop
While loop in Python:

45
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
The while loop contains an expression/condition. As per the syntax colon (:) is
mandatory otherwise it throws a syntax error. The condition gives the result as
bool type, either True or False. The loop keeps on executing the statements
until the condition becomes False.
Flowchart for the while loop:

Parts of while loop in Python:


Initialization: This is the first part of the while loop. Before entering the
condition section, some initialization is required
Condition: Once the initializations are done, then it will go for condition
checking which is the heart of the while loop. The condition is checked and if it
returns True, then execution enters the loop for executing the statements
inside.
After executing the statements, the execution goes to the increment/decrement
section to increment the iterator. Mostly, the condition will be based on this
iterator value, which keeps on changing for each iteration. This completes the
first iteration. In the second iteration, if the condition is False, then the
execution comes out of the loop else it will proceed as explained in the above
point.
Increment/Decrement section: This is the section where the iterator is
increased or decreased. Generally, we use arithmetic operators in the loop for
this section
Let us understand it better with an example
Example: Printing numbers from 1 to 5 by using while loop (demo11.py)
x=1
while x<=5:
print(x)
x+=1
46
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
print("End")
Output:

In the demo11.py
1. The program is to print the number from 1 to 5
2. Before starting the loop, we have made some assignments( x = 1). This is
called the Initialization section.
3. After initialization, we started the while loop with a condition x<=5. This
condition returns True until x is less than 5.
4. Inside the loop, we are printing the value of x.
5. After printing the x value, we are incrementing it using the operator
x+=1. This is called the increment/decrement section.
6. For each iteration, the value of x will increase and when the x value
reaches 6, then the condition x<=5 returns False. At this iteration, the
execution comes out of the loop without executing the statements inside.
Hence in the output ‘6’ is not printed.
Example: Printing even numbers from 10 to 20 by using while loop (demo12.py)

x=10
while (x>=10) and (x<=20):
print(x)
x+=2
print("End")
Output:

for loop in python:


Basically, a for loop is used to iterate elements one by one from sequences like
string, list, tuple, etc. This loop can be easily understood when compared to the
while loop. While iterating elements from the sequence we can perform
operations on every element.

47
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Example: Printing elements of a list (demo13.py)

x = [10, 20, 30, "Python"]


for i in x:
print(i)
Output:

Example: Printing characters from a string (demo14.py)

x= "python"
for ch in x:
print(ch)
Output:

Example: Printing every item cost by adding gst (demo15.py)

items_costs = [10, 20, 30,]


gst = 2
for x in items_costs:
print(x+gst)
Output:

Example: Printing elements by using range() function and for loop (demo16.py)

for x in range(1, 5):


print(x)
Output:

48
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Example: Printing the sum of elements in a list (demo17.py)

item_costs = [10, 20, 30]


sum=0
for x in item_costs:
sum=sum + x
print(sum)
Output: 60
INFINITE LOOPS in PYTHON
The loop which never ends or the loop whose condition never gets False is
called an infinite loop. This loop never exits. In order to come out of the loop, we
need to manually do it by command ctrl+c.
Example: Infinite loop (demo18.py)

while True:
print("Hello")
Output:

NESTED LOOPS IN PYTHON


If a loop is written inside another loop then it is called a nested loop. Let’s
understand it with an example.
Example: Nested Loops (demo19.py)

rows = range(1, 5)
for x in rows:
for star in range(1, x+1):
print('* ', end=' ')
print()
Output:

49
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
LOOPS with ELSE block in Python:
In python, loops can also have an else block. These else blocks will get executed
irrespective of the loop i.e even if the loop got executed(demo20.py) or
not(demo21.py).

Example: Loops with else block (demo20.py)

values = range(5)
for x in values:
print("item is available")
else:
print("sorry boss, item is not available")
Output:

Example: Loops with else block (demo21.py)

values = range(5)
for x in values:
print("item is available")
else:
print("sorry boss, item is not available")
Output:

Note: These loops with else blocks are best suitable in the scenarios, where we
need to search an element in the list. When the element is not present in the
list then the else part will be executed saying no such element in the list.
Example: Element search in the list (demo22.py)

group = [1, 2, 3, 4]
50
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
search = int(input("Enter the element in search: "))
for element in group:
if search == element:
print("element found in group")
break
else:
print("Element not found")
Output1:

Output2:

BREAK statement in Python


The break statement when encountered will terminate the loop and bring the
execution out of the loop. Let’s consider the demo22.py, where we are searching
for an element in the list. There are four elements in the list and we are
searching for element 2. Our search element and the list element get matched
in the second iteration itself. It’s unnecessary to execute the loop for the other
two remaining iterations. So, we placed a break statement immediately when
the condition is matched in order to skip the remaining iterations.
CONTINUE statement in Python
The continue statement when encountered will skip the current iteration and
the loop proceeds for the next iteration without executing the statements, which
are followed by after the continue statement.
Example: Printing the items which are below 500 (demo23.py)

cart=[10, 20, 500, 700, 50, 60]


for item in cart:
if item>=500:
continue
print("Item: ",item)
Output:

PASS statement in Python:


The pass statement is used when you have to include some statement
syntactically but don’t want to perform any operation.

51
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Example: Pass statement (demo24.py)

num = [10, 20, 30,400, 500, 600]


for i in num:
if i<100:
print("pass statement executed")
pass
else:
print("Give festival coupon for these guys who bought: ",i)
Output:

RETURN statement in Python:


The return statement is one that returns something. This statement is used
with functions. We shall deal with this in detail in the functions chapter. For
now, just understand that it is one of the statements with which flow can be
controlled.

Strings in Python
Reminder
We already learn the first hello world program in python. In that program, we
just print a group of characters by using the print() function. Those groups of
characters are called as a string.
Program to print string (Demo1.py)
print(“Welcome to python programming”)
Output: Welcome to python programming
What is a string in Python?
A group of characters enclosed within single or double or triple quotes is called
a string. We can say the string is a sequential collection of characters.

Program to print employee information (Demo2.py)

name = "Balayya"
emp_id = 20
52
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
print("Name of the employee: ", name)
print("employee id is :", emp_id)
Output:

Note: Generally, to create a string mostly used syntax is double quotes syntax.
When triple single and triple-double quotes are used?
If you want to create multiple lines of string, then triple single or triple-double
quotes are the best to use.
Program to print multi-line employee information (Demo3.py)

loc1 = """XYZ company


While Field
Bangalore"""
loc2 = """XYZ company
Banglore
Human tech park"""
print(loc1)
print(loc2)
Output:

Note: Inside string, we can use single and double quotes


Program to use single and double quotes inside a string (Demo4.py)

s1 = "Welcome to 'python' learning"


s2 = 'Welcome to "python" learning'
s3 = """Welcome to 'python' learning"""
print(s1)
print(s2)
print(s3)

53
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Output:

The Empty string in Python:


If a string has no characters in it then it is called an empty string.
Program to print an empty string (Demo5.py)

s1 = ""
print(s1)
Output:
Accessing string characters in python:
We can access string characters in python by using,
1. Indexing
2. Slicing
Indexing:
Indexing means a position of string’s characters where it stores. We need to use
square brackets [] to access the string index. String indexing result is string
type. String indices should be integer otherwise we will get an error. We can
access the index within the index range otherwise we will get an error.
Python supports two types of indexing
1. Positive indexing: The position of string characters can be a positive
index from left to right direction (we can say forward direction). In this
way, the starting position is 0 (zero).
2. Negative indexing: The position of string characters can be negative indexes
from right to left direction (we can say backward direction). In this way, the
starting position is -1 (minus one).
Diagram representation

Note: If we are trying to access characters of a string without of range index,


then we will get an error as IndexError.
Example: Accessing a string with index in Python (Demo6.py)

wish = "Hello World"


print(wish[0])
print(wish[1])

54
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Output:

Example: Accessing a string with float index in Python (Demo7.py)

wish = "Hello World"


print(wish[1.3])
Output:

Example: Accessing a string without of bound index (Demo8.py)

wish = "Hello World"


print(wish[100])
Output:

Example: Accessing a string with a negative index (Demo9.py)

wish = "Hello World"


print(wish[-1])
print(wish[-2])
Output:

Example: Printing character by character using for loop


(Demo10.py)

name ="Python"
for a in name:
print(a)
Output:

What is Slicing in Python?


A substring of a string is called a slice. A slice can represent a part of a string
from a string or a piece of string. The string slicing result is string type. We
need to use square brackets [] in slicing. In slicing, we will not get any Index
out-of-range exception. In slicing indices should be integer or None or __index__
method otherwise we will get errors.
55
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Syntax:

Example:

Different Cases:
wish = “Hello World”
1. wish [::] => accessing from 0th to last
2. wish [:] => accessing from 0th to last
3. wish [0:9:1] => accessing string from 0th to 8th means (9-1) element.
4. wish [0:9:2] => accessing string from 0th to 8th means (9-1) element.
5. wish [2:4:1] => accessing from 2nd to 3rd characters.
6. wish [:: 2] => accessing entire in steps of 2
7. wish [2 ::] => accessing from str[2] to ending
8. wish [:4:] => accessing from 0th to 3 in steps of 1
9. wish [-4: -1] => access -4 to -1
Note: If you are not specifying the beginning index, then it will consider the
beginning of the string. If you are not specifying the end index, then it will
consider the end of the string. The default value for step is 1
Example: Slicing operator using several use cases (Demo11.py)

wish = "Hello World"


print(wish[::])
print(wish[:])
print(wish[0:9:1])
print(wish[0:9:2])
print(wish[2:4:1])
print(wish[::2])
print(wish[2::])
print(wish[:4:])
print(wish[-4:-1])
56
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Output:

What is Immutable in Python?


Once we create an object then the state of the existing object cannot be
changed or modified. This behavior is called immutability. Once we create an
object then the state of the existing object can be changed or modified. This
behavior is called mutability.
Strings are immutable in Python:
A string having immutable nature. Once we create a string object then we
cannot change or modify the existing object.
Example: Immutable (Demo12.py)

name = "Balayya"
print(name)
print(name[0])
name[0]="X"
Output: TypeError: ‘str’ object does not support item assignment
Mathematical operators on string objects in Python
We can perform two mathematical operators on a string. Those operators are:
1. Addition (+) operator.
2. Multiplication (*) operator.
Addition operator on strings in Python:
The + operator works like concatenation or joins the strings. While using the +
operator on the string then compulsory both arguments should be string type,
otherwise, we will get an error.
Example: Concatenation (Demo13.py)

a = "Python"
b = "Programming"
print(a+b)
Output: Python Programming
Example: Concatenation (Demo14.py)

a = "Python"
b=4
print(a+b)
57
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Output:

Multiplication operator on Strings in Python:


This is used for string repetition. While using the * operator on the string then
the compulsory one argument should be a string and other arguments should
be int type.
Example: Multiplication (Demo15.py)

a = "Python"
b=3
print(a*b)
Output: PythonPythonPython
Example: Multiplication (Demo16.py)

a = "Python"
b = "3"
print(a*b)
Output:

How to Find the Length of a string in Python?


We can find the length of the string by using the len() function. By using the
len() function we can find groups of characters present in a string. The len()
function returns int as result.
Example: len Function (Demo17.py)

course = "Python"
print("Length of string is:",len(course))
Output: Length of string is: 6
Membership Operators in Python:
We can check, if a string or character is a member/substring of string or not by
using the below operators:
1. In
2. not in
in operator
in operator returns True, if the string or character found in the main string.
Example: in operator (Demo18.py)

print('p' in 'python')
print('z' in 'python')
print('on' in 'python')
print('pa' in 'python')
58
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Output:

Example: To find substring in the main string (Demo19.py)

main=input("Enter main string:")


s=input("Enter substring:")
if s in main:
print(s, "is found in main string")
else:
print(s, "is not found in main string")
Output1:

Output2:

Not in Operator in Python


The not-in operator returns the opposite result of in operator. not in operator
returns True, if the string or character is not found in the main string.
Example: not in operator (Demo20.py)
print(‘b’ not in ‘apple’)
Output: True
Comparing strings in Python:
We can use the relational operators like >, >=, <, <=, ==, != to compare two
string objects. While comparing it returns boolean values, either True or False.
The comparison will be done based on alphabetical order or dictionary order.
Example: Comparison operators on the string in Python (Demo21.py)

s1 = "abcd"
s2 = "abcdefg"
print(s1 == s2)
if(s1 == s2):
print("Both are same")
else:
print("not same")

59
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Output:

Example: User name validation (Demo22.py)

user_name ="rahul"
name = input("Please enter user name:")
if user_name == name:
print("Welcome to gmail: ", name)
else:
print("Invalid user name, please try again")
Output:

How to remove spaces from a string in Python?


Space is also considered as a character inside a string. Sometimes unnecessary
spaces in a string will lead to wrong results.
Example: To check space importance in the string at the end of the string
(Demo23.py)

s1 = "abcd"
s2 = "abcd "
print(s1 == s2)
if(s1 == s2):
print("Both are same")
else:
print("not same")
Output:

Predefined methods to remove spaces in Python


1. rstrip() -> remove spaces at right side of string
2. lstrip() -> remove spaces at left side of string
3. strip() -> remove spaces at left & right sides of string
Note: These methods won’t remove the spaces which are in the middle of the
string.
Example: To remove spaces in the star and end of the string in
python (Demo24.py)

course = "Python "


60
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
print("with spaces course length is: ",len(course))
x=course.strip()
print("after removing spaces, course length is: ",len(x))
Output:

How to Find substrings in a string in python?


We can find a substring in two directions like forwarding and backward
direction. We can use the following 4 methods:
For forwarding direction
1. find()
2. index()
For backward direction
1. rfind()
2. rindex()
find() method:
Syntax– nameofthestring.find(substring)
This method returns an index of the first occurrence of the given substring, if it
is not available, then we will get a -1(minus one) value. By default find() method
can search the total string of the object. You can also specify the boundaries
while searching.
Syntax – nameofthestring.find(substring, begin, end)
It will always search from beginning index to end-1 index.
Example: finding substring by using find method in python
(Demo25.py)

course="Python programming language"


print(course.find("p"))
print(course.find("a", 1, 20))
Output:

index() method in Python:


index() method is exactly the same as the find() method except that if the
specified substring is not available then we will get ValueError. So, we can
handle this error at the application level
Example: finding substring by using index method (Demo26.py)

s="Python programming language"


print(s.index("Python"))
Output: 0
61
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Example: finding substring by using index method (Demo27.py)

s="Python programming language"


print(s.index("Hello"))
Output:

Example: Handling the error (Demo28.py)

s="Python programming language"


try:
print(s.index("Hello"))
except ValueError:
print("not found")
Output: not found
How to Count substring in a given String in Python?
By using the count() method we can find the number of occurrences of
substring present in the string
Syntax – nameofthestring.count(substring)
Example: count() (Demo29.py)

s="Python programming language, Python is easy"


print(s.count("Python"))
print(s.count("Hello"))
Output:

How to replace a string with another string in Python?


We can replace the old string with a new string by using replace() method. As
we know string is immutable, so replace() method never performs changes on
the existing string object. The replace() method creates a new string object, we
can check this by using the id() method.
Syntax- nameofthestring.replace(old string, new string)
Example: replace a string with another string (Demo30.py)

s1="Java programming language"


s2=s1.replace("Java", "Python")
print(s1)
print(s2)
print(id(s1))
print(id(s2))

62
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Output:

Does replace() method modify the string objects in python?


A big NO. The string is immutable. Once we create a string object, we cannot
change or modify the existing string object. This behavior is called immutability.
If you are trying to change or modify the existing string object, then with those
changes a new string object will be created. So, replace the () method will create
a new string object with the modifications.
How to Split a string in Python?
We can split the given string according to the specified separator by using the
split() method. The default separator is space. split() method returns list.
Syntax- nameofthestring=s.split(separator)
Example: Splitting a string in Python (Demo31.py)

message="Python programming language"


n=message.split()
print("Before splitting: ",message)
print("After splitting: ",n)
print(type(n))
for x in n:
print(x)
Output:

Example: Splitting a string based on separator in python (Demo32.py)

message="Python programming language,Python is easy"


n=message.split(",")
print(n)
Output:

How to Join strings in Python?


We can join a group of strings (list or tuple) with respect to the given separator.
Syntax: s=separator.join(group of strings)

63
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Example: separator is – symbol joining string by using join() method
(Demo33.py)

profile = ['Roshan', 'Actor', 'India']


candidate = '-'.join(profile)
print(profile)
print(candidate)
Output:

Example: separator is : symbol joining string by using join() method


(Demo34.py)

profile = ['Roshan', 'Actor', 'India']


candidate = ':'.join(profile)
print(profile)
print(candidate)
Output:

How to change cases of string in Python?


1. upper() – This method converts all characters into upper case
2. lower() – This method converts all characters into lower case
3. swapcase() – This method converts all lower-case characters to
uppercase and all upper-case characters to lowercase
4. title() – This method converts all character to title case (The first
character in every word will be in upper case and all remaining
characters will be in lower case)
5. capitalize() – Only the first character will be converted to upper case and
all remaining characters can be converted to lowercase.
Example: Changing cases (Demo35.py)

message='Python programming language'


print(message.upper())
print(message.lower())
print(message.swapcase())
print(message.title())
print(message.capitalize())

64
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Output:

How to Formatting the Strings in Python?


We can format the strings with variable values by using replacement operator {}
and format() method.
Example: Formatting strings (Demo36.py)

name='Rakesh'
salary=100
age=16
print("{} 's salary is {} and his age is {}".format(name, salary, age))
print("{0} 's salary is {1} and his age is {2}".format(name, salary, age))
print("{x} 's salary is {y} and his age is{z}".format(z=age,y=salary,x=name))
Output:

Character Data Type in Python:


If a single character stands alone then we can say that is a single character. For
example: M -> Male F -> Female. In other programming languages, char data
type represents the character type, but in python, there is no specific data type
to represent characters. We can fulfill this requirement by taking a single
character in single quotes. A single character also represents a string type in
python.
Example: Character data type (Demo37.py)

gender1 = "M"
gender2 = "F"
print(gender1)
print(gender2)
print(type(gender1))
print(type(gender2))
Output:

65
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Python – Functions, Modules & Packages
Functions in Python
General example why the function is required?
Let us understand this with an example. When you go for walk in the early
morning, the things you do are
1. Get up from the bed
2. fresh up
3. Tie the shoe
4. Pick the smooth towel
5. Start the walk.
Think of this sequence of steps to do a morning walk. Now when my dad calls
for a morning walk, he doesn’t need to explain all these steps each time to me.
Whenever dad says, “Get ready for morning walk”, it’s like making a function
call. “Morning walk‟ is an abstraction for all the many steps involved.
When should we go for function in python?
While writing coding logic, instead of writing like plain text, it’s good to keep
those coding statements in one separate block, because whenever required then
we can call these. If a group of statements is repeatedly required, then it is not
recommended to write these statements each and every time separately.
So, it’s good to define these statements in a separate block. After defining a
function we can call directly if required. This block of statements is called a
function. Let us understand more by doing practically.
WHAT IS A FUNCTION?
A function is one that contains a group of statements or a block of code to
perform a certain task. The advantages of using functions are:
1. Maintaining the code is an easy way.
2. Code re-usability.
Example: print() is a predefined function in python that prints output on the
console
Types of functions in python:
There are many categories based on which we can categorize the functions. This
categorization is based on who created it.
1. Pre-defined or built-in functions
2. User-defined functions
Predefined or built-in functions: The functions which come installed along
with python software are called predefined or built-in functions. We have
covered some inbuilt functions in examples of earlier chapters. Some of them
are id(), type(), input(), print() etc.
User-defined functions: The functions which are defined by the developer as
per the requirement are called user-defined functions. In this chapter, we shall
concentrate on these kinds of functions that are user-defined.

66
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
FUNCTION RELATED TERMINOLOGY
1. def’ keyword – Every function in python should start with the keyword
‘def’. In other words, python can understand the code as part of a
function if it contains the ‘def’ keyword only.
2. Name of the function – Every function should be given a name, which
can later be used to call it.
3. Parenthesis – After the name ‘()’ parentheses are required
4. Parameters – The parameters, if any, should be included within the
parenthesis.
5. Colon symbol ‘:’ should be mandatorily placed immediately after closing
the parentheses.
6. Body – All the code that does some operation should go into the body of
the function. The body of the function should have an indentation of one
level with respect to the line containing the ‘def’ keyword.
7. Return statement – Return statement should be in the body of the
function. It’s not mandatory to have a return statement.
Note: After defining a function we can call the function using its name. While
calling a function, we need to pass the parameters if it has any as stated in
point 4 above.
How to Create and call a function in Python?
From creating a function to using it, these are the two things that are done.
1. Defining function
2. Calling function
Defining a function
In the function-related terminologies above, it was clearly explained what is
what and how are they used. All the points together define the function. To
summarize the definition contains – def keyword, name for the function,
parentheses, parameters(optional), colon (:), body, return(optional).
Syntax to define a function in Python:

Example: Define a function that has no parameters (Demo1.py)

def display():
print("welcome to function")
Output: No Output
Calling a function in Python:
In the above demo1.py example we defined a function with the name ‘display’
with a print statement in it. But when we execute the demo1.py it will not
display any output because the function is not called. Hence, function calling is
also important along with function definition.

67
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
After defining a function, we need to call to execute the function. While calling
the function, we have to call with the same name of the function which we used
while defining it, otherwise we will get an error.
Example: Define a function and call it (Demo2.py)

def display():
print("welcome to function")
display()
display()
display()
Output:

Note: When a function is called once then it will execute once, if called twice
then it will be executed twice, and so on.
Example: Define a function and call it with a different name (Demo3.py)

def one():
print("welcome to function")
two()
Output: NameError: name ‘two’ is not defined
Function with Parameters in Python:
Based on the parameters, functions can be categorized into two types. They are:
1. Function without parameters
2. Function with parameters
Function without Parameters in Python:
A function that has no parameters in the function definition is called a function without
parameters. The syntax is given below.

Example: Function performing addition operation (Demo5.py)

# defining a function
def sum(a, b):
print("Sum of two values=", (a+b))
# calling function
sum(20,30)
Output: Sum of two values= 50

68
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Example: Check a number is even or odd by using a function (Demo6.py)

def checking(num):
if num % 2 == 0:
print(num," is even")
else:
print(num," is odd")
checking(12)
checking(31)
Output:

RETURN KEYWORD IN PYTHON:


As mentioned above, the return statement is included in the function body, and it returns
some results after doing the operations. Some point about the return statement
1. return is a keyword in the python programming language.
2. By using return, we can return the result.
3. It is not mandatory for a function to have a return statement.
4. If there is no return statement in the function body then the function, by default,
returns None
Syntax to use Return Keyword in Python:

Example: function returning the value (Demo7.py)

def sum(a, b):


c=a+b
return c
x=sum(1, 2)
print("Sum of two numbers is: ",x)
Output: Sum of two numbers is: 3
Example: function returning the value (Demo8.py)

def m1():
print("This function is returning nothing")
# function calling
m1()
x=m1()

69
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
print(x)
Output:

How to Return multiple values from a function in Python?


In python, a function can return multiple values. If a function is returning multiple values
then the same should be handled at the function calling statement as shown in the
demo9.py. x and y, two variables are used to capture the values returned by the function
m1.
Example: Define a function that can return multiple values (Demo9.py)

def m1(a, b):


c = a+b
d = a-b
return c, d
#calling function
x, y = m1(10, 5)
print("sum of a and b: ", x)
print("subtraction of a and b: ", y)
Output:

The function can call another function in Python:


It is also possible in python that a function can call another function. The syntax to call a
function from another function is given below.

Example: One function can call another function in python (Demo10.py)

def m1():
print("first function information")
def m2():
print("second function information")
m1()
m2()

70
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Output:

In demo10.py, we defined two functions m1 and m2. In function m2, we are calling the
m1 function. So finally, we are calling only the m2 function which internally calls the m1
function.
FUNCTIONS ARE FIRST CLASS OBJECTS
All functions in Python are first-class functions. To say that functions are first-class in a
certain programming language means that they can be passed around and manipulated
in the same way as to how you would pass around and manipulate other kinds of objects
(like integers or strings). You can assign a function to a variable, pass it as an argument
to another function, etc. The distinction is not that individual functions can be first-class
or not, but that entire language may treat functions as first-class objects, or may not.
Functions are considered as first-class objects. In python, below things are possible to
1. Assign a function to variables (demo11.py)
2. Pass function as a parameter to another function (demo12.py)
3. Define one function inside another function (demo13.py)
4. The function can return another function (demo14.py)
Assigning a function to a variable in Python:
Example: Assign a function to a variable (Demo11.py)
def add():
print("We assigned function to variable")
#Assign function to variable
sum=add
#calling function
sum()
Output: We assigned function to a variable
Pass function as a parameter to another function in Python
Example: Pass function as a parameter to another function (Demo12.py)
def display(x):
print("This is display function")
def message():
print("This is message function")
# calling function
display(message())
Output:

Define one function inside another function in Python:


Example: function inside another function (Demo13.py)
71
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
def first():
print("This is outer function")
def second():
print("this is inner function")
second()
#calling outer function
first()
Output:

Note: If we defined the inner function, then we need to call that inner function in the
outer function.
The function can return another function in Python:
Example: function can return another function (Demo14.py)
ef first():
def second():
print("This function is return type to outer function")
return second
x=first()
x()
Output: This function is return type to outer function

Types of Function Arguments in Python


TYPES OF ARGUMENTS IN PYTHON FUNCTIONS
Argument: An argument is a variable (which contains data) or a parameter that
is sent to the function as input. Before getting into argument types, let’s get
familiar with words formal and actual arguments.
1. Formal arguments: When a function is defined it (may) has (have) some
parameters within the parentheses. These parameters, which receive the
values sent from the function call, are called formal arguments.
2. Actual arguments: The parameters which we use in the function call or the
parameters which we use to send the values/data during the function call
are called actual arguments.
Example: formal and actual function arguments in python (Demo15.py)

def sum(a, b):


c = a + b # a and b are formal arguments
print(c)
72
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
# call the function
x = 10
y = 15
sum(x, y) # x and y are actual arguments
Output: 25
Types of Arguments in Pythons:
In python, depending on the way or format we send the arguments to the
function, the arguments can be classified into four types:
1. Positional arguments
2. Keyword arguments
3. Default arguments
4. Variable-length arguments
5. keyword variable-length argument
Positional Arguments in Python:
If there are three arguments (formal arguments) in the function definition, then
you need to send three arguments(actual arguments) while calling the function.
The actual arguments will be received by the formal arguments in the same
order as in the function call. Let’s understand this through an example.
In demo16.py the actual arguments 10, 20 will be received in the same order
sent i.e 10 will go into variable ‘x’, and 20 will go into the variable ‘y’. If we send
the arguments as 20,10 then 20 will go into x and 10 will go into y. The number
of arguments and position of arguments should be matched, otherwise, we will
get errors as shown in demo17.py
Example: Positional arguments (Demo16.py)

def sub(x, y):


print(x-y)
# calling function
sub(10, 20)
Output: -10
Example: Positional arguments (Demo17.py)

def sub(x, y):


print(x-y)
# calling function
sub(10, 20,30)
Output: TypeError: sub() takes 2 positional arguments but 3 were given
Keyword Arguments in Python:
In the function call, if we send the values using keys then they are called
keyword arguments. Here, keys are nothing but the names of the variables. In a
way, we can say that keyword arguments are arguments that recognize the
parameters by the name of the parameters. Let’s understand it by the example
73
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
demo18.py where the name of the function is cart() and parameters are item
and price can be written as:
def cart(item, price):
At the time of calling this function, we must pass two values and we can write
which value is for what by using the name of the parameter, for example,
cart(item=”bangles”, price=20000)
cart(item=”handbag”, price=100000)
item and price are called keywords in this scenario. Here we can change the
order of arguments.
Example: Keyword arguments (Demo18.py)

def cart(item, price):


print(item, "cost is :" ,price)
cart(item="bangles", price=20000)
cart(item="handbag", price=100000)
cart(price=1200, item="shirt")
Output:

Example: Keyword arguments (Demo19.py)

def details(id, name):


print("Emp id is: ",id)
print("Emp name is: ",name)
# calling function
details(id=1, name="Balayya Babu")
details(id=2, name="Chiru")
Output:

Note: We can use both positional and keyword arguments simultaneously. But
first, we must take positional arguments and then keyword arguments,
otherwise, we will get syntax errors as shown in demo21.py
Example: Positional and keyword arguments in Python (Demo20.py)

def details(id, name):


print("Emp id is: ",id)
print("Emp name is: ",name)
# calling function
details(1, name="Anushka")
74
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Output:

Example: Positional and keyword arguments in Python (Demo21.py)

def details(id, name):


print("Emp id is: ",id)
print("Emp name is: ",name)
# calling function
details(name="Anushka",1)
Output: SyntaxError: non-keyword arg after keyword arg
Default Arguments in Python Function with Examples:
In the function definition, while declaring parameters, we can assign some
value to the parameters, which are called default values. Such default values
will be considered when the function call does not send any data to the
parameter. Let’s take the function from demo18.py as an example. There, the
function cart has parameters as items and price. Let’s say the price of many
items is 20 rupees. In this case, we can set the price param to the default value
of 20 rupees
def cart(items, price=20):
In the above example items have no default value, so we should provide. price
has a default value of 20. Still, if we provide the value at the time of calling then
default values will be overridden with passed value.
Example: Default Arguments in Python (Demo22.py)

def cart(item, price=20):


print(item, "cost is :" ,price)
cart(item="pen")
cart(item="handbag", price=10000)
cart(price=500, item="shirt")
Output:

Note: If we are not passing any value, then only the default value will be
considered. While defining a function, after default arguments we should not
take non-default arguments.
Example: Default arguments (Demo23.py)

def cart(item=1, price):


print(item, "cost is :" ,price)
cart(item="pen")
cart(item="handbag", price=10000)
75
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
cart(price=500, item="shirt")
Output: SyntaxError: non-default argument follows default argument
Variable Length Arguments in Python Function:
Sometimes, the programmer does not know how many values need to pass to
function. In that case, the programmer cannot decide how many arguments to
be given in the function definition. Therefore, we use variable-length arguments
to accept n number of arguments.
The variable-length argument is an argument that can accept any number of
values. The variable-length argument is written with a ‘*’ (one star) before the
variable in the function definition.
Syntax:

x is a formal argument, *y is a variable-length argument. Now we can pass any


number of values to this *y. Internally the provided values will be represented
in the tuple.
Example: Variable-length argument in python (Demo24.py)

def total_cost(x, *y):


sum=0
for i in y:
sum+=i
print(x + sum)
#calling function
total_cost(100, 200) #valid
total_cost(110, 226, 311) #valid
total_cost(11,) #valid
Output:

keyword variable-length argument (**variable) in Python:


Just as variable length arguments, there are keyword variable length
arguments that are n key-value pairs. The syntax is given below.

**x represents as keyword variable argument. Internally it represents a


dictionary object. A dictionary stores the data in the form of key-value pairs.

76
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Example: keyword variable length argument (**variable) in Python (Demo25.py)

def print_kwargs(**kwargs):
print(kwargs)
print_kwargs(id=1, name="Nireekshan", qualification="MCA")
Output:

Example: keyword variable-length argument (**variable) (Demo26.py)

def m1(**x):
for k, v in x.items():
print(k,"=",v)
m1(a=10, b=20, c=30)
m1(id=100, name="Subbalaxmi")
Output:

Function vs Module vs Library in Python:


1. A group of lines with some name is called a function
2. A group of functions saved to a file is called Module
3. A group of Modules is nothing but Library

Types of Variables in Python


Types of Variables in Python
The variables based on their scope can be classified into two types:
1. Local variables
2. Global variables
Local Variables in Python:
The variables which are declared inside of the function are called local
variables. Their scope is limited to the function i.e we can access local variables
within the function only. If we are trying to access local variables outside of the
function, then we will get an error.
Example: Local variables (Demo27.py)

def m():
a=11
print(a)
77
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
m()
Output: 11
Example: Local variables in Python (Demo28.py)

def m():
a=11
print(a)
def n():
print(a)
m()
n()
Output:

Global variables in Python:


The variables which are declared outside of the function are called global
variables. Global variables can be accessed in all functions of that module.
Example: Global variables in Python (Demo29.py)

a=11
b=12
def m():
print("a from function m(): ",a)
print("b from function m(): ",b)
def n():
print("a from function n(): ",a)
print("b from function n(): ",b)
m()
n()
Output:

78
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
GLOBAL KEYWORD IN PYTHON
The keyword global can be used for the following 2 purposes:
1. To declare a global variable inside a function
2. To make global variables available to the function.
When can we choose a global keyword?
There might be some scenarios, where the global variable names and local
variable names are the same. In such cases, within the function, by default, the
local variables are only referred and the global variables are ignored. If we want
our function to refer to the global variable rather than the local variable, we can
use the global keyword before the variable in the function as shown in
demo31.py
Example: Global and Local variables having the same name in Python
(Demo30.py)

a=1
def m1():
a=2
print("a value from m1() function: ", a)
def m2():
print("a value from m2() function:", a)
m1()
m2()
Output:

Note: If a programmer wants to use the global variable inside a function, then
need to use a global keyword before the variable in the beginning of the
function body.
Example: global and local variables having the same name in Python
(Demo31.py)

a=1
def m1():
global a
a=2
print("a value from m1() function: ", a)
def m2():
print("a value from m2() function:", a)
m1()
m2()

79
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Output:

If we use the global keyword inside the function, then the function is able to
read-only global variables.
PROBLEM: This would make the local variable no more available.
globals() built-in function in python:
The problem of local variables not available, due to the use of global keywords
can be overcome by using the Python built-in function called globals().
The globals() is a built-in function that returns a table of current global
variables in the form of a dictionary. Using this function, we can refer to the
global variable “a” as: global()[“a”].
Examle: Globals built-in function in python (Demo32.py)

a=1
def m():
a=2
print(a)
print(globals()["a"])
m()
Output:

Recursive and Lambda Functions in Python


Recursive Function in Python
A function is called recursive when it is called by itself. Let’s understand this
with an example. Let’s consider a function which calculates the factorial of a
number. It can be written as a recursive functions as explained below.

Example: Factorial using the recursive function in python (Demo33.py)

def factorial(n):
if n ==0:
result=1
else:
80
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
result = n * factorial(n-1)
return result
x= factorial(4)
print("Factorial of 4 is: ",x)
Output: Factorial of 4 is: 24
Example: Factorial without recursive function in python (Demo34.py)

def f1():
n=4
fact=1
while(n>0):
fact=fact*n
n=n-1
print("Factorial of the number is: ", fact)
f1()
Output: Factorial of the number is: 24
From the above two programs we can conclude that using recursive functions
brings in some advantages:
1. We can reduce the length of the code and improves readability
2. We can solve complex problems in a very easy way.
Lambda Function (Anonymous Functions) in Python
The name of the function is the mandatory item in the function definition as
discussed earlier. But, in python, we have a keyword called ‘lambda’ with which
we can define a simple function in a single line without actually naming it.
Such functions are called lambda functions.
Syntax: lambda argument_list: expression
Example: Lambda Function in Python (Demo35.py)

s = lambda a: a*a
x=s(4)
print(x)
Output: 16
Example: Lambda Function in Python (Demo36.py)

add = lambda a,b: a+b


x=add(4,5)
print(x)
Output: 9

81
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Points to Remember while working with Python Lambda Functions:
1. A lambda function can take any number of arguments but should have
only one expression.
2. It takes the parameters and does some operation on them and returns
the result, just the same as normal functions.
3. The biggest advantage of lambda functions is that a very concise code
can be written which improves the readability of the code.
4. This can be used for only simple functions but not for complex functions.
5. The lambda function, mostly, can be used in combination with other
functions such as map(), reduce(), filter() etc which we are going to
discuss now.
filter() function in Python:
This function is used to filter values from a sequence of values. The syntax is:
Syntax: filter(function, sequence)
The filter function will filter the elements in the sequence based on the
condition in the function. Let’s understand it through the example.
Example: Filter Function in python (Demo37.py)

items_cost = [999, 888, 1100, 1200, 1300, 777]


gt_thousand = filter(lambda x : x>1000, items_cost)
x=list(gt_thousand)
print("Eligible for discount: ",x)
Output:
In the above example, the filter applies the lambda function on all the elements
in the ‘items_cost’ and returns the elements which satisfy the lambda function.
map() function in Python:
This function is used to map a particular function onto the sequence of
elements. After applying, this returns a new set of values.
Syntax: map(function, sequence)
Example: Map Function in Python (Demo38.py)

without_gst_cost = [100, 200, 300, 400]


with_gst_cost = map(lambda x: x+10, without_gst_cost)
x=list(with_gst_cost)
print("Without GST items costs: ",without_gst_cost)
print("With GST items costs: ",x)
Output:

82
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
reduce() function in Python:
This function reduces the sequence of elements into a single element by
applying a specific condition or logic. To use the reduce function we need to
import the functools module.
Syntax: reduce(function, sequence)
Example: Reduce Function (Demo39.py)

from functools import reduce


each_items_costs = [111, 222, 333, 444]
total_cost = reduce(lambda x, y: x+y, each_items_costs)
print(total_cost)
Output: 1110

Decorators and Generators in Python


Decorators in Python with Examples:
We have already discussed nested functions and function as first class object
concepts already. Clear understanding of these concepts is important in
understanding decorators. A decorator is a special function which adds some
extra functionality to an existing function. The meaning of the statement can be
understood clearly by the end of this topic. For now let’s understand a
decorator as:
1. A decorator is a function that accepts a function as a parameter and
returns a function.
2. Decorators are useful to perform some additional processing required by
a function.
Steps to create decorator:
Step1: Decorator takes a function as an argument

Step2: Decorator body should have an inner function

Step3: Decorator should return a function

83
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Step4: The extra functionality which you want to add to a function can be
added in the body of the inner_function.
Let’s create a function which takes two arguments and prints the sum of them.
Example: Add Function (Demo40.py)

def add(a,b):
res = a + b
return res
print(add(20,30))
print(add(-10,5))
Output:

Now, I wish to add some extra functionality of adding the two numbers only if
they are positive. If any number is negative, then I wish to take it as 0 during
adding. For adding this extra functionality let create a decorator.
def decor(func): #Here ‘func’ is the the argument/parameter which
receives the function
def inner_function(x,y):
if x<0:
x=0
if y<0:
y=0
return func(x,y)
return inner_function #Decor returns the func passed to it.
We have created our decorator and now let’s use it with our add function from
demo40.py
add = decor(add)
With the above statement, we are passing the add function as parameter to the
decorator function, which is returning inner_function. Now, the inner_function
object or address will be overridden in the ‘add’ because we are capturing the
returned function in it. After this, whenever we call add, the execution goes to
inner_function in the decorator.
add(-10,20)
In inner_function, we are doing the extra logic for checking whether the
arguments are positive or not. If not positive we are assigning them with zero.
And we are passing the processed values to the original add function which was
sent to the decorator. Our final code will be
Example: Decorator Function in Python (Demo41.py)

def decor(func):
def inner_function(x,y):
if x<0:
84
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
x=0
if y<0:
y=0
return func(x,y)
return inner_function
def add(a,b):
res = a + b
return res
add = decor(add)
print(add(20,30))
print(add(-10,5))
Output:

@ symbol in python:
In the above example, in order to use the decorator, we have used the ‘add =
decor(add)’ line. Rather than using this we can just use the ‘@decor’ symbol on
top of the function for which we want to add this extra functionality. The
decorator once created can also be used for other functions as well.
Example: Subtract Function using decorator function in Python (Demo40.py)

def decor(func):
def inner_function(x,y):
if x<0:
x=0
if y<0:
y=0
return func(x,y)
return inner_function
@decor
def sub(a,b):
res = a - b
return res
print(sub(30,20))
print(sub(10,-5))

85
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Output:

Generators in Python with Examples:


Generators are just like functions which give us a sequence of values one as an
iterable (which can be iterated upon using loops). Generators contain yield
statements just as functions contain return statements.
Example: Generators in Python (Demo41.py)

def m():
yield 'Mahesh'
yield 'Suresh'
g = m()
print(g)
print(type(g))
for y in g:
print(y)
Output:

Example: Generators in Python (Demo42.py)

def m(x, y):


while x<=y:
yield x
x+=1
g = m(5, 10)
for y in g:
print(y)
Output:

next function in Python:


If we want to retrieve elements from a generator, we can use the next function
on the iterator returned by the generator. This is the other way of getting the
86
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
elements from the generator. (The first way is looping in through it as in the
examples above).
Example: Generators with next function in Python (Demo43.py)

def m():
yield 'Mahesh'
yield 'Suresh'
g = m()
print(type(g))
print(next(g))
print(next(g))
Output:

Modules and Packages in Python


What are Modules in Python?
In python a module means a saved python file. This file can contain a group of
classes, methods, functions and variables. Every file with .py or .python
extension is called a python file, in turn a module.
Example: Modules in Python (addmultiplication.py)

x = 10
def sum(a, b):
print("Sum of two values: " , (a+b))
def multiplication(a, b):
print("Multiplication of two values: " , (a*b))
Now addmultiplication.py file is a module. addmultiplication.py module
contains one variable and two functions.
What is import keyword in python?
If we want to use other members(variable, function, etc) of a module in your
program, then you should import that module by using the import keyword.
After importing you can access members by using the name of that module.
Example: demo1.py

import addmultiplication
print(addmultiplication.x)
addmultiplication.sum(1, 2)

87
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
addmultiplication.multiplication(2, 3)
Output:

Note: Whenever we are using a module in our program, that module’s compiled
file will be generated and stored in the hard disk permanently.
Renaming or Aliasing a module in Python:
The syntax for renaming or giving an alias name for the module

Example: Aliasing module in python (demo2.py)

import addmultiplication as calculator


print(calculator.x)
calculator.sum(1, 2)
calculator.multiplication(3, 4)
Output:

from keyword in python:


We can import some specific members of the module by using the from
keyword. The main advantage of the from keyword is we can access members
directly without using module names.
Example: from keyword in python (demo3.py)

from add
multiplication import x, sum
print(x)
sum(10,20)
Output:

Import * in python:
We can import all members of a module as by using import * (symbol).
Example: import * in python (demo4.py)

from addmultiplication import *


print(x)

88
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
sum(10,20)
multiplication(10,20)
Output:

Aliasing members in Python:


We can give alias name to the members of a module as well
Example: Aliasing members of a module in Python (demo5.py)

from addmultiplication import x as y, sum as add


print(y)
add(10,20)
Output:

Once an alias name is given, we should use the alias name only and not the
original name.
Example: Aliasing members of a module in Python (demo6.py)

from addmultiplication import x as y


print(x)

Output:
Reloading a module in Python:
By default, a module will be loaded only once even though we are importing
multiple times. Let’s consider a module with name module1.
Example: Reloading (module1.py)
print(“This is from module1”)
Output:
Example: Reloading in Python (demo7.py)

import module1
import module1
import module1
import module1
print("This is test module")
Output:

89
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
The problem in this approach is if a module is updated outside after loading it
in our program, then the updated version of the module will not be available to
our program. We can solve this problem by reloading modules explicitly based
on our requirement wherever needed. We can reload by using the reload()
function of the imp module.
Syntax:
import imp
imp.reload(module1)
Example: demo8.py

import module1
import module1
from imp import reload
reload(module1)
reload(module1)
reload(module1)
print("This is test module")
Output:

In the above program module1 will be loaded 4 times in that 1 time by default
and 3 times explicitly. The main advantage of explicit module reloading is we
can ensure that updated versions are always available to our program.
dir() function in Python:
We can find members of a module by using the dir() function. For every module
at the time of execution, the Python interpreter will add some special properties
automatically for internal use, for example
__name__
__package__
This inbuilt function dir() helps us to list out all members, including those
which are included by interpreter, of the current module or a specified module.
1. dir() ===> To list out all members of current module
2. dir(moduleName) ===> To list out all members of specified module
Example: dir() function in python (demo9.py)

x=10
y=20
def f1():
print("Hello")
print(dir())

90
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Output:

Example: To display members of the specific module in python (demo10.py)

import module1
import addmultiplication
print(dir(module1))
print(dir(addmultiplication))
Output:

What is a Package in Python?


A package is nothing but a folder or directory which represents a collection of
python modules(programs). Any folder or directory, for python to recognize as a
package, should contains__init__ .py file. __init__ .py can be an empty file. A
package can contain sub-packages also.
Diagrammatic representation of Package in Python:

Summary of Modules and Packages in Python


1. Library → A group of packages
2. Package → A group of modules
3. Modules → A group of functions or methods and classes.

91
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training

Python – Data Structure


Python Data Structures:
In python, there are quite a few data structures available. They are used to
store a group of individual objects as a single entity.
Sequences
Sequences are those, which contain a group of elements, whose purpose is to
store and process a group of elements. In python, strings, lists, tuples, and
dictionaries are very important sequence data types.
Lists in Python:
A list is a data structure that can store a group of elements or objects. It has
the following features/properties:
1. Lists can store the same type as well as different types of elements.
Hence, it is heterogeneous.
2. Lists have dynamic nature which means we don’t need to mention the
size of the list while declaring as we do for arrays in other programming
languages. The size will increase dynamically.
3. Insertion order is preserved. The order, in which the items are added to a
list, is the order in which output is displayed.
4. The list can store duplicates elements.
5. In lists, the index plays the main role. Using index we perform almost all
the operations on the items in it.
6. List objects are mutable which means we can modify or change the
content of the list even after the creation.
Creating a list in Python
There are a couple of ways to create a list in Python. Let’s see them with
examples.
Creating a list in Python by using square brackets ‘[]’
We can create a list in python by using square brackets ‘[]’. The elements in the
list should be comma-separated.
Example: Creating an empty list (demo1.py)

l1 = []
print(l1)
print(type(l1))
Output:

Example: Creating a list with elements (demo2.py)


names = ["Mohan", "Prasad", "Ramesh", "Mohan", 10, 20, True, None]

92
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
print(names)

Output:
You can observe from the output that the order is preserved and also duplicate
items are allowed. It can contain mixed data types (strings, integers, boolean,
None) elements.
Creating a list in Python by using the list() function
You can create a list by using the list() function in python. Generally, we use
this function for creating lists from other data types like range, tuple, etc. This
is generally referred to as type conversion
Example: Creating a list using list() function (demo3.py)

r=range(0, 10)
l=list(r)
print(l)

Output:
Difference between list() function and list class in python:
list() is a predefined function in python. list() function is used to convert other
sequences or data types into list data types. The list is a predefined class in
python. Once we create a list then it is internally represented as a list class
object type. We can check this by using a type function.
Example: Creating a list using list() function (demo3.py)

r=range(0, 10)
l=list(r)
print(l)
print(type(l))
Output:

Example: Mutability (demo4.py)

l = [1, 2, 3, 4, 5]
print(l)
print("Before modifying l[0] : ",l[0])
l[0]=20
print("After modifying l[0] : ",l[0])
print(l)

93
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Output:

Accessing List in Python:


There are three ways in which you can access the elements in the list in
python. They are:
1. By using indexing
2. By using the slicing operator
3. By using loops
Accessing List By using indexing in Python:
This way is the same as we have seen for the string data type. Accessing the
elements by index means, accessing by their position numbers in the list. Index
starts from 0 onwards. List also, just as strings, supports both positive and
negative indexes. The positive index represents from left to right direction and
the negative index represents from right to left direction.

Note: IndexError: If we are trying to access beyond the range of list index, then
we will get IndexError.
Example: List Indexing (demo5.py)

names = ["Prabhas", "Prashanth", "Prakash"]


print(names)
print(names[0])
print(names[1])
print(names[2])
print(type(names))
print(type(names[0]))
print(type(names[1]))
print(type(names[2]))

94
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Output:

Example: List index out of range error (Demo6.py)

names = ["Prabhas", "Prashanth", "Prakash"]


print(names)
print(names[0])
print(names[1])
print(names[2])
print(names[10])
Output:

Accessing List By using slicing operator in Python


Slicing is the way of extracting a sublist from the main list. The syntax is given
below.
list_name[start: stop: stepsize]
start represents the index from where we slice should start, the default value is
0. stop represents the end index where the slice should end. The max value
allowed is the length of the list. If no value is provided, then it takes the last
index of the list as the default value. stepsize represents the increment in the
index position of the two consecutive elements to be sliced. The result of the
slicing operation on the list is also a list i.e it returns a list.
Example: Slicing (Demo7.py)

n = [1, 2, 3, 4,5, 6]
print(n)
print(n[2:5:2])
print(n[4::2])
print(n[3:5])
Output:

95
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training

Accessing List By using loops in Python:


We can also access the elements of a list using for and while loops
Example: Accessing list using loops (demo8.py)

a = [100, 200, 300, 400]


for x in a:
print(x)
Output:

Example: Accessing list using loops (demo9.py)

a = [100, 200, 300, 400]


x=0
while x<len(a):
print(a[x])
x = x+1
Output:

IMPORTANT FUNCTIONS OR METHODS OF LISTS IN PYTHON


In python, a method and functions are one and the same. There is not much
difference between them. It will be clearly explained in the OOPS concepts. For
now, just remember function and method are the same.
len() method in python:
This function when applied to a list will return the length of the elements in it.
Example: len() function (demo10.py)

n = [1, 2, 3, 4, 5]
print(len(n))
Output: 5

96
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
count() function in Python:
This method returns the number of occurrences of a specific item in the list
Example: count() method (demo11.py)

n = [1, 2, 3, 4, 5, 5, 5, 3]
print(n.count(5))
print(n.count(3))
print(n.count(2))
Output:

append() method in Python:


Using this method we can add elements to the list. The items or elements will
be added at the end of the list.
Example: append() method (demo12.py)

l=[]
l.append("Ramesh")
l.append("Suresh")
l.append("Naresh")
print(l)

Output:
insert() method in Python:
We can add elements to the list object by using the insert() method. The insert()
method takes two arguments as input: one is the index and the other is the
element. It will add the elements to the list at the specified index.
Example: insert() method (demo13.py)

n=[10, 20, 30, 40, 50]


n.insert(0, 76)
print(n)
Output:
Difference between append and insert in Python
Both methods are used to add elements to the list. But the difference between
them is that the append will add the elements to the last, whereas the insert
will add the elements at the specified index mentioned.
While you are using the insert() method,
1. If the specified index is greater than the max index, then the element will
be inserted at the last position.

97
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
2. If the specified index is smaller than the min index, then the element will
be inserted at the first position.
Example: insert() method (demo14.py)

l=[10, 20, 30, 40]


print(l) # [10, 20, 30, 40]
l.insert(1, 111)
print(l) # [10, 111, 20, 30, 40]
l.insert(-1, 222)
print(l) # [10, 111, 20, 30, 222, 40]
l.insert(10, 333)
print(l) # [10, 111, 20, 30, 222, 40, 333]
l.insert(-10, 444)
print(l) # [444, 10, 111, 20, 30, 222, 40, 333]
Output:

extend() method in Python:


Using this method the items in one list can be added to the other.
Example: extend() method (demo15.py)

l1 = [1,2,3]
l2 = ['Rahul', 'Rakesh', 'Regina']
print('Before extend l1 is:', l1)
print('Before extend l2 is:', l2)
l2.extend(l1)
print('After extend l1 is:', l1)
print('After extend l2 is:', l2)
Output:

Example: extend() method (demo16.py)

august_txns = [100, 200, 500, 600, 400, 500, 900]


sept_txns = [111, 222, 333, 600, 790, 100, 200]
print("August month transactions are : ",august_txns)
98
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
print("September month transactions are : ",sept_txns)
sept_txns.extend(august_txns)
print("August and Sept total transactions amount: ",sum(sept_txns))
Output:

remove() method in Python:


We can use this method to remove specific items from the list.
Example: remove() method (demo17.py)

n=[1, 2, 3]
n.remove(1)
print(n)

Output:
If the item exists multiple times, then only the first occurrence will be removed.
If the specified item not present in list, then we will get ValueError. Before
removing elements it’s a good approach to check if the element exists or not to
avoid errors.
Example: remove() method (demo18.py)

n=[1, 2, 3, 1]
n.remove(1)
print(n)

Output:
Example: remove() method (demo19.py)

n=[1, 2, 3, 1]
n.remove(10)
print(n)

Output:
pop() method in Python:
This method takes an index as an argument and removes and returns the
element present at the given index. If no index is given, then the last item is
removed and returned by default. If the provided index is not in the range, then
IndexError is thrown.
Example: pop() method (demo20.py)

n=[1, 2, 3, 4, 5]
print(n.pop(1))

99
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
print(n)
print(n.pop())
print(n)
Output:

Example: pop() method (demo21.py)

n=[1, 2, 3, 4, 5]
print(n.pop(10))

Output:
Difference between remove() and pop()

Ordering the elements in list:


reverse() method in python:
This method reverses the order of list elements.
Example: reverse() method (demo22.py)

n=[1, 2, 3, 4, 'two']
print(n)
n.reverse()
print(n)
Output:

sort() method in Python:


In a list by default insertion order is preserved. If we want to sort the elements
of the list according to the default natural sorting order then we should go for
the sort() method. For numbers, the default natural sorting order is ascending
order. For strings, the default natural sorting order is alphabetical order. To use
the sort() method, the list should contain only homogeneous elements,
otherwise, we will get TypeError.

100
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Example: sort() method (demo23.py)

n=[1, 4, 5, 2, 3]
n.sort()
print(n)
s=['Suresh', 'Ramesh', 'Arjun']
s.sort()
print(s)
Output:

Example: sort() method (demo24.py)

n=[1, 4, 5, 2, 3, 'Suresh', 'Ramesh', 'Arjun']


n.sort()
print(n)
Output:

LIST ALIASING and CLONING in PYTHON:


Aliasing List in Python:
The process of giving a new name to an existing one is called aliasing. The new
name is called an alias name. Both names will refer to the same memory
location. If we do any modifications to the data, then it will be updated at the
memory location. Since both the actual and alias name refer to the same
location, any modifications done on an existing object will be reflected in the
new one also.
Example: aliasing (demo25.py)

x=[10, 20, 30]


y=x
print(x)
print(y)
print(id(x))
print(id(y))
x[1] = 99
print(x)
print(y)
print(id(x))
print(id(y))

101
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Output:

Cloning in List:
The process of creating duplicate independent objects is called cloning. We can
implement cloning by using the slice operator or by using the copy() method.
These processes create a duplicate of the existing one at a different memory
location. Therefore, both objects will be independent, and applying any
modifications to one will not impact the other.
Example: Cloning using slicing operator (demo26.py)

x=[10, 20, 30]


y=x[:]
print(x)
print(y)
print(id(x))
print(id(y))
x[1] = 99
print(x)
print(y)
print(id(x))
print(id(y))
Output:

Example: Cloning by using copy() method (demo27.py)

x=[10, 20, 30]


y=x.copy()
print(x)
print(y)
print(id(x))
102
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
print(id(y))
Output:

MATHEMATICAL OPERATORS on LIST


The concatenation operator (+): “+” operator concatenates two list objects to join
them and returns a single list. For this, both the operands should be list type,
else we will get TypeError
Example: Concatenation (demo28.py)

a= [1, 2, 3]
b= [4, 5, 6]
c=a+b
print(c)

Output:
Example: TypeError (demo29.py)

a= [1, 2, 3]
b= 'Balu'
c=a+b
print(c)

Output:
Multiplication operator in Lists:
The “*” operator works to repeat elements in the list by the said number of
times. For this one operand should be list and the other operand should be an
integer, else we get TypeError
Example: Multiplication operator (demo30.py)

a = [1, 2, 3]
print(a)
print(2*a)
Output:

COMPARISON of LISTS in Python


We can use relational operators (<, <=,>,>=) on the List objects for comparing
two lists. Initially, the first two items are compared, and if they are not the

103
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
same then the corresponding result is returned. If they are equal, the next two
items are compared, and so on
Example: Comparison Operators (demo31.py)

print([1, 2, 3] < [2, 2, 3])


print([1, 2, 3] < [1, 2, 3])
print([1, 2, 3] <= [1, 2, 3])
print([1, 2, 3] < [1, 2, 4])
print([1, 2, 3] < [0, 2, 3])
print([1, 2, 3] == [1, 2, 3])
Output:

While comparing lists that are loaded with strings the following things are
considered for the comparison.
1. The number of elements
2. The order of elements
3. The content of elements (case sensitive)
Example: Comparison of lists (demo32.py)

x =["abc", "def", "ghi"]


y =["abc", "def", "ghi"]
z =["ABC", "DEF", "GHI"]
a =["abc", "def", "ghi", "jkl"]
print(x==y)
print(x==z)
print(x==a)
Output:

MEMBERSHIP OPERATORS IN LIST


We can check if the element is a member of a list or not by using membership
operators. They are:
1. in operator
2. not in operator
If the element is a member of the list, then the in operator returns True
otherwise False. If the element is not in the list, then not in operator returns
True otherwise False.

104
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Example: Membership operators (demo33.py)

x=[10, 20, 30, 40, 50]


print(20 in x) # True
print(20 not in x) # False
print(90 in x) # False
print(90 not in x) # True
Output:

NESTED LISTS in Python:


A list within another list is called a nested list. It is possible to take a list as an
element in another list. Let’s understand it with example.
Example: Nested Lists (demo34.py)

a = [80, 90]
b = [10, 20, 30, a]
print(b[0])
print(b[1])
print(b[2])
print(b[3])
Output:

LIST COMPREHENSIONS IN PYTHON:


List comprehensions are the precise way of creating a list using iterable objects
like tuples, strings, lists etc. Generally, for multiplying each element of a list
with 2, we take a for loop and taking one item at a time, multiply it with 2 and
finally save the value in a new list.
Example: Multiplying with 2 (demo35.py)

x = [1, 2, 3, 4]
y = []
for i in x:
y.append(i*2)
print(y)

Output:
The above code can be written in a single line using list comprehensions.
105
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Example: List Comprehensions (demo36.py)

x = [1, 2, 3, 4]
y = [ i*2 for i in x]
print(y)

Output:
Syntax for list comprehension would be
list = [expression for item1 in iterable1 if statement]
Here Iterable represents a list, set, tuple, dictionary, or range object. The result
of list comprehension is a new list based on the applying conditions.
Example: List Comprehensions (demo37.py)

s=range(1, 20, 3)
for i in s: #This loop is for knowing what is in s
print(i)
m=[x for x in s if x%2==0] #List comprehension
print(m)
Output:

Tuples in Python
What are Tuples in Python?
A tuple refers to a collection of objects in python which are ordered and can’t be
changed. The python objects here may be strings, lists, tuples, integers etc.
Characteristics and Features of Tuples in Python:
1. Insertion order is preserved: The order in which elements are added to
the tuple is the order in which the output will be displayed.
2. Immutable: Once if we create a tuple object, then we cannot modify the
content of the tuple object. This is the only feature which differentiates
tuples from the lists.
3. Tuple can store duplicates.
4. Tuple can store the same type of objects and different types of objects as
well.
5. Index plays the main role in tuple.
6. Tuple supports both positive and negative indexes. Positive index means
forward direction (from left to right). Negative index means backward
direction (from right to left).
106
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
7. We can create a tuple by using parenthesis () symbol. Parenthesis is
optional but it’s recommended to use.
8. Inside the tuple every object should be separated by comma as a
separator.
When should we go for tuple data structure in python?
If we are going to define a data which is not going to change over the period,
then we should go for tuple data structure. For example, weekdays, calendar
months, years etc. Let us see an example for better understanding.
Example: Tuple having same type of objects (demo1.py)

employee_ids = (1, 2, 3, 4, 5)
print("same type of objects:",employee_ids)
print(type(employee_ids))
Output

Note: parenthesis are optional, when creating tuples.


Example: Parenthesis is optional for tuple (Demo2.py)

employee_ids = 1, 2, 3, 4, 5
print("same type of objects:",employee_ids)
print(type(employee_ids))
Output

Example: Different elements in tuple (demo3.py)

employee_details = (1, "RGV", 1000.123)


print("different type of objects:", employee_details)

Output:
Single Value tuple
If a tuple has only one object, then that object should end with a comma
separator otherwise python, internally, will not consider it as a tuple.
Example: Single Value Tuple (demo4.py)

name =("Sushanth")
print(name)
print(type(name))
Output

107
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Example: Single Tuple value (demo5.py)

a = (11)
print(a)
print(type(a))
Output

Example: Single Tuple (demo6.py)

name =("Sushanth",)
print(name)
print(type(name))
Output

Different Ways to Create Tuples in Python:


1. Empty Tuple
2. Single value tuple
3. Tuple with group of values
4. By using tuple() function
Empty Tuple in Python:
We can create an empty tuple by using empty parenthesis.
Example: Empty Tuple (demo7.py)

emp_id = ()
print(emp_id)
print(type(emp_id))
Output

Single Value Tuple


We can create a single value tuple in two ways:
1. Using parenthesis – Comma is mandatory.
2. Without using parenthesis – Comma is mandatory
Example:Single Value Tuple (demo8.py)

emp_id = (11,)
std_id = 120,
print(emp_id)
print(std_id)

108
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Output

Tuple with group of values


Tuple can contain group of objects; those objects can be of the same type or
different types. While creating tuple with group of values parentheses are
optional.
Example: Tuple with group of Values (demo9.py)

emp_id = (11, 12, 13)


std_id = 120, 130, 140
print(emp_id)
print(std_id)
Output

By using tuple() function


We can create a tuple by using tuple() function.
Example: Using Tuple Function (demo10.py)

l = [11, 22, 33]


t=tuple(l)
print(t)

Output:
Example: Using Tuple Function (demo11.py)

t=tuple(range(1, 10, 2))


print(t)

Output:
Different Ways to Access Tuples in Python:
We can access tuple elements in three ways,
1. Indexing
2. Slicing operator
3. Looping
These are the methods which we discussed in the lists chapter. So, let’s move
on with examples.
Accessing Tuples using Indexing in Python:
Index refers to the position where the element is stored. This is same as what
we discussed in case of strings and lists.
Example: Indexing (demo12.py)

t=(10,20,30,40,50,60)
109
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
print(t[0]) # 10 #Positive indexing
print(t[-1]) # 60 #Negative indexing
#print(t[100]) # IndexError: tuple index out of range
Output:

Accessing Tuples using Slicing operator in Python:


Example: Slicing Operator(demo13.py)
t=(10,20,30,40,50,60)
print(t[2:5])
print(t[2:100])
print(t[::2])
Output

Accessing Tuples using Looping in Python:


Example: Looping(demo14.py)
t=(10,20,30,40,50,60)
for i in t:
print(i)
Output

TUPLE IMMUTABILITY
Tuple having immutable nature. If we create a tuple then we cannot modify the
elements of the existing tuple. The operations/functions/methods on tuples,
which we are going to see now, will create and return new objects (lists, strings,
tuples) depending on the operation, but not change the existing tuple because
of its immutability.
Example: Immutability (demo15.py)

t=(10,20,30,40)
t[1]=70

Output:

110
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
MATHEMATICAL OPERATORS
We can apply plus (+) and Multiplication (*) operators on tuple.
1. + operator works as concatenation.
2. * operator works as multiplication.
Concatenation operator (+):
This operator concatenates two tuples and returns a single new tuple object.
Example: Concatenation (demo16.py)

t1=(10,20,30)
t2=(40,50,60)
t3=t1+t2
print(t3)

Output:
Multiplication operator (*):
Multiplication operator works as repetition operator, and returns a single, new,
repeated tuple object.
Example: Multiplication (demo17.py)

t1=(10,20,30)
t2=t1*3
print(t2)

Output:
IMPORTANT METHODS and FUNCTIONS of Tuples in Python:
1. len() function
2. count() method
3. index() method
4. sorted() function
5. min() and max() functions
len() function in Tuples:
It returns number of elements present in the tuple.
Example: len() function (demo18.py)

t=(10,20,30,40)
print(len(t))
Output: 4
count() method in Tuples:
It returns number of occurrences of given element in the tuple.
Example: count() method (demo19.py)

t=(10,20,10,10,20)

111
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
print(t.count(10))
Output: 3
index() method in Tuples:
It returns the index of first occurrence of the given element. If the specified
element is not available, then we will get ValueError.
Example: index() method (demo20.py)

t=(10,20,10,10,20)
print(t.index(10))
# print(t.index(30))# # ValueError
Output: 0
Example: index() method in Tuples (demo21.py)

t=(10,20,10,10,20)
#print(t.index(10))
print(t.index(30))# # ValueError

Output:
sorted() function in Tuples:
This function can sort the elements which is default natural sorting order. This
returns a sorted list of elements.
Example: sorted() method in Tuples (demo22.py)

t=(40,10,30,20)
t1=sorted(t)
print(t)
print(t1)
Output:

We can sort according to reverse of default natural sorting order as below


Example: sorted() method in Tuples (demo23.py)

t=(40,10,30,20)
t1=sorted(t,reverse=True)
print(t1)

Output:
min() and max() functions in Tuples:
These functions return min and max values according to default natural sorting
order.

112
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Example: min() and max() method in Tuples (demo24.py)

t=(40,10,30,20)
print(min(t)) # 10
print(max(t)) # 40
Output:

TUPLE PACKING
We can create a tuple by packing a group of variables.
Example: tuple packing (demo25.py)

a=10
b=20
c=30
d=40
t=a, b, c, d
print(t)

Output:
TUPLE UNPACKING
Tuple unpacking is the reverse process of tuple packing, we can unpack a tuple
and assign its values to different variables
Example: tuple unpacking (demo26.py)

t=(10, 20, 30, 40)


a, b, c, d = t
print("a=",a , "b=" , b," c=", c ,"d=",d)

Output:
Note: At the time of tuple unpacking the number of variables and number of
Values should be the same, otherwise we will get ValueError.
TUPLE COMPREHENSION
Tuple comprehension is not supported by Python. For example, let’s consider,
t= (x**2 for x in range (1,6))
This expression after execution will return a generator object in ‘t’ rather than a
tuple object. We need to run it using a loop
Example: Tuple comprehension (demo27.py)

t= ( x**2 for x in range(1,6))


print(type(t))
for x in t:

113
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
print(x)
Output

DIFFERENCES BETWEEN LISTS and TUPLES in PYTHON:


List and Tuple are exactly the same except for a small difference: List objects
are mutable Whereas Tuple objects are immutable. In both cases insertion, the
order is preserved, duplicate objects are allowed, heterogeneous objects are
allowed, index and slicing are supported.

Sets in Python with Examples


SET Data Structure in Python
Sets in python are also one of the data types just as lists and tuples. If we want
to represent a group of unique elements then we can go for sets. Set cannot
store duplicate elements.
Points to remember about set data structure in python:
1. Insertion order is not preserved.
2. Indexing and slicing are not allowed for the set.
3. Sets can store the same and different types of elements or objects.
4. Set objects are mutable which means once we create a set object we can
perform any changes in it.
Creating a SET in Python:
We can create set by using curly braces {} and all elements separated by comma
separator in set. Remember, [] is for lists, () is for tuples and {} for sets.
114
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Example: Creating a set (demo1.py)

s = {10,20,30,40}
print(s)
print(type(s))
Output:

Example: Creating a set with different elements (demo2.py)

s = {10,'20','Rahul', 234.56, True}


print(s)
print(type(s))
Output:

Example: Creating a set using range function (demo3.py)

s=set(range(5))
print(s)

Output:
From the above programs, we can observe that the order of the elements is not
the same in the input and output. Hence, the order is not preserved.
Example: Duplicates not allowed (demo4.py)

s = {10, 20, 30, 40, 10, 10}


print(s)
print(type(s))
Output:

Difference between set() function and set class in Python


1. set() is a predefined function in python.
2. The set() function is used to create a set of elements or objects, it takes a
sequence as a parameter.
3. set is predefined class in python.
4. Once if we create a set then internally the created set will be represented
as a set class type which can be checked by using the type function.
Example: Sets in Python Example (demo5.py)

r=range(0, 10)
s=set(r)
print(s)
115
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
print(type(s))
Output:

Creating an empty set in Python:


We might think that creating an empty set is just to use empty curly braces {}.
But, in python, we have another data type called dictionaries for which we use
{} braces only. Hence creating a data type with empty curly braces will be
considered as dictionary type rather than set. Then how to create an empty set?
We can do so by using the set() function as shown in the below example.
Example: Creating an empty set (demo6.py)

d={}
print(d)
print(type(d))
s=set()
print(s)
print(type(s))
Output:

IMPORTANT METHODS OF SETS in PYTHON:


add(x) method:
The add() method in sets is used to add elements to the set
Example: add() function in sets (demo7.py)

s={10,20,30}
s.add(40)
print(s)

Output:
update(x, y) method:
To add multiple items to the set. The arguments are not individual elements,
but are Iterable objects like list, range etc. All elements present in the given
Iterable objects will be added to the set.
Example: Update method in sets (demo8.py)

s = {10,20,30}
l = [40,50,60,10]

116
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
s.update(l)
print(s)

Output:
Example: Update method (demo9.py)

s = {10,20,30}
l = [40,50,60,10]
s.update(l, range(5))
print(s)

Output:
Difference between add() and update() methods in set?
1. We can use add() to add individual items to the set, whereas we can use
update() method to add multiple items to the set.
2. The add() method can take one argument whereas the update() method
can take any number of arguments but the only point is all of them
should be iterable objects.
Some examples
1. s.add(10) → Valid
2. s.add(10,20,30) → Invalid, TypeError: add() takes exactly one argument
(3 given)
3. s.update(10) → Invalid, TypeError: ‘int’ object is not iterable
4. s.update(range(1,10,2),range(0,10,2)) → Valid
copy() method in Set:
This method returns a copy of the set. It is a cloned object.
Example: copy() method (demo1o.py)

s={10,20,30}
s1=s.copy()
print(s1)

Output:
pop() method:
This method removes and returns some random element from the set
Example: pop() method (demo11.py)

s = {40,10,30,20}
print(s)
print(s.pop())
print(s)

117
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Output:

remove(x) method in Set:


This method removes specific elements from the set. If the specified element is
not present in the set then we will get KeyError.
Example: Remove() method (demo12.py)

s={40,10,30,20}
s.remove(30)
print(s)

Output:
Example: Remove (demo13.py)

s={40,10,30,20}
s.remove(50)
print(s)

Output:
discard(x) method:
This method removes the specified element from the set. If the specified element
is not present in the set, then we won’t get any error.
Example: discard (demo14.py)

s={10,20,30}
s.discard(10)
print(s)
Output:
Example: discard (demo15.py)

s={10,20,30}
s.discard(10)
print(s)
s.discard(50)
print(s)
Output:

clear() method in Python Sets:


This method removes all elements from the set.

118
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Example: Clear() method(demo16.py)

s={10,20,30}
print(s)
s.clear()
print(s)
Output:

MATHEMATICAL OPERATIONS ON SETS in PYTHON:


union() method in set:
This method return all elements present in both sets.
Syntax: x.union(y) or x|y
Example: union() method (demo17.py)

x={10,20,30,40}
y={30,40,50,60}
print(x.union(y))

Output:
intersection() method in Python SET:
This method returns common elements present in both x and y
Syntax: x.intersection(y) or x&y
Example: intersection() method(demo18.py)

x = {10,20,30,40}
y = {30,40,50,60}
print(x.intersection(y))
print(x&y)
Output:

difference() method in Python Sets:


This method returns the elements present in x but not in y
Syntax: x.difference(y) or x-y
Example: difference() method(demo19.py)

x={10,20,30,40}
y={30,40,50,60}
print(x.difference(y))
print(x-y)
119
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
print(y-x)
Output:

symmetric_difference():
This method returns elements present in either x or y but not in both
Syntax: x.symmetric_difference(y) or x^y
Example: symmetric_difference() method(demo20.py)

x={10,20,30,40}
y={30,40,50,60}
print(x.symmetric_difference(y))
print(x^y)
Output:

MEMBERSHIP OPERATOR in SETS


The membership operators are, in and not in. By using these operators we can
find whether the specified element exists in the set or not.
Example: membership operators in sets (demo21.py)

s= {1, 2, 3, "Sharuk"}
print(s)
print(1 in s)
print('S' in s)
print(2 not in s)
Output:

SET COMPREHENSION in PYTHON


Just as we have seen list comprehensions, we also have set comprehensions.
Example: comprehensions in sets (demo22.py)

s = {x*x for x in range(5)}


print(s)

Output:

120
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
REMOVING DUPLICATE ELEMENTS FROM SETS IN PYTHON
We can remove duplicates elements from a list by converting it to set using set()
function
Example: remove duplicates elements in sets (demo23.py)

l=[10,20,30,10,20,40]
s=set(l)
print(s)

Output:
FROZEN SET in PYTHON
As we know, a set is mutable which means we can modify the elements of a set
after its creation. A frozen set is the same as a set but it is immutable which
means we cannot modify the elements in the frozen set.
Creating a frozen set

vowels = ('a', 'e', 'i', 'o', 'u')


fSet = frozenset(vowels)
print(fSet)
print(type(fSet))
Output:

Dictionary in Python
Dictionaries in Python:
In python, to represent a group of individual objects as a single entity then we
have used lists, tuples, sets. If we want to represent a group of objects as key-
value pairs then we should go for dictionaries.
Characteristics of Dictionary
1. Dictionary will contain data in the form of key, value pairs.
2. Key and values are separated by a colon “:” symbol
3. One key-value pair can be represented as an item.
4. Duplicate keys are not allowed.
5. Duplicate values can be allowed.
6. Heterogeneous objects are allowed for both keys and values.
7. Insertion order is not preserved.
8. Dictionary object having mutable nature.
9. Dictionary objects are dynamic.
10.Indexing and slicing concepts are not applicable

121
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
How to Create a dictionary in Python?
The syntax for creating dictionaries with key,value pairs is: d = {key1:value1,
key2:value2, …., keyN:valueN}
Example: creating dictionary (demo1.py)

d ={1:"Ramesh", 2:"Arjun", 3:"Nireekshan"}


print(d)

Output:
Creating an Empty dictionary in Python:
We can create empty dictionaries by using curly braces. And later on, we can
add the key-value pairs into it as shown in the below example.
Example: creating an empty dictionary and adding the items (demo2.py)

d = {}
d[1] = "Ramesh"
d[2] = "Suresh"
d[3] = "Mahesh"
print(d)

Output:
ACCESSING DICTIONARIES IN PYTHON:
We can access dictionary values by using keys. Keys play a main role to access
the data.
Example: Accessing dictionary values by using keys (demo3.py)

d = {1: 'Ramesh', 2: 'Suresh', 3: 'Mahesh'}


print(d[1])
print(d[2])
print(d[3])
Output:

While accessing, if the specified key is not available then we will get KeyError
Example: KeyError (demo4.py)

d = {1: 'Ramesh', 2: 'Suresh', 3: 'Mahesh'}


print(d[10])

Output:

122
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
How to handle this KeyError?
We can handle this error by checking whether a key is already available or not
by using “in” operator. There is also another precise way of handling this error,
which we shall discuss later.
Example: Handle KeyError in Python Dictionary(demo5.py)

d = {1: 'Ramesh', 2: 'Suresh', 3: 'Mahesh'}


if 400 in d:
print(d[400])
else:
print("key not found")
Output:
Example: Employee info program by using a dictionary(demo6.py)

d={}
n=int(input("Enter number of employees: "))
i=1
while i <=n:
name=input("Enter Employee Name: ")
salary=input("Enter Employee salary: ")
d[name]=salary
i=i+1
for x in d:
print("The name is: ", x ," and his salary is: ", d[x])
Output

Updating a dictionary in Python:


We can update the value for a particular key in a dictionary. The syntax is:
d[key] = value
Case1: While updating the key in the dictionary, if the key is not available then
a new key will be added at the end of the dictionary with the specified value
Case2: If the key is already existing in the dictionary, then the old value will be
replaced with a new value
Example: Updating a dictionary – Case 1(demo7.py)

d = {1: 'Ramesh', 2: 'Suresh', 3: 'Mahesh'}


123
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
print("Old dictionary:", d)
d[10]="Hari"
print("Added key-value(10:Hari) pair to dictionary:",d)
Output

Example: Updating a dictionary – Case 2(demo8.py)

d = {1: 'Ramesh', 2: 'Suresh', 3: 'Mahesh'}


print("Old dictionary:", d)
d[3]="Hari"
print("UPdated value of key 3 pair to dictionary:",d)
Output

Removing or deleting elements from the dictionary in Python:


1. By using the del keyword, we can remove the keys
2. By using clear() we can clear the objects in the dictionary
By using the del keyword
Syntax: del d[key]
As per the syntax, it deletes entries associated with the specified key. If the key
is not available, then we will get KeyError
Example: By using del keyword (demo9.py)

d = {1: 'Ramesh', 2: 'Suresh', 3: 'Mahesh'}


print("Before deleting key from dictionary",d)
del d[1]
print("After deleting key from dictionary:", d)
Output

Example: By using del() (demo10.py)


d = {1: 'Ramesh', 2: 'Suresh', 3: 'Mahesh'}
print("Before deleting key from dictionary",d)
del d[10]
print("After deleting key from dictionary:", d)

Output:

124
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
By Using clear() method:
The clear () method removes all entries in the dictionary. After deleting all
entries, it just keeps an empty dictionary.
Example: By using clear() (demo11.py)

d = {1: 'Ramesh', 2: 'Suresh', 3: 'Mahesh'}


print("Before clearing dictionary: ", d)
d.clear()
print("After cleared entries in dictionary: ", d)
Output:

Delete total dictionary object in Python:


We can also use the del keyword to delete the total dictionary object. Before
deleting we just have to note that once it is deleted then we cannot access the
dictionary.
Syntax: del nameofthedictonary
Example: Deleting the dictionary (demo12.py)

d = {1: 'Ramesh', 2: 'Suresh', 3: 'Mahesh'}


print("Before clearing dictionary: ", d)
del d
print("After cleared entries in dictionary: ", d)
Output

Functions and methods of dictionary in Python


1. dict() function
2. dict({key1:value1, key2:value2}) function
3. dict([tuple1,tuple2])
4. len() function
5. clear() method
6. get() method
7. pop() method
8. popitem() method
9. keys() method
10.Items() method
11.keys() method
12.copy() method

125
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
dict() function:
This can be used to create an empty dictionary. Later, we can add elements to
that created dictionary
Example:

d=dict()
print(d)
print(type(d))
Output

dict({key1:value1, key2:value2}) function:


It creates dictionary with specified elements
Example:

d = dict({1: 'Ramesh', 2: 'Suresh', 3: 'Mahesh'})


print(d)

Output:
dict([tuple1,tuple2]):
This function creates a dictionary with the given list of tuple elements
Example:

d = dict([(1, "Ramesh"), (2, "Arjun")])


print(d)

Output:
len() function:
This function returns the number of items in the dictionary
Example:

d = dict([(1, "Ramesh"), (2, "Arjun")])


print("length of dictionary is: ",len(d))

Output:
clear() method:
This method can remove all elements from the dictionary. We have already
discussed this above.
get() method:
This method used to get the value associated with the key. This is another way
to get the values of the dictionary based on the key. The biggest advantage it
gives over the normal way of accessing a dictionary is, this doesn’t give any
error if the key is not present. Let’s see through some examples:
126
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Case1: If the key is available, then it returns the corresponding value otherwise
returns None. It won’t raise any errors. Syntax: d.get(key)
Case 2: If the key is available, then returns the corresponding value otherwise
returns the default value that we give. Syntax: d.get(key, defaultvalue)
Example:

d = {1: 'Ramesh', 2: 'Suresh', 3: 'Mahesh'}


print(d.get(1))
print(d.get(100))
Output

Example:

d = {1: 'Ramesh', 2: 'Suresh', 3: 'Mahesh'}


print(d.get(1))
print(d.get(100,'No key found'))
Output

pop() method:
This method removes the entry associated with the specified key and returns
the corresponding value. If the specified key is not available, then we will get
KeyError
Syntax: d.pop(key)
Example:

d = {1: 'Ramesh', 2: 'Suresh', 3: 'Mahesh'}


print("Before pop:", d)
d.pop(1)
print("After pop:", d)
Output

Example:

d = {1: 'Ramesh', 2: 'Suresh', 3: 'Mahesh'}


d.pop(23)
Output:
popitem() method:
This method removes an arbitrary item(key-value) from the dictionary and
returns it.
127
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Example:

d = {1: 'Ramesh', 2: 'Suresh', 3: 'Mahesh'}


print("Before popitem:", d)
d.popitem()
print("After popitem:", d)
Output

If the dictionary is empty, then we will get KeyError


Example:

d= {}
d.popitem()
print("After popitem:", d)

Output:
keys() method:
This method returns all keys associated with the dictionary.
Example:

d = {1: 'Ramesh', 2: 'Suresh', 3: 'Mahesh'}


print(d)
for k in d.keys():
print(k)
Output

values() method:
This method returns all values associated with the dictionary
Example:

d = {1: 'Ramesh', 2: 'Suresh', 3: 'Mahesh'}


print(d)
for k in d.values():
print(k)

128
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Output

items() method:
A key-value pair in a dictionary is called an item. items() method returns the list
of tuples representing key-value pairs.
Example:

d = {1: 'Ramesh', 2: 'Suresh', 3: 'Mahesh'}


for k, v in d.items():
print(k, "---", v)
Output

copy() method:
To create an exactly duplicate dictionary (cloned copy)
Example:

d1 = {1: 'Ramesh', 2: 'Suresh', 3: 'Mahesh'}


d2=d1.copy()
print(d1)
print(d2)
Output:

Dictionary Comprehension in Python:


Just as we had lists and sets comprehensions, we also have this concept
applicable for dictionaries even.
Example:

squares={a:a*a for a in range(1,6)}


print(squares)

Output:

129
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training

Python - Object Oriented

Programming
OOPs in Python
Before OOPs
Before oops(object oriented programming), there were two approaches,
procedure-oriented programming and functional oriented programming, being
used.
What are these?
All the three approaches mentioned above are programming paradigms. A
programming paradigm is nothing but the style of writing a program. We can
also call them as methodologies which are used in writing a software program.
Different languages follow different methodologies.
Functional Oriented Programming
Functional oriented programming is a program paradigm where programs are
built around functions. Functions can be used as parameters, can be returned,
can be used in other functions etc. Here functions are everything and they
should always return the same output for a particular input. Erlang, Haskell,
and Sakaila are the languages which are built on this paradigm.
Procedural Oriented Programming
POP languages are C, Pascal, Fortran etc. These languages used procedures
and functions to perform the task. This kind of programming divides the
program into subtasks composed of several procedures or functions or routines.
This approach is called Procedure Oriented Approach.
After OOPs
OOPs is paradigm or methodology to implement software. OOPs languages are
C++, Java, Dot Net etc. While developing any software, by using OOPs we need

130
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
to implement it using classes and objects. This approach is called Object-
Oriented Programming.
Where does Python belong to?
Python follows both functional oriented and object oriented programming
approaches.
What is OOPS?
Object Oriented Programming language is a methodology which uses the
concept of class and object to program. Let’s understand the concept of classes
and objects with an example of a vehicle.
For example, let’s list down the properties a vehicle possess
1. Name
2. Number of wheels
3. Colour
4. Brand
Now, if we consider ‘vehicle’ as class, then the properties which we listed above
will be attributes of that class. The types of vehicles available are
1. Bike
2. Car
3. Truck
4. Jeep
These types of vehicles will be objects to the class vehicle. All the properties of a
car, like the name of the vehicle, number of wheels it has, its colour, its brand
can be stored in the class ‘vehicle’. In order to access the information of the car
we can create and object for the class and access it. Let’s say ‘car_obj’ is the
object created for class ‘vehicle’ and assume the following data
1. car_obj.name will be car
2. car_obj.number_of_wheels will be four
3. car_obj.colour will be blue
4. car_obj.brand will be audi
Similarly, let’s create another object with name bike_obj
1. bike_obj.name will be bike
2. bike_obj.number_of_wheels will be two
3. bike_obj.colour will be black
4. bike_obj.brand will be honda
For both the objects, car_obj and bike_obj, the class is the same i.e vehicle, the
attributes are the same, but the data is different. You can create any number of
objects to the class and use the attributes to save the data.
We can say that class is a template or blueprint with which we can create
objects. The objects of the same class contain different data but the same
attributes.
FEATURES OF OOPS:
Let’s understand the terms familiar in OOPS.
1. Class
2. Object
3. Encapsulation
4. Abstraction
5. Inheritance
6. Polymorphism
131
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
7. Abstract class
Class in Python:
A class is a blueprint or template which contains attributes.It is a specification
of properties and action of objects.
Defining a class:

Documentation string represents the description of the class. It’s up to you to


include this i.e its optional. It’s a good programming practice to include this.
After the class keyword comes the name of the class. After the name of the class
we should give colon : symbol. class can contain
Constructors are used for initialization purpose and variables are used to
represent the data. Variables can be of three types are as follows:
1. instance variables
2. static variables
3. local variables
Methods are used to represent actions. Methods are again of three types are as
follows:
1. instance methods
2. static methods
3. class methods
Example: Define a class (demo1.py)

class Employee:
def display(self):
print("Hello my name is Shiksha")
In the above program ‘Employee’ represents a class which is defined by the
developer. display is the method in the class. The program doesn’t give any
output because we haven’t created any object to access the class members
(attributes).
Self variable in Python:
In the demo1.py the display method has a parameter named ‘self’. Let’s talk
about it:
1. self is a default variable that refers to a current class object or the
current instance(object) of a class.

132
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
2. Generally, by using self, we can initialize the instance variables inside the
constructor. (To be discussed in detail later).
3. By using a self variable, we can access instance variables and instance
methods.
4. It can also be some other name rather than ‘self’, but the most commonly
used and preferred is ‘self’.
5. It contains the address of the current object being referred.
Objects in Python:
An object is an instance of a class. Using objects we can access class members,
store data etc. They are like physical entities of class.
Syntax: name_of_the_object = NameOfTheClass()
Example: demo1.py contd..
class Employee:
def display(self):
print("Hello my name is Shiksha")
emp_obj = Employee()
emp_obj.display()

Output:
Here, we created an object ‘emp_obj’ for the class ‘Employee’. With the created
object, we called the display method which is printing something to the console.
Therefore, after creating the object of a class, we can access the attributes
available in that class with the created object as shown below.

1. name_of_the_object.method()
2. name_of_the_object.variable
Can we create more than one object to a class?
Yes, the main concept of OOPs is class acts as a template for the objects. So,
any number of objects can be created for one class.
Example: Creating more than one object (demo2.py)
class Employee:
def display(self):
print("Hello my name is Rahul")
emp_obj1 = Employee()
emp_obj1.display()
emp_obj2 = Employee()
emp_obj2.display()
Output:

133
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training

Constructors in Python
Constructors in Python
In any programming language, constructor is a method which, by default, is
invoked whenever an instance(object) for a class is created. It’s not required to
explicitly invoke or call it.
Generally, the constructor is used for initial intializations that are required
during the object creation. In python, constructor is a method with the name
‘__init__’. The methods first parameter should be ‘self’ (referring to the current
object).
Syntax:

Is constructor mandatory in Python?


No, it’s not mandatory for a class to have a constructor. It completely is based
on our requirement whether to have a constructor or not. At the time of object
creation if any initialization is required then we should go for a constructor, else
it’s not needed. Without a constructor also, the python program is valid.
Example: Constructor (demo3.py)
class Employee:
def __init__ (self):
print("constructor is executed automatically at the time of object
creation")
emp = Employee()
Output:

In this demo3.py, we just created an object and haven’t called any method. But,
we have something printed to the console, which is done by the constructor
“__init__”. Hence, we can conclude that it is automatically called at the time of
object creation,
Can a constructor be called explicitly?
Yes, we can call constructor explicitly with object name. But since the
constructor gets executed automatically at the time of object creation, it is not
recommended to call it explicitly.
Example: Calling Constructor Explicitly (demo4.py)
class Employee:
def __init__ (self):
print("constructor")
emp = Employee()
emp.__init__()
134
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Output:

Note: The constructor is not mandatory to be included. In case, if we haven’t


included a constructor then python will, internally, include an empty
constructor. We can check this by using dir(class_name) built in method.
Example: Empty Constructor in Python(demo5.py)
class Sample:
def m1(self):
print("m1 is instance method called with object name")
s = Sample()
s.m1()
print(dir(Sample))
Output:

How many parameters can constructor have?


Constructor can have any number of parameters depending on the
requirement. There is no limit for it. All the values which we need or want to be
initialized during the object creation should be passed on to the constructor. A
variable, by default, should be referring to the current instance should always
be there in the constructor i.e self.
Example: Non Parameterized Constructor in Python(demo6.py)
class Employee:
def __init__ (self):
print("constructor")
print(self)
emp = Employee()
Output:

In demo.6.py, the constructor doesn’t have any parameters except self. The self
contains the current object address.
Example: Non Parameterized Constructor in Python(demo7.py)
class Employee:
def __init__(self):
self.id = 1
print("Employee id is: ", self.id)
e1 = Employee()

135
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
e2 = Employee()
e3 = Employee()
Output:

Parameterised Constructor in Python:


In demo7.py also, the constructor doesn’t have any parameters except self. In
constructor we initialized a variable ‘id’ with value 1. All the objects created for
the above class will have the same value for id. If we want different values for
different instances then we need to go for a parameterised constructor.
Example: Parameterised Constructor in Python(demo8.py)
class Employee:
def __init__(self, id):
self.id = id
print("Employee id is: ", self.id)
e1 = Employee(1)
e2 = Employee(2)
Output:

In demo8.py, we have used a parameterised constructor with id as a parameter.


At the time of object creation, we need to pass a value so that it can be stored in
the id variable for the object. While referring to the id of the object ‘e1’, self will
be referring to e1. Hence, self.id gives 1 as the output. While referring to the id
of the object ‘e2’, self will be referring to e2. Hence, self.id gives 2 as the output.
This explains us what self exactly is and how it can be used.
Example: Parameterised Constructor in Python(demo9.py)
class Employee:
def __init__(self, id,name):
self.id=id
self.name=name
def display(self):
print("Hello my id is :", self.id)
print("My name is :", self.name)
e1=Employee(1, 'Nithin')
e1.display()
e2=Employee(2, 'Arjun')
e2.display()
Output:
136
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training

Difference between a method and constructor:

Difference between a method and a function


Functions which are written inside a class can be accessed only with the
objects created from the class. They are called methods. We can say that
methods are nothing but functions which can be referenced by the objects of
the class.

Types of Variables in a Class in Python


Types of Class Variables in Python:
Inside a class, we can have three types of variables. They are:
1. Instance variables (object level variables)
2. Static variables (class level variables)
3. Local variables
Instance Variables in Python:
If the value of a variable is changing from object to object then such variables
are called as instance variables.
Example: (Instance Variables) demo10.py
class Student:
def __init__(self, name, id):
self.name=name
self.id=id
s1=Student('Nitya', 1)
s2=Student('Anushka', 2)
print("Studen1 info:")
print("Name: ", s1.name)

137
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
print("Id : ", s1.id)
print("Studen2 info:")
print("Name: ",s2.name)
print("Id : ",s2.id)
Output:

The value of id,name is different for instances(objects) s1 and s2, hence they
are instance variables. In the case of instance variables for every object a
separate copy will be created.
Where instance variables can be declared?
We can declare and initialize the instance variables in following ways,
1. By using a constructor.
2. By using instance methods.
3. By using object name
Declaring instance variables in a constructor
We can declare and initialize instance variables inside a constructor by using
self variable.
Example: Declaring instance variables in a constructor (demo11.py)
class Employee:
def __init__(self):
self.eno=1
self.ename="Nithya"
self.esal=100
e=Employee()
print("Employee number: ",e.eno)
print("Employee name: ", e.ename)
print("Employee salary: ", e.esal)
print(e.__dict__)
Output:

Every object in Python has an attribute denoted as __dict__, which python


creates internally. This displays the object information in dictionary form. It
maps the attribute name to its value.

138
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Declaring instance variables using instance methods
We can declare and initialize instance variables inside instance method by
using self variable.
Example: Declaring instance variables using instance methods
(demo12.py)
class Student:
def m1(self):
self.a=11
self.b=21
self.c=34
print(self.a)
print(self.b)
print(self.c)
s= Student()
s.m1()
print(s.__dict__)
Output:

Declaring instance variables using object name


We can declare and initialize instance variables by using object name as well
Example: Declaring instance variables using object name (demo13.py)
class Test:
def __init__(self):
print("This is constructor")
def m1(self):
print("This is instance method")
t=Test()
t.m1()
t.a=10
t.b=20
t.c=55
print(t.a)
print(t.b)
print(t.c)
print(t.__dict__)
139
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Output:

Accessing instance variables in Python:


The instance variable can be accessed in two ways:
1. By using self variable
2. By using object name
Accessing instance variables By self variable in Python:
We can access instance variables within the class by using self variable.
Example: Accessing instance variables in Python By self variable
(demo14.py)
class Student:
def __init__(self):
self.a=10
self.b=20
def display(self):
print(self.a)
print(self.b)
s= Student()
s.display()
Output:

Accessing instance variables By object name:


We can access instance variables by using the object’s name.
Example: Accessing instance variables in Python By object name
(demo15.py)
lass Student:
def __init__(self):
self.a=10
self.b=20
t=Student()
print(t.a)
print(t.b)
Output:

140
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Static Variables in Python
If the value of a variable is not changing from object to object, such types of
variables are called static variables or class level variables. We can access static
variables either by class name or by object name. Accessing static variables
with class names is highly recommended than object names.
Accessing static variables outside of class
Example: Accessing static variables outside of class in Python (demo16.py)
class Student:
college_name='GITAM'
def __init__(self, name, id):
self.name=name
self.id=id
s1=Student('Nithya', 1)
s2=Student('Anushka', 2)
print("Studen1 info:")
print("Name: ", s1.name)
print("Id : ", s1.id)
print("College name n : ", Student.college_name)
print("\n")
print("Studen2 info:")
print("Name: ",s2.name)
print("Id : ",s2.id)
print("College name : ", Student.college_name)
Output:

Example: Accessing static variables with object name (demo17.py)


class Student:
college_name='GITAM'
def __init__(self, name, id):
self.name=name
self.id=id
141
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
s1=Student('Nithya', 1)
s2=Student('Anushka', 2)
print("Studen1 info:")
print("Name: ", s1.name)
print("Id : ", s1.id)
print("College name n : ", s1.college_name)
print("\n")
print("Studen2 info:")
print("Name: ",s2.name)
print("Id : ",s2.id)
print("College name : ", s1.college_name)
Output:

Declaring static variables in Python:


We can declare static variable in the following ways,
1. Inside class and outside of the method
2. Inside constructor
3. Inside instance method
4. Inside class method
5. Inside static method
Declaring static variable inside class and outside of the method
Generally, we can declare and initialize static variable within the class and
outside of the methods. This is the preferred way.
Example: Declaring static variable inside class and outside of the method
(demo18.py)
class Demo:
a=20
def m(self):
print("this is method")
print(Demo.__dict__)
Output:

142
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training

Declaring static variable inside constructor


We can declare and initialize static variables within the constructor by using
class’s name.
Example: Declaring static variable inside constructor (demo19.py)
class Demo:
def __init__(self):
Demo.b=20
d = Demo()
print(Demo.__dict__)
Output:

Declaring static variable inside instance method


We can declare and initialize static variable inside instance method by using
class Name just as we have done in the constructor.
Example: Declaring static variable inside instance method (demo20.py)
class Demo:
def m1(self):
Demo.b=20
obj=Demo()
obj.m1()
print(Demo.__dict__)
Output:

Declaring static variable inside class method


We can declare and initialise static variable inside class method in two ways,
one is using class name, other is using cls pre-defined variable
What is class method?
A method inside a class with @classmethod decorator is called a class method.
We will discuss this in next chapters. Inside the class method we can declare
and initialize static variables by using the class’s name.
Example: Declaring static variable inside class method (demo21.py)

143
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
class Demo:
@classmethod
def m2(cls):
Demo.b=30
obj=Demo()
obj.m2()
print(Demo.__dict__)
Output:

We can also do the initialization in the class method using the cls variable. cls
is predefined variable in python. We should pass the cls parameter to the class
methods just as we use self for instance methods.
Example: static variable inside class method by using cls (demo21.py)
class Demo:
@classmethod
def m2(cls):
cls.b=30
obj=Demo()
obj.m2()
print(Demo.__dict__)
Output:

Declaring static variable inside static method


We can declare and initialize static variables inside a static method by using
class name.
What is a static method?
Before method if we write @staticmethod decorator then that method will
become a staticmethod. We will learn more about static method in upcoming
chapter
Example: static variable inside static method by using class name
(demo22.py)
class Demo:
@staticmethod
def m3():

144
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Demo.z=10
Demo.m3()
print(Demo.__dict__)
Output:

Accessing a static variable within the class in Python:


We have already discussed with examples, how static variables can be accessed
outside of class earlier. Now, we shall discuss how we can access static variable
in (within the class),
1. Inside constructor
2. Inside instance method
3. Inside class method
4. Inside static method
Accessing a static variable Inside Constructor:
We can access static variables inside the constructor by using either self or
class name.
Example: Accessing static variable Inside Constructor (demo23.py)
class Demo:
a=10
def __init__(self):
print(self.a)
print(Demo.a)
d = Demo()
Output:

Accessing a static variable Inside instance method:


We can access static variables inside instance methods by using either self or
class name.
Example: Accessing static variable Inside instance method (demo24.py)
class Demo:
a=10
def m1(self):
print(self.a)
print(Demo.a)
obj=Demo()
obj.m1()
145
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Output:

Accessing a static variables Inside class method:


We can access static variables inside class methods by using cls variables and
class’s name.
Example: Accessing static variable Inside class method (demo25.py)
class Demo:
a=10
@classmethod
def m1(cls):
print(cls.a)
print(Demo.a)
obj=Demo()
obj.m1()
Output:

Accessing a static variables Inside static method:


We can access static variables inside the static method by using class’s name.
Example: Accessing static variable Inside static method (demo26.py)
class Demo:
a=10
@staticmethod
def m1():
print(Demo.a)
obj=Demo()
obj.m1()
Output:
Local Variables in Python:
The variable which we declare inside of the method is called a local variable.
Generally, for temporary usage we create local variables to use within the
methods. The scope of these variables is limited to the method in which they
are declared. They are not accessible out side of the methods.
Example: Local Variables in Python (demo27.py)
class Demo:
def m(self):
a=10 #Local Variable

146
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
print(a)
d=Demo()
d.m()
Output:
Example: Local Variables in Python (demo28.py)
class Demo:
def m(self):
a=10 #Local Variable
print(a)
def n(self):
print(a) #'a' is local variable of m()
d=Demo()

Output:

Types of Methods in a Class in Python


Types of Methods in a Class
In python, we can classify the methods into three types from the perspective of
object oriented programming.
1. Instance Methods
2. Class Methods
3. Static Methods
Instance Methods in Python:
Instance methods are methods which act upon the instance variables of the
class. They are bound with instances or objects, that”s why called as instance
methods. The first parameter for instance methods should be self variable
which refers to instance. Along with the self variable it can contain other
variables as well.
Example: Instance Methods in Python (demo29.py)
class Demo:
def __init__(self, a):
self.a=a
def m(self):
print(self.a)
d=Demo(10)
d.m()

Output:

147
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Setter and Getter methods in Python:
Setter methods can be used to set values to the instance variables. They are
also known as mutator methods. Their main aim is to only set values to
instance variables, hence they don’t return anything.
Syntax:

Example: Setter Methods in Python (demo30.py)


class Customer:
def set_name(self, name):
self.name=name
def set_id(self, id):
self.id=id
c=Customer()
c.set_name("Balayya")
c.set_id(1)
print(c.name)
Output:

Getter methods are used to get the values of instance variables. They return the
value in the instance variable. Getter methods also known as accessor methods.
Syntax:

Example: Getter Methods in Python (demo31.py)


class Customer:
def set_name(self, name):
self.name=name
def set_id(self, id):
self.id=id
def get_name(self):
return self.name
def get_id(self):
return self.id
c=Customer()
c.set_name("Balayya")

148
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
c.set_id(1)
print("My name is: ", c.get_name())
print("My id is: ", c.get_id())
Output:

Class Methods in Python:


Class methods are methods which act upon the class variables or static
variables of the class. We can go for class methods when we are using only
class variables (static variables) within the method.
1. Class methods should be declared with @classmethod.
2. Just as instance methods have ‘self’ as the default first variable, class
method should have ‘cls’ as the first variable. Along with the cls variable
it can contain other variables as well.
3. Class methods are rarely used in python
Example: Class Methods in Python (demo32.py)
class Pizza:
radius=200
@classmethod
def get_radius(cls):
return cls.radius
print(Pizza.get_radius())

Output:
Static Methods in Python:
The static methods, in general, utility methods. Inside these methods we won’t
use any instance or class variables. No arguments like cls or self are required at
the time of declaration.
1. We can declare static method explicitly by using @staticmethod
decorator.
2. We can access static methods by using class name or object reference
Example: Static Methods in Python (demo33.py)
class Demo:
@staticmethod
def sum(x, y):
print(x+y)
@staticmethod
def multiply(x, y):
print(x*y)
Demo.sum(2, 3)
Demo.multiply(2,4)
149
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Output:

Nested Classes in Python:


A class inside another class are called nested classes.
Example: Nested Classes in Python (demo34.py)
class A:
def __init__(self):
print("outer class object creation")
class B:
def __init__(self):
print("inner class object creation")
def m1(self):
print("inner class method")
a=A()
b=a.B()
b.m1()
Output:

So, to create inner class object, first we need to create outer class object. With
the created outer class object we can create an inner class object. After creating
an inner class object, we can access the members of the inner class.
Garbage Collection in Python:
1. In old languages like C++, programmers are responsible for both creation
and destruction of objects.
2. Usually a programmer should take very much care to create objects, and
sometimes he may neglect destruction of useless objects.
3. Due to this negligence, at a certain point of time there may be a chance,
total memory can be filled with useless objects which creates memory
problems and total application will be down with Out of memory error.
4. But in Python, internally a program will run in background always to
destroy useless objects.
5. So, the chance of failing a Python program with memory problems are
very little.
6. This program is nothing but Garbage Collector.
Objective:
The main objective of Garbage Collector is to destroy useless objects. If an
object does not have any reference variable, then that object is eligible for
Garbage Collection.
By default, the Garbage collector is enabled, but we can disable it based on our
requirement. In order to do so, we need to import the gc module.
150
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Methods:
1. gc.isenabled() – This method returns True if garbage collector is enabled
2. gc.disable() – This function is used to is disable the garbage collector
explicitly
3. gc.enable() – This function is used to is enable the garbage collector
explicitly
Example: Garbage Collection in Python (demo35.py)
import gc
print(gc.isenabled())
gc.disable()
print(gc.isenabled())
gc.enable()
print(gc.isenabled())
Output:

Inheritance in Python
What is Inheritance in Python:
Inheritance, in general, is the passing of properties to someone. In
programming languages, the concept of inheritance comes with classes.
1. Creating new classes from already existing classes is called inheritance.
2. The existing class is called a super class or base class or parent class.
3. The new class is called a subclass or derived class or child class.
4. Inheritance allows sub classes to inherit the variables, methods and
constructors of their super class.
Advantages of Inheritance:
1. The main advantage of inheritance is code re-usability.
2. Time taken for application development will be less.
3. Redundancy (repetition) of the code can be reduced.
Implementation of Inheritance in Python:
While declaring subclass, we need to pass super class name into subclass’s
parenthesis
Program: Implementing Inheritance (demo1.py)
class One:
def m1(self):
print("Parent class m1 method")
class Two(One):
def m2(self):
print("Child class m2 method")
151
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
c = Two()
c.m1()
c.m2()
Output:

Types of Inheritance in Python:


There are there types of inheritance, they are:
1. Single inheritance
2. Multilevel inheritance
3. Multiple inheritance
SINGLE INHERITANCE in PYTHON:
Creating a subclass or child class from a single superclass/parent class is
called single inheritance. Diagrammatic representation of Python Single
Inheritance is given below.

Program: Single Inheritance (demo2.py)


class A:
def m1(self):
print("A class m1 Method")
class B(A):
def m2(self):
print("Child B is derived from A class: m2 Method")
obj=B()
obj.m1()
obj.m2()
Output:

MULTILEVEL INHERITANCE in PYTHON:


If a class is derived from another derived class then it is called multi level
inheritance. Diagrammatic representation of Python Multilevel Inheritance is
given below.
152
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training

Program: Multilevel inheritance (demo3.py)


class A:
def m1(self):
print("Parent class A: m1 Method")
class B(A):
def m2(self):
print("Child class B derived from A: m2 Method")
class C(B):
def m3(self):
print("Child class C derived from B: m3 Method")
obj=C()
obj.m1()
obj.m2()
obj.m3()
Output:

MULTIPLE INHERITANCE in PYTHON:


If a child class is derived from multiple superclasses then it is called multiple
inheritance. Diagrammatic representation of Multiple Inheritance is given
below.

153
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training

Program: Multiple Inheritance (demo4.py)


class P1:
def m1(self):
print("Parent1 Method")
class P2:
def m2(self):
print("Parent2 Method")
class C(P1, P2):
def m3(self):
print("Child Method")
c=C()
c.m1()
c.m2()
c.m3()
Output:

What if both parent classes have a method with the same name?
There may be a chance that two parent classes can contain methods which are
having the same method name in both classes. Syntactically this is valid.
Program: Parent classes having same method names (demo5.py)
class P1:
def m1(self):
print("Parent1 Method")
class P2:
def m1(self):
print("Parent2 Method")
class C(P1, P2):
154
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
def m2(self):
print("Child Method")
c=C()
c.m2()

Output:
In the above scenario, which method will child class inherit?
The answer for this depends on the order of inheritance of parent classes in the
child class.
1. class C(P1, P2): ===>P1”s class method will be considered
2. class C(P2, P1): ===>P2”s class method will be considered
Program: demo5.py contd
class P1:
def m1(self):
print("Parent1 Method")
class P2:
def m1(self):
print("Parent2 Method")
class C(P1, P2):
def m2(self):
print("Child Method")
c=C()
c.m2()
c.m1()
Output:

Program: Other scenario of demo5.py


class P1:
def m1(self):
print("Parent1 Method")
class P2:
def m1(self):
print("Parent2 Method")
class C(P2, P1):
def m2(self):
print("Child Method")
c=C()
155
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
c.m2()
c.m1()
Output:

CONSTRUCTORS in INHERITANCE
By default, the super class‟s constructor will be available to the subclass.
Program:demo6.py
class A:
def __init__(self):
print("super class A constructor")
class B(A):
def m1():
print("Child Class B: m1 method from B")
b=B()

Output:
If child class and super class both have constructors, then?
If child class and super class both have constructors, if you create an object to
child class then child class constructor will be executed. While creating object
for a class, that class’s constructor is first priority.
Program: demo7.py
class A:
def __init__(self):
print("super class A constructor")
class B(A):
def __init__(self):
print("Child class B constructor")
b=B()

Output:
Can we call super class constructor from child class constructor?
Yes, we can call super class constructor from child class constructor by using
super() function. super() is a predefined function which is useful to call the
superclass constructors, variables and methods from the child class.
Program: demo8.py
class A:
def __init__(self):
print("super class A constructor")

156
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
class B(A):
def __init__(self):
print("Child class B constructor")
super().__init__()
b=B()
Output:

Method Resolution Order (MRO) in Python


Method Resolution Order (MRO)
In multiple inheritance scenarios, any specific attribute or method will initially
be searched in the current class. If not found in the current class, then next
search continues into parent classes in depth-first left to right fashion.
Searching in this order is called Method Resolution Order (MRO).
Three principles of MRO:
1. The first principle is to search for the subclass before going for its base
classes. If class B is inherited from A, it will search B first and then goes
to A.
2. The second principle is, if any class is inherited from several classes, it
searches in the order from left to right in the base classes. For example, if
class C is inherited from A and B, syntactically class C(A, B), then first it
will search in A and then in B.
3. The third principle is that it will not visit any class more than once. That
means a class in the inheritance hierarchy is traversed only once exactly.
Understanding MRO gives you clear idea regarding which classes are being
executed and in which sequence. We have a predefined method to see the
sequence of execution of classes. It is: classname.mro()
Demo 1 for MRO

157
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Here,
1. mro(A)=A, object
2. mro(B)=B, A, object
3. mro(C)=C, A, object
4. mro(D)=D, B, C, A, object
Note: Object is a default super class in python.
Program: MRO (demo9.py)

class A:
def m1(self):
print("m1 from A")
class B(A):
def m1(self):
print("m1 from B")
class C(A):
def m1(self):
print("m1 from C")
class D(B, C):
def m1(self):
print("m1 from D")
print(A.mro())
print(B.mro())
print(C.mro())
print(D.mro())
Output:

Program: MRO contd (demo10.py)

class A:
def m1(self):
print("m1 from A")
class B(A):
def m1(self):
print("m1 from B")
class C(A):
def m1(self):

158
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
print("m1 from C")
class D(B, C):
def m1(self):
print("m1 from D")
c=C()
c.m1()
print(C.mro())
Output:

In above program, with c object we are calling m1 method. So, m1() is already
available in C class, so output is m1 from C.
Program: demo11.py

class A:
def m1(self):
print("m1 from A")
class B(A):
def m1(self):
print("m1 from B")
class C(A):
def m2(self):
print("m2 from C")
class D(B, C):
def m1(self):
print("m1 from D")
c=C()
c.m1()
print(C.mro())
Output:

In the above program, with the object ‘c’ we are calling the m1 method. But the
m1() method is not available in class C. First the search will be in class C, then
it will be in class A because A is super class to C. In class A, m1() method is
available, so output is ‘m1 from A’.
Program: MRO contd. (demo12,py)

class A:
def m1(self):
159
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
print("m1 from A")
class B(A):
def m1(self):
print("m1 from B")
class C(A):
def m1(self):
print("m1 from C")
class D(B, C):
def m1(self):
print("m1 from D")
d=D()
d.m1()
print(D.mro())
Output:

In the above program, with object ‘d’ we are calling the m1 method. Since,
method m1() is already available in class D, the output is ‘m1 from D’.
Program: MRO contd (demo13.py)

class A:
def m1(self):
print("m1 from A")
class B(A):
def m1(self):
print("m1 from B")
class C(A):
def m1(self):
print("m1 from C")
class D(B, C):
def m3(self):
print("m3 from D")
d=D()
d.m1()
print(D.mro())
Output:

160
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training

In the above program, with object ‘d’ we are calling the method m1(). But,
method m1() is not available in class D. So, next it will search in class B
because it is super class to class D and also the first one to be searched
according to MRO. In class B, m1() method is available, so output is ‘m1 from
B’.
Program: MRO contd (demo14.py)

class A:
def m1(self):
print("m1 from A")
class B(A):
def m2(self):
print("m1 from B")
class C(A):
def m1(self):
print("m1 from C")
class D(B, C):
def m3(self):
print("m3 from D")
d=D()
d.m1()
print(D.mro())
Output:

In the above program, with object ‘d’ we are calling the method m1(). Since,
method m1() is not available in class D, it will search in class B based on MRO
(class B is superclass to class D). m1() method is also not available in class B.
So, next it will search in class C because C is also super class to class D. In
class C m1() method is available, so output is ‘m1 from C’.

161
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Demo2 for MRO

Here,
1. mro(A)=A, object
2. mro(B)=B, object
3. mro(C)=C, object
4. mro(X)=X, A, B, object
5. mro(Y)=Y, B, C, object
6. mro(P)=P, X, A, Y, B, C, object
Program: MRO (demo15.py)

class A:
def m1(self):
print("m1 from A")
class B:
def m1(self):
print("m1 from B")
class C:
def m1(self):
print("m1 from C")
class X(A, B):
def m1(self):
print("m1 from C")
class Y(B, C):
def m1(self):

162
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
print("m1 from A")
class P(X, Y, C):
def m1(self):
print("m1 from P")
print(A.mro())#AO
print(X.mro())#XABO
print(Y.mro())#YBCO
print(P.mro())#PXAYBCO
Output:

Super Function in Python


Super() Function in Python:
super() is a predefined function in python. By using super() function in child
class, we can call,
1. Super class constructor.
2. Super class variables.
3. Super class methods.
Program: Calling super class constructor from child class constructor
using super() (demo16.py)
class A:
def __init__(self):
print("super class A constructor")
class B(A):
def __init__(self):
print("Child class B constructor")
super().__init__()
b=B()
Output:

Which scenarios super() function is required?


When both superclass and child class may have the same method names, same
variable names, some scenarios may come where we want to use both of them.
In such a case, using the super() function we can call the parent class method.
163
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Program: Calling super class method from child class method using super()
(demo17.py)
class A:
def m1(self):
print("Super class A: m1 method")
class B(A):
def m1(self):
print("Child class B: m1 method")
super().m1()
b=B()
b.m1()
Output:

Program: Calling super class variable from child class method using super()
(demo18.py)
class A:
x=10
def m1(self):
print("Super class A: m1 method")
class B(A):
x=20
def m1(self):
print('Child class x variable', self.x)
print('Super class x variable', super().x)
b=B()
b.m1()
Output:

Program: demo19.py

class Person:
def __init__(self, name, age):
self.name=name
self.age=age
def display(self):
print('Name:', self.name)

164
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
print('Age:', self.age)
class Employee(Person):
def __init__(self, name, age, empno, address):
super().__init__(name, age)
self.empno=empno
self.address =address
def display(self):
super().display()
print('Emp No:', self.empno)
print('Address:', self.address)
e1=Employee('Neethu',16,111,"Delhi")
e1.display()
Output:

Different Approaches for Calling method of a specific superclass


We can use the following approaches:
1. NameOfTheClass.methodname(self) – It will call super class method
2. super(NameOfTheClass, self).methodname – It will call the method of
super class of mentioned class name.
Program: NameOfTheClass.methodname(self) (demo20.py)

class A:
def m1(self):
print('m1() method from A class')
class B(A):
def m1(self):
print('m1() method from B class')
class C(B):
def m1(self):
print('m1() method from C class')
class D(C):
def m1(self):
print('m1() method from D class')
class E(D):
def m1(self):

165
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
A.m1(self)
e=E()
e.m1()
Output:
Program: super(NameOfTheClass, self).methodname (demo21.py)

class A:
def m1(self):
print('m1() method from A class')
class B(A):
def m1(self):
print('m1() method from B class')
class C(B):
def m1(self):
print('m1() method from C class')
class D(C):
def m1(self):
print('m1() method from D class')
class E(D):
def m1(self):
#A.m1(self)
super(D, self).m1()
e=E()
e.m1()
Output:
Since using this approach, the super class of specified class will be called, class
C is called. The mentioned class is D and its super class is C.
Different cases for super() function
CASE1:
From a child if we want to access the parent class instance variable then we
should use a self variable only. By using super() function we cannot access
parent class instance variables from child class. But, the class variables can be
accessed which we discussed earlier in demo18.py.
Program: Accessing instance variable using super() (demo22.py)
class P:
def __init__(self):
self.a=20

166
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
class C(P):
def m1(self):
print(super().a)
c=C()
c.m1()

Output:
Program: Accessing instance variable without super() (demo23.py)
class P:
def __init__(self):
self.a=20
class C(P):
def m1(self):
print(self.a)
c=C()
c.m1()
Output:
CASE2:
By using super() function we can access parent class static variables. An
example for this is already shown in demo18.py.
Program: Accessing static variable super() (demo24.py)
class P:
a = 10
def m1(self):
print("m1 from Parent class")
class C(P):
def m2(self):
print(super().a)
c=C()
c.m2()

Output:
CASE3:
From child class constructor, we can access parent class
1. instance method
2. static method
3. class method
Program: demo25.py
class P:
167
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
def __init__(self):
print('Parent class Constructor')
def m1(self):
print('m1() instance method from Parent class')
@classmethod
def m2(cls):
print('m2() class method from Parent class')
@staticmethod
def m3():
print('m3() static method from Parent class')
class C(P):
def __init__(self):
super().__init__()
super().m1()
super().m2()
super().m3()
c=C()
Output:

From child class instance method, we can access parent class


1. instance method
2. static method
3. class method
Program: demo26.py

class P:
def __init__(self):
print('Parent class Constructor')
def m1(self):
print('m1() instance method from Parent class')
@classmethod
def m2(cls):
print('m2() class method from Parent class')
@staticmethod
def m3():
print('m3() static method from Parent class')
168
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
class C(P):
def __init__(self):
print("Child class constructor")
def m1(self):
super().__init__()
super().m1()
super().m2()
super().m3()
c=C()
c.m1()
Output:

CASE4:
By using super() function we cannot access parent class instance method and
constructor from child class, classmethod. In clear terms, “Parent class –
Constructor, Instance Methods” cannot be accessed from “Child class –
ClassMethod”
Program: demo27.py
class P:
def __init__(self):
print('Parent Constructor')
def m1(self):
print('Parent instance method')
@classmethod
def m2(cls):
print('Parent class method')
@staticmethod
def m3():
print('Parent static method')
class C(P):
@classmethod
def m1(cls):
super().__init__()
super().m1()

169
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
C.m1()
Output:

Since we are calling a class method, object creation is not required. We


discussed about this in the class methods topic of previous chapter. So, there is
no object instance for the class, which is by default expected by the constructor
and instance methods. Hence, the error.
CASE5:
By using super() function we can access parent class static method and class
method from child class, class method. In clear terms, “Parent class – Static
Method, Class Method” can be accessed from “Child class – ClassMethod”.
Program: demo28.py
class P:
def __init__(self):
print('Parent Constructor')
def m1(self):
print('Parent instance method')
@classmethod
def m2(cls):
print('Parent class method')
@staticmethod
def m3():
print('Parent static method')
class C(P):
@classmethod
def m1(cls):
super().m2()
super().m3()
C.m1()
Output:

CASE6:
As discussed in case 4, “Parent class – Constructor, Instance Methods” cannot
be accessed from “Child class – ClassMethod”. But there is way to access them.
Program: demo29.py
class P:
def __init__(self):
print('Parent Constructor')
170
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
def m1(self):
print('Parent instance method')
@classmethod
def m2(cls):
print('Parent class method')
@staticmethod
def m3():
print('Parent static method')
class C(P):
@classmethod
def m1(cls):
super(C, cls).__init__(cls)
super(C, cls).m1(cls)
C.m1()
Output:

Polymorphism in Python
What is Polymorphism in Python?
The word ‘Poly’ means many and ‘Morphs’ means forms. The process of
representing “one form in many forms” is called a polymorphism.
Types of Polymorphism in Python:
The following are the examples, or implementations, of polymorphism:
1.Duck Typing Philosophy of Python
2.Overloading
Operator Overloading
Method Overloading
Constructor Overloading
3.Overriding
Method overriding
Constructor overriding
Duck Typing Philosophy of Python
Duck typing refers to the programming style, in which the object passed to a
method supports all the attributes expected from it, at the runtime. The
important thing here is not about the object type, but about what attributes
and methods the object supports.

171
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
In duck typing, while creating a data, it’s not required to declare the argument
type explicitly. At runtime, based on provided value the type will be considered
automatically. Since Python is considered as a Dynamically Typed Programming
Language, it follows Duck Typing.
“If it walks like a duck, swims like a duck, and quacks like a duck, then it
probably is a duck.”
Duck Typing originates from the above saying. For example, let’s consider a
class “Car” which has an attribute ‘engine_name’ and a method ‘start_engine’
which takes the ‘engine_name’ attribute and does the action of starting the
engine. A ‘Truck’ is different from a ‘Car’ but for the duck typing it actually
doesn’t matter. We can create any truck object for the ‘Car’ and use the
‘start_engine’ method to start it.
Program: Duck typing philosophy (demo1.py)

class Duck:
def talk(self):
print("Quack.. Quack")
class Dog:
def talk(self):
print("Bow...Bow")
class Cat:
def talk(self):
print("Moew...Moew ")
def m(obj):
obj.talk()
duck = Duck()
m(duck)
cat = Cat()
m(cat)
dog = Dog()
m(dog)
Output:

In the above program, the function ‘m’ takes an object and calls for the talk()
method of it. With duck typing, the function is not worried about what object
type of object it is. The only thing that matters is whether the object has a
method with name ‘talk()’ supported or not.
Overloading in Python:
We can use the same operator or methods for different purposes. There are 3
types of overloading:

172
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
1. Operator Overloading
2. Method Overloading
3. Constructor Overloading
Operator overloading in Python:
If we use the same operator for multiple purposes, then it is nothing but
operator overloading.
1. ‘+’- addition operator can be used for Arithmetic addition and String
concatenation as well
2. * multiplication operator can be used for multiplication for numbers and
repetition for strings, lists, tuples etc
Program: Operator overloading (demo2.py)
print(10+20)
print("Python" + "Programming")
print([1,2,3]+[4,5,6])
Output:

Program: Operator overloading (demo3.py)


print(10*20)
print("Python"*3)
print([1,2,3]*3)
Output:

Addition Operator (+):


Program: Addition operator in depth understanding (demo4.py)
class Book:
def __init__(self, pages):
self.pages=pages
b1=Book(100)
b2=Book(200)
print(type(b1))
print(type(b2))
print(type(b1.pages))
print(type(b2.pages))
print(b1.pages + b2.pages)
print((b1.pages).__add__(b2.pages))
Output:

173
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training

We defined a class ‘Book’ and two objects ‘b1’ and ‘b2’ to it. We tried adding the
pages attributes, which are integers, of the two objects in two different ways.
One is the general way and the other is using ‘__add__’ method. Whenever we
call for an operation using ‘+’ operator, this __add__ method is called by default.
This is known as the magic method. There are many such magic methods for
many operators.
Program: use + operator for user defined objects (demo5.py)

class Book:
def __init__(self, pages):
self.pages=pages
b1=Book(100)
b2=Book(200)
print(b1 + b2)

Output:
In the above program, we are trying to add two user defined objects ‘b1’ and
‘b2’. The default, __add__ method, which will be called cannot perform the
addition of two such objects. We can override the __add__ method in our class,
in a way that it can act on user defined objects also. Overriding the methods
will allow overloading of the + operator.
Magic Methods
For every operator Magic methods are available. To overload any operator, we
should override that Method in our class. Internally + operator is implemented
by using __add__() method. This method is called magic method for + operator.
Program: Overloading + in our program (demo6.py)
class Book:
def __init__(self, pages):
self.pages=pages
def __add__(self, others):
return self.pages + others.pages
b1=Book(100)
b2=Book(200)
print(b1 + b2)

Output:
List of operators and corresponding magic methods

174
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training

Program: Using less than and greater than symbols on user defined objects
(demo7.py)
class Student:
def __init__(self, name, marks):
self.name=name
self.marks=marks
s1=Student("Samvida", 100)
s2=Student("Surya", 200)
print("s1>s2 =", s1>s2)
print("s1<s2 =", s1<s2)
print("s1<=s2 =", s1<=s2)
print("s1>=s2 =", s1>=s2)
Output:

Program: Overloading operators (demo8.py)

class Student:
def __init__(self, name, marks):
self.name=name
self.marks=marks
def __gt__(self, other):
return self.marks>other.marks
def __lt__(self, other):
175
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
return self.marks<=other.marks
s1=Student("Samvida", 100)
s2=Student("Surya", 200)
print("s1>s2 =", s1>s2)
print("s1<s2 =", s1<s2)
Output:

Method overloading in Python:


If 2 methods have the same name but different types of arguments, then those
methods are said to be overloaded methods.
But in Python Method overloading is not possible. If we are trying to declare
multiple methods with the same name and different number of arguments, then
Python will always consider only the last method.
Program: Methods names same and number of arguments are different
(demo9.py)
class Demo:
def m1(self):
print('no-arg method')
def m1(self, a):
print('one-arg method')
def m1(self, a, b):
print('two-arg method')
d= Demo()
d.m1()
#d.m1(10)
#d.m1(10,20)
Output:

Program: Method Overloading (demo9.py)

class Demo:
def m1(self):
print('no-arg method')
def m1(self, a):
print('one-arg method')
def m1(self, a, b):
print('two-arg method')

176
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
d= Demo()
#d.m1()
d.m1(10)
#d.m1(10,20)

Output:
Program: Method Overloading (demo10.py)
class Demo:
def m1(self):
print('no-arg method')
def m1(self, a):
print('one-arg method')
def m1(self, a, b):
print('two-arg method')
d= Demo()
#d.m1()
#d.m1(10)
d.m1(10,20)
Output:
Conclusion
If we are trying to declare multiple methods with the same name and different
number of arguments, then Python will always consider only the method which
was last declared. In the above program python will consider only the method
with two arguments, the last method.
How we can handle overloaded method requirements in Python
Most of the time, if a method with a variable number of arguments is required
then we can handle it with default arguments or with a variable length of
argument methods.
Program: Default Arguments (demo11.py)

class Demo:
def sum(self, a=None, b=None, c=None):
if a!=None and b!= None and c!= None:
print('The Sum of 3 Numbers:', a + b + c)
elif a!=None and b!= None:
print('The Sum of 2 Numbers:', a + b)
else:
print('Please provide 2 or 3 arguments')
d=Demo()
177
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
d.sum(10,20,30)
d.sum(10,20)
d.sum(10)
Output:

Program: Variable length arguments (demo12.py)


class Demo:
def sum(self, *a):
total=0
for x in a:
total=total+x
print('The Sum:', total)
d=Demo()
d.sum(10,20,30)
d.sum(10,20)
d.sum(10)
Output:

Constructor Overloading in Python:


Constructor overloading is also not possible in Python. If we define multiple
constructors, only the last constructor will be considered.
Program: Constructor overloading (demo13.py)
class Demo:
def __init__(self):
print('No-Arg Constructor')
def __init__(self, a):
print('One-Arg constructor')
def __init__(self, a, b):
print('Two-Arg constructor')
d1=Demo()
#d1=Demo(10)
#d1=Demo(10,20)
Output:

178
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Program: Constructor overloading (demo14.py)
class Demo:
def __init__(self):
print('No-Arg Constructor')
def __init__(self, a):
print('One-Arg constructor')
def __init__(self, a, b):
print('Two-Arg constructor')
#d1=Demo()
d1=Demo(10)
#d1=Demo(10,20)
Output:

Program: Constructor overloading (demo15.py)

class Demo:
def __init__(self):
print('No-Arg Constructor')
def __init__(self, a):
print('One-Arg constructor')
def __init__(self, a, b):
print('Two-Arg constructor')
#d1=Demo()
#d1=Demo(10)
d1=Demo(10,20)
Output:
In the above program only Two-Arg Constructor is available. But based on our
requirement we can declare constructor with default arguments and variable
length arguments.
Program: Constructor with Default Arguments (demo16.py)

class Demo:
def __init__(self,a=None,b=None,c=None):
print(a)
print(b)
print(c)
d1=Demo(10, 20)
Output:
179
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training

Program: Constructor with Variable Length Arguments (demo17.py)


class Demo:
def __init__(self, *a):
print('Constructor with variable number of arguments')
d1=Demo()
d2 = Demo(10)
d3 = Demo(10,20)
d4 = Demo(10,20,30)
d5 = Demo(10,20,30,40,50,60)
Output:

Overriding in Python:
Overriding refers to the process of implementing something again, which
already exists in parent class, in child class.
All the members available in the parent class, those are by-default available to
the child class through inheritance. If the child class is not satisfied with parent
class implementation, then child class is allowed to redefine that method in the
child class based on its requirement. This concept is called overriding.
Overriding concept applicable for both methods and constructors.
Method Overriding in Python:
Program: Method Overriding (demo18.py)
class P:
def properties_status(self):
print('Money, Land, Gold')
def to_marry(self):
print('Anushka')
class C(P):
def study_status(self):
print("Studies done waiting for job")
def to_marry(self):
print('Megha')
c=C()
c.properties_status()
180
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
c.to_marry()
c.study_status()
Output:

Constructor Overriding in Python:


We have already discussed in detail about the constructor concepts in the
inheritance chapter. Those concepts also include overriding concepts. Let’s
remember some points from there:
1. If child class does not have constructor, then parent class constructor
will be executed at the time of child class object creation.
2. If child class has a constructor, then child class constructor will be
executed at the time of child class object creation.
3. From child class constructor we can call parent class constructor by
using super() method
Program: Constructor Overriding (demo19.py)

class Person:
def __init__(self, name, age):
self.name=name
self.age=age
class Employee(Person):
def __init__(self, name, age, eno, esal):
super().__init__(name, age)
self.eno=eno
self.esal=esal
def display(self):
print('Employee Name:', self.name)
print('Employee Age:', self.age)
print('Employee Number:', self.eno)
print('Employee Salary:', self.esal)
e1=Employee('Surabhi', 16, 872425,26000)
e1.display()
e2=Employee('Ranjith',20,872426,36000)
e2.display()
Output:

181
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training

Abstract classes in Python


What is an Abstract Class in Python?
An abstract class is the class which contains one or more abstract methods. An
abstract method is the one which is just defined but not implemented.
The above statements may seem unclear with the new terms. Let’s discuss
them in detail in this article.
Types of Methods in Python:
Based on the implementation the methods can be divided into two types:
1. Implemented methods.
2. Un-implemented method.
Implemented methods:
A method which has a both method name and method body, that method is
called an implemented method. They are also called concrete methods or non-
abstract methods. The methods which we have seen in the previous chapters
are implemented i.e having method name and body as well.
Un-implemented methods:
A method which has only method name and no method body, that method is
called an unimplemented method. They are also called as non-concrete or
abstract methods.
How to declare an abstract method in Python:
Abstract methods, in python, are declared by
using @abstractmethod decorator. For better understanding, please have a
look at the bellow image.

Method ‘one’ is abstract method. Method ‘two’ is non-abstract method. Since


one abstract method is present in class ‘Demo’, it is called Abstract class

182
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Abstract Method in Python
From the above example, we can understand that an abstract class is the one
which does not have implementation. Few points about it:
1. By using @abstractmethod decorator we can declare a method as an
abstract method.
2. @abstractmethod decorator presents in abc module. We should import
the abc module in order to use the decorator.
3. Since abstract method is an unimplemented method, we need to put a
pass statement, else it will result in error.
4. Class which contains abstract methods is called an abstract class.
5. For abstract methods, implementation must be provided in the subclass
of abstract class.
Program: Abstract methods (demo1.py)
from abc import *
class Demo1(ABC):
@abstractmethod
def m1(self):
pass
@abstractmethod
def m2(self):
pass
def m3(self):
print("Implemented method")
Output: No Output because no object is created. Just a demo to show abstract
methods
Abstract Classes in Python:
1. Every abstract class in Python should be derived from the ABC class
which is present in the abc module. Abstract class can contain
Constructors, Variables, abstract methods, non-abstract methods, and
Subclass.
2. Abstract methods should be implemented in the subclass or child class
of the abstract class. (demo2.py)
3. If in subclass the implementation of the abstract method is not provided,
then that subclass, automatically, will become an abstract class.
(demo3.py)
4. Then, if any class is inheriting this subclass, then that subclass should
provide the implementation for abstract methods. (demo4.py)
5. Object creation is not possible for abstract class. (demo4.py or demo8.py)
6. We can create objects for child classes of abstract classes to access
implemented methods.
Program: Abstract Class (demo2.py)
from abc import ABC, abstractmethod
#Abstract Class
183
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
class Bank(ABC):
def bank_info(self):
print("Welcome to bank")
@abstractmethod
def interest(self):
"Abstarct Method"
pass
#Sub class/ child class of abstract class
class SBI(Bank):
def interest(self):
"Implementation of abstract method"
print("In sbi bank 5 rupees interest")
s= SBI()
s.bank_info ()
s.interest()
Output:

In the above example, Bank is an abstract class which having intertest()


abstract method. SBI class is a child class to Bank class, so SBI class should
provide implementation for abstract method which is available in Bank abstract
class. An object is created to subclass, which is SBI, and the implemented
method interest() is called.
If child class misses to provide abstract methods’ implementation
If a child class inherits an abstract class, doesn’t provide the implementation
for abstract methods, then that child class also will be considered as an
abstract class. Object creation for such child classes is also not possible. Even,
if we try to create an object an error will be thrown.
Program: Abstract Class (demo3.py)
from abc import ABC, abstractmethod
#Abstract Class
class Bank(ABC):
def bank_info(self):
print("Welcome to bank")
@abstractmethod
def interest(self):
"Abstarct Method"
pass

184
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
#Sub class/ child class of abstract class
class SBI(Bank):
def balance(self):
print("Balance is 100")
s= SBI()
s.bank_info ()
s.balance()
Output:

In the above example, Bank is an abstract class, which is having an abstract


method intertest(). SBI is a child class to Bank class, so SBI should provide
implementation for abstract method interest() of Bank class, but it is not
providing. So, the class SBI will also be considered as an abstract class.
Hence, if we try to create an object to it, then we will get TypeError. Now, if we
define a class which is inheriting SBI class, there we should provide the
implementation for interest method.
Program: abstract class and subclass of abstract class (demo4.py)

from abc import ABC, abstractmethod


#Abstract Class
class Bank(ABC):
def bank_info(self):
print("Welcome to bank")
@abstractmethod
def interest(self):
"Abstarct Method"
pass
#Sub class/ child class of abstract class
class SBI(Bank):
def balance(self):
print("Balance is 100")
class Sub1(SBI):
def interest(self):
print("In sbi bank interest is 5 rupees")
s= Sub1()
s.bank_info ()
s.balance()
s.interest()

185
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Output:

Abstract class can also contain concrete methods


As discussed abstract class can contains implemented methods also along with
abstract methods. In the above example, bank_info() method is a concrete
method which has implementation along with name in the abstract class.
Program: Abstract class can also contain concrete methods (demo5.py)
from abc import ABC, abstractmethod
#Abstract Class
class Bank(ABC):
def bank_info(self):
print("Welcome to bank")
@abstractmethod
def interest(self):
"Abstarct Method"
pass
def offers(self):
print("Providing offers")
#Sub class/ child class of abstract class
class SBI(Bank):
def interest(self):
print("In SBI bank 5 rupees interest")
s= SBI()
s.bank_info ()
s.interest()
Output:

Can abstract classes contain more subclasses?


Yes, an abstract class can contain more than one subclass. If different child
classes require different kinds of implementations, in that case an abstract
class can contain more than one subclass.
Program: abstract classes contain more subclasses (demo6.py)
from abc import ABC, abstractmethod
#Abstract Class
class Bank(ABC):
def bank_info(self):
186
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
print("Welcome to bank")
@abstractmethod
def interest(self):
"Abstarct Method"
pass
def offers(self):
print("Providing offers")
#Sub class/ child class of abstract class
class SBI(Bank):
def interest(self):
print("In SBI bank 5 rupees interest")
class HDFC(Bank):
def interest(self):
print("In HDFC 7 rupees interest")
s= SBI()
h=HDFC()
s.bank_info()
s.interest()
h.bank_info()
h.interest()
Output:

Program: abstract classes in python (demo7.py)


from abc import ABC, abstractmethod
class One(ABC):
@abstractmethod
def calculate(self, a):
pass
def m1(self):
print("implemented method")
class Square(One):
def calculate(self, a):
print("square: ", (a*a))
class Cube(One):
187
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
def calculate(self, a):
print("cube: ", (a*a*a))
s = Square()
c = Cube()
s.calculate(2)
c.calculate(2)
Output:

Different cases for Abstract class object creation


Case1: If any class is inheriting ABC class, and that class doesn’t contain an
abstract method, then happily we can create an object to that class.
Program: Different cases for Abstract class object creation (demo8.py)
from abc import *
class Demo(ABC):
def m(self):
print("calling")
d=Demo()
d.m()
Output:
Case2: If any class is inheriting ABC class, then that class will become an
abstract class. If that class contains an abstract method, then the object
creation is not possible for abstract class.
Program: Different cases for Abstract class object creation (demo9.py)
from abc import *
class Demo(ABC):
@abstractmethod
def m(self):
pass
def n(self):
print("Implemented method")
t=Demo()
Output:

Case3: If any class is not inheriting ABC class, then we can create an object for
that class even though it contains an abstract method. As per below example,
class not inheriting ABC class, but it contains abstract methods.
Program: Different cases for Abstract class object creation (demo10.py)
from abc import *
188
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
class Demo:
@abstractmethod
def m(self):
pass
def n(self):
print("Implemented method")
t=Demo()
t.m()
t.n()

Output:

Interfaces in Python
What is Interface in Python?
In our previous article, we discussed that an abstract class is a class which
may contain some abstract methods as well as non-abstract methods also.
Imagine there is an abstract class which contains only abstract methods and
doesn’t contain any concrete methods, such classes are called Interfaces.
Therefore, an interface is nothing but an abstract class which can contains only
abstract methods.
Points to Remember:
In python there is no separate keyword to create an interface. We can create
interfaces by using abstract classes which have only abstract methods.
Interface can contain:
1. Constructors
2. Variables
3. abstract methods
4. sub class
As we know, abstract methods should be implemented in the subclass of
interface (Abstract Class). Object creation is not possible for the interface class
(abstract class). We can create objects for the child class of interface to access
implemented methods.
Program: Interface having two abstract methods and one sub class
(demo11.py)
from abc import ABC, abstractmethod
class Bank(ABC):
@abstractmethod
def balance_check(self):
pass
@abstractmethod
189
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
def interest(self):
pass
class SBI(Bank):
def balance_check(self):
print("Balance is 100 rupees")
def interest(self):
print("SBI interest is 5 rupees")
s = SBI()
s.balance_check()
s.interest()
Output:

Program: one interface and two sub classes to that interface (demo12.py)
from abc import *
class DBInterface(ABC):
@abstractmethod
def connect(self):
pass
@abstractmethod
def disconnect(self):
pass
class Oracle(DBInterface):
def connect(self):
print('Connecting to Oracle Database...')
def disconnect(self):
print('Disconnecting to Oracle Database...')
class Sybase(DBInterface):
def connect(self):
print('Connecting to Sybase Database...')
def disconnect(self):
print('Disconnecting to Sybase Database...')
dbname=input('Enter Database Name either Oracle or Sybase:')
classname=globals()[dbname]
x=classname()

190
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
x.connect()
x.disconnect()
Output:

The globals()[str] is a predefined function, it will convert the string ‘str’ into a
class name and returns the classname.
When should we go for interfaces?
Since, Interfaces will not contain implemented methods, when we don‟t know
anything about implementation of requirements, then we should go for
interfaces.
When should we go for abstract class?
An abstract class is a class which can contains few implemented methods and
few unimplemented methods as well. When we know about requirements
partially, but not completely, then we should go for abstract class.
When should we go for concrete class?
Concrete class is a class which is fully implemented. It contains only
implemented methods. When we know complete implementation about
requirements, then we should go for concrete class.
Useful Information:
__str__() method:
This is one of the magical methods. Whenever we are trying to print any object
reference internally, then this method will be called. It returns output, about
the location of the object, in the string format as shown in the example below.
Program: __str__ method example in python (demo13.py)
class Student:
def __init__(self, name, rollno):
self.name=name
self.rollno=rollno
s1=Student('Ram',10)
s2=Student('Rahim' ,12)
print(s1)
print(s2)
Output:

We can override the __str__ method in our class, to return a meaningful string
whenever we are trying to print an object.
Program: Overriding __str__ method example in python (demo14.py)
class Student:

191
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
def __init__(self, name, rollno):
self.name=name
self.rollno=rollno
def __str__(self):
return 'This is Student object with name {} and roll no
{}'.format(self.name, self.rollno)
s1=Student('Ram',10)
s2=Student('Rahim' ,12)
print(s1)
print(s2)
Output:

Exception Handling in Python

Exception Handling in Python with


Examples
Types of Error:
In any programming language there are 2 types of errors possible. They are:
1. Syntax Errors
2. Runtime Errors
Syntax Errors
The errors which occur because of invalid syntax are called syntax errors.
Program: Syntax Error (demo1.py)
x=123
if x==123
print("Hello")

Output:
Here we missed to place a colon in the if condition, which is violating the
syntax. Hence, syntax error.
Program: Syntax Error (demo2.py)
print(‘hello’
Output:
The programmer is responsible to correct these syntax errors. Once all syntax
errors are corrected then only program execution will be started.

192
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Runtime Errors
While executing the program if something goes wrong then we will get Runtime
Errors. They might be caused due to,
1. End user input
2. Programming logic
3. Memory problems etc.
Such types of errors are called exceptions.
Program: Runtime Error (demo3.py)
print(10/0)
Output:
Program: Runtime Error (demo4.py)
print(10/”two”)
Output:
Program: Runtime Error (demo4.py)
x=int(input("Enter Number:"))
print(x)
Output:

Note: Exception Handling concept applicable for Runtime Errors but not for
syntax errors.
Normal Flow of Program Execution:
In a program if all statements are executed as per the conditions, successfully
and we get output then that flow is called as normal flow of the execution.
Below program will get executed successfully from starting to ending.
Program: Normal Flow (demo5.py)
print('One')
print('Two')
print('Three')
print('Four')
print('Five')
Output:

Abnormal Flow of Program Execution:


While executing statements in a program, if any error occurs at runtime then
immediately program flow gets terminated abnormally, without executing the

193
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
other statements. This kind termination is called an abnormal flow of the
execution.
Program: Abnormal flow (demo6.py)
print('One')
print('Two')
print(10/0)
print('Four')
print('Five')
Output:

Above program terminated in the middle where run time error occurred. As
discussed, if runtime error occurs it won’t execute remaining statements.
What is an Exception?
An unwanted or unexpected event which disturbs the normal flow of the
program is called exception. Whenever an exception occurs, then immediately
program will terminate abnormally. In order to get our program executed
normally, we need to handle those exceptions on high priority.
Exception Handling in Python:
Exception handling does not mean repairing or correcting the exception.
Instead, it is the process in which we define a way, so that the program doesn’t
terminate abnormally due to the exceptions.
Default Exception Handing in Python:
In python, for every exception type, a corresponding class is available and every
exception is an object to its corresponding class. Whenever an exception occurs,
Python Virtual Machine (PVM) will create the corresponding exception object
and will check for handling code.
If handling code is not available, then Python interpreter terminates the
program abnormally and prints corresponding exception information to the
console. The rest of the program won’t be executed.

194
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Exception Hierarchy:

Note: Every Exception in Python is a class. The BaseException class is the root
class for all exception classes in python exception hierarchy and all the
exception classes are child classes of BaseException. The Programmers need to
focus and understand clearly the Exception and child classes.
How to Handle Exception in Python?
Using try except statements we can handle exception in python.
try block: try is a keyword in python. The code which may or expected to raise
an exception, should be written inside the try block.
except block: except is a keyword in python. The corresponding handling code
for the exception, if occured, needs to be written inside the except block.
Syntax:

How it works?
If the code in the try block raises an exception, then only execution flow goes to
the except block for handling code. If there is no exception raised by the code in
the try block, then execution flow won’t go to the except block.
Program: Handling exception by using try and except (demo7.py)

195
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
print('One')
print('Two')
try:
print(10/0)
except ZeroDivisionError:
print("Exception passed")
print('Four')
print('Five')
Output:

Let’s see how the execution flow is, in different scenarios using ‘try except’
Case1:
In our program if there is no exception, then should be normal flow with normal
termination. In this case, the except block won’t execute.
Program: without Exception (demo8.py)
print('One')
print('Two')
try:
print(10/2)
print("No Exception")
except ZeroDivisionError:
print("Exception passed")
print('Four')
print('Five')
Output:

Case 2:
In our program if an exception occurs before the try block then the program
terminates abnormally. Only the code inside the try block will be checked for
the exception and its handling code. But, if there is any exception for the code
before the try block, then abnormal termination
Program: program terminates abnormally (demo9.py)

196
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
print(10/0)
try:
print(10/2)
print("No Exception")
except ZeroDivisionError:
print("Exception passed")
print('Four')
print('Five')

Output:
Case 3:
If the code inside the try block raises an exception, then execution flow goes to
the except block. In the except block we should have handling for the
corresponding exception occurred, only then the except block will execute
leading to normal termination.
Program: demo10.py
print('One')
print('Two')
try:
print(10/0)
print("No Exception")
except ZeroDivisionError:
print("Exception passed")
print('Four')
print('Five')
Output:

Case 4:
If the code inside the try block raises an exception, then execution flow goes to
the except block. In the except block we should have handling for the exception
other than what occurred in the try block, then the except block will not
execute leading to abnormal termination.
Program: demo11.py
try:
print(10/0)
print("No Exception")

197
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
except TypeError:
print("Exception passed")
print('Four')
print('Five')
Output:
Case 5:
If there are 3 lines of code inside the try block and an exception is raised when
executing the first line, then execution flow goes to the except block without
executing the remaining two lines.
Program: demo12.py
try:
print(10/0)
print("line 2")
print("line 3")
print("No Exception")
except ZeroDivisionError:
print("Exception passed")
print('Four')
print('Five')
Output:

Case 6:
If an exception is raised inside the try block, and the execution goes to the
except block. If the code inside the except block also raises an exception then it
leads to abnormal termination
Program: demo13.py
try:
print(10/0)
print("No Exception")
except ZeroDivisionError:
print(10/0)
print('Four')
print('Five')
Output:

198
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training

Case 7:
If an exception is raised inside the try block, and the execution goes to the
except block. After the execution of the code inside the except block, the
execution comes out of it and continues with the other statements that follow. If
any exceptions occurs, when executing those following statements, then it leads
to abnormal termination.
Program: demo14.py
try:
print(10/0)
except ZeroDivisionError:
print("Exception passed")
print(10/0)
print('Four')
print('Five')
Output:

Printing Exception Information in Python:


In the above examples, in the exception handling code, we are printing our
custom message like “Exception passed” etc. Rather than that, we can also
print exception information by creating a reference to the exception.
Program: Printing exception information (demo15.py)
try:
print(10/0)
except ZeroDivisionError as z:
print("Exception information:", z)

Output:
try with multiple except Blocks in python:
In python, try with multiple except blocks are allowed. Sometimes, there may
be the possibility that a piece of code can raise different exceptions in different
cases. In such cases, in order to handle all the exceptions, we can use multiple
199
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
except blocks. So, for every exception type a separate except block we have to
write.
Syntax:

Program: try with Multiple except Blocks (demo16.py)


try:
x=int(input("Enter First Number: "))
y=int(input("Enter Second Number: "))
print(x/y)
except ZeroDivisionError:
print("Can't Divide with Zero")
except ValueError:
print("please provide int value only")
Output1:

Output2:

Output3:

Output4:

ONE except BLOCK – MULTIPLE EXCEPTIONS


Rather than writing different except blocks for handling different exceptions, we
can handle all them in one except block. The only thing is we will not have the
flexibility of customizing the message for each exception. Rather, we can take
the reference to the exception and print its information as shown in one of the
examples above.
Syntax:

200
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training

Parenthesis are mandatory, and this group of exceptions is internally


considered as tuple.
Program: single except block handling multiple exceptions (demo17.py)
try:
x=int(input("Enter First Number: "))
y=int(input("Enter Second Number: "))
print(x/y)
except (ZeroDivisionError,ValueError) as e:
print("Please Provide valid numbers only and problem is: ", e)
Output1:

Output2:

Output3:

Output4:

Default except Block in Python:


We can use default except block to handle any type of exceptions. It’s not
required to mention any exception type for the default block. Whenever we don’t
have any idea of what expectation the code could raise, then we can go for
default except block.
We know that we can have multiple except blocks for a single try block. If the
default except block is one among those multiple ones, then it should be at last,
else we get SyntaxError.
Program: Default except block (demo18.py)
try:
x=int(input("Enter First Number: "))
y=int(input("Enter Second Number: "))
print(x/y)
except ZeroDivisionError:
print("ZeroDivisionError: Can't divide with zero")
201
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
except:
print("Default Except: Please provide valid input only")
Output1:

Output2:

Program: Default block (demo19.py)


try:
x=int(input("Enter First Number: "))
y=int(input("Enter Second Number: "))
print(x/y)
except:
print("Default Except: Please provide valid input only")
except ZeroDivisionError:
print("ZeroDivisionError: Can't divide with zero")

Output:

Finally Block in Python


Why we need Finally Block?
In any project after completing the tasks, it is recommended to destroy all the
unwanted things that are created for the completion of the task. For example, if
I have opened a database connection in my code and done some tasks related
to the database. After the tasks are completed, it is recommended to close the
connection. These clean-up activities are very important and should be handled
in our code.
finally Block in Python:
finally is a keyword in python which can be used to write a finally block to do
clean-up activities.
Why not ‘try except’ block for clean-up activities?
try block: There is no guarantee like every statement will be executed inside
the try block. If an exception is raised at the second line of code in the try block
at, then the remaining lines of code in that block will not execute. So, it is not
recommended to write clean up code inside the try block.
except block: There is no guarantee that an except block will execute. If there
is no exception then except block won’t be executed. Hence, it is also not
recommended to write clean up code inside except block
202
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Conclusion:
So, a separate block is required to write clean-up activities. This block of code
should always execute irrespective of the exceptions. If no exception, then
clean-up code should execute. If an exception is raised and is also handled ,
then also clean-up code should execute. If an exception is raised, but not
handled, then also clean-up code should execute.
All the above requirements, which can’t be achieved by try except block, can be
achieved by finally block. The finally block will be executed always, irrespective
of the exception raised or not, exception handled or not.
Case 1: If there is no exception, then finally block will execute
Program: demo20.py
try:
print("try block")
except:
print("except block")
finally:
print("finally block")
Output:

Case 2: If an exception is raised and handled with except block, then also
finally block will be executed
Program: demo21.py
try:
print("try block")
print(10/0)
except ZeroDivisionError:
print("except block")
finally:
print("finally block")
Output:

Case 3: If an exception raised inside try block but except block doesn’t
handle that particular exception, then also finally block will be executed.
Program: demo22.py
try:
print("try block")
print(10/0)
except NameError:
203
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
print("except block")
finally:
print("finally block")
Output:

If an exception is raised but is not handled, then program supposed to


terminate abnormally. But before terminating, the finally block will be executed.
Different control flow cases of try except finally in python:
Case 1:
If there is no exception, then try and finally blocks will execute and except block
won’t execute, leading to normal termination.
Program: demo23.py
print("One")
print("Two")
try:
print("try block")
except ZeroDivisionError:
print("except block: Handling code")
finally:
print("finally block: clean-up activities")
print("Four")
Output:

Case 2:
If an exception is raised inside the try block and the except block is handling
that corresponding exception then try, except and finally blocks will execute,
leading to normal termination.
Program: demo24.py
print("One")
print("Two")
try:
print("try block")
print(10/0)
204
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
except ZeroDivisionError:
print("except block: Handling code")
finally:
print("finally block: clean-up activities")
print("Four")
Output:

Case 3:
If an exception is raised inside the try block and the except block is not
handling that corresponding exception then try and finally blocks will execute,
leading to abnormal termination.
Program: demo25.py
print("One")
print("Two")
try:
print("try block")
print(10/0)
except NameError:
print("except block: Handling code")
finally:
print("finally block: clean-up activities")
print("Four")
Output:

In the above program, since it’s is abnormal termination, the print statement
after (print(“Four”)) the finally block didn’t get executed.
Case 4:
If an exception is raised inside the try block, then flow goes to the except block.
And in the except block, assume, the particular exception is handled. Instead of
handling exceptions, if the block itself raises another exception then the
program will terminate abnormally. In this case also, before the program
termination finally block will be executed.
205
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Program: demo26.py
print("One")
print("Two")
try:
print("try block")
print(10/0)
except ZeroDivisionError:
print(10/0)
finally:
print("finally block: clean-up activities")
print("Four")
Output:

Case 5:
If an exception is raised inside the finally block, then it’s always abnormal
termination.
Program: demo27.py
print("One")
print("Two")
try:
print("try block")
print(10/0)
except ZeroDivisionError:
print("except block: Handling code")
finally:
print(10/0)
print("Four")
Output:

206
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training

Nested try-except-finally blocks in Python


Nested try-except-finally blocks in Python
In python nested try except finally blocks are allowed. We can take try-except-
finally blocks inside try block. We can take try-except-finally blocks inside
except block. We can take try-except-finally blocks inside finally block
Different cases and scenarios
Case 1: If no exception raised then outer try, inner try, inner finally, outer
finally blocks will get executed
Program: demo28.py
try:
print("outer try block")
try:
print("Inner try block")
except ZeroDivisionError:
print("Inner except block")
finally:
print("Inner finally block")
except:
print("outer except block")
finally:
print("outer finally block")
Output:

Case 2:
If an exception is raised in an outer try, then outer except blocks are
responsible to handle that exception.
Program: demo29.py
try:
207
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
print("outer try block")
print(10/0)
try:
print("Inner try block")
except ZeroDivisionError:
print("Inner except block")
finally:
print("Inner finally block")
except:
print("outer except block")
finally:
print("outer finally block")
Output:

Case 3:
If an exception raised in inner try block then inner except block is responsible
to handle, if it is unable to handle then outer except block is responsible to
handle.
Program: Exception handled by inner except block (demo30.py)
try:
print("outer try block")
try:
print("Inner try block")
print(10/0)
except ZeroDivisionError:
print("Inner except block")
finally:
print("Inner finally block")
except:
print("outer except block")
finally:
print("outer finally block")
Output:

208
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training

Program: Exception handled by outer except block (demo31.py)


try:
print("outer try block")
try:
print("Inner try block")
print(10/0)
except NameError:
print("Inner except block")
finally:
print("Inner finally block")
except:
print("outer except block")
finally:
print("outer finally block")
Output:

Else Block in Python:


We can use else blocks with try-except-finally blocks. The else block will be
executed if and only if there are no exceptions inside the try block.
Note: If no exception then try, else and finally blocks will get executed. If an
exception is raised inside the try block, then the except block will get executed
but the else block won’t.
Program: else block (demo32.py)
try:
print("try block")
except:
print("except: Handling code")
else:
print("else block")
finally:
print("finally block")

209
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Output:

Program: else block (demo33.py)


try:
print("try block")
print(10/0)
except:
print("except: Handling code")
else:
print("else block")
finally:
print("finally block")
Output:

Possible Combinations with try-except-else-finally


Only try block is invalid, only except block is invalid, only finally block is invalid
Program: only try block (demo33.py)
try:
print("try block")

Output:
Program: only except block (demo34.py)
except:
print("except: Handling code")

Output:
Program: Only Finally block (demo35.py)
finally:
print("finally block")

Output:
Note:
1. try with except combination is valid → try block follows except block
2. try with finally combination is valid → try block follows finally block
3. try, except and else combination is valid → try, except blocks follows else
block
Program: try with except combination (demo36.py)
try:
210
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
print("try block")
except:
print("except: Handling code")
Output:
Program: try with finally combination (demo37.py)
try:
print("try block")
finally:
print("finally block")
Output:

Program: try, except and else combination (demo38.py)


try:
print("try block")
except:
print("except: Handling code")
else:
print("else block")
Output:

Custom Exception in Python


Predefined Exceptions in Python
The exceptions which we handled in the examples till now are predefined ones.
They are already available builtin exceptions. If any exception occurs, then
Python Virtual Machine will handle those exceptions using the predefined
exceptions. Examples of predefined exceptions are ZeroDivisionError,
ValueError, NameError etc.
Custom Exceptions in Python:
Sometimes based on project requirement, a programmer needs to create his
own exceptions and raise explicitly for corresponding scenarios. Such types of
exceptions are called customized Exceptions or Programmatic Exceptions. We
can raise a custom exception by using the keyword ‘raise’.

211
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Steps to create Custom Exception in python:
The first step is to create a class for our exception. Since all exceptions are
classes, the programmer is supposed to create his own exception as a class.
The created class should be a child class of in-built “Exception” class.
Syntax

In the second step raise the exception where it required. When the programmer
suspects the possibility of exception, then he can raise his own exception using
raise keyword
Syntax:

Program: Creating Custom Exception in Python (demo39.py)

class NegativeError(Exception):
def __init__(self, data):
self.data = data
try:
x = int(input("Enter a number between positive integer: "))
if x < 0:
raise NegativeError(x)
except NegativeError as e:
print("You provided {}. Please provide positive integer values
only".format(e))
Output:

Program: Custom Exceptions in Python (demo40.py)

class TooYoungException(Exception):
def __init__(self, arg):
self.msg=arg
class TooOldException(Exception):
def __init__(self, arg):
self.msg=arg
age=int(input("Enter Age:"))
if age>60:

212
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
raise TooOldException("Your age already crossed marriage age...no
chance of getting marriage")
elif age<18:
raise TooYoungException("Plz wait some more time you will get best
match soon!!!")
else:
print("You will get match details soon by email!!!")
Output:

Files in Python
What is a File?
A file is a resource to store data. As part of the programming requirement, we
may have to store our data permanently for future purpose. For this
requirement we should go for files. Files are very common permanent storage
areas to store our data.
Types of Files:
There can be two types of files based on the type of information they store. They
are:
1. Text files
2. Binary files
Text files: Text files are those which store data in the form of characters or
strings.
Binary files: Binary files are those which store entire data in the form of bytes,
i.e a group of 8 bits each. While retrieving data from the binary file, the
programmer can retrieve it in the form of bytes. Binary files can be used to
store text, images, audio and video.
File Modes:
Before going into details of how to do operation on files in python, let’s
understand about some modes which are required to work with them.

213
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training

Note: All the modes in the table are applicable for text files. For binary files, the
above modes need to be suffixed with ‘b’. For example, rb, wb, ab, r+b, w+b,
a+b, xb.
Opening a File in Python:
Before performing any operation (like read or write or append) on the file, first
we must open that file programmatically. In order to open the file, we have a
predefined function open()in python. At the time of opening a file, we must
specify the mode(one mode from the above table), which represents the purpose
of opening a file.
Syntax: f = open(filename, mode)
When we execute the above command with proper filename and mode, then a
file object will be returned, which we are storing in variable ‘f’. Operation
performed on file object is the operation performed on file.
Closing a File in Python:
After completing our operations on the file, it is highly recommended to close
the file programmatically. For this we have a predefined function close().
Syntax: f.close()
Properties of File Object in Python:
The file object which we get when we open a file has many predefined methods
which can be called to get the information about the file and the mode.
1. f.name → Name of opened file mode
2. f.mode → Mode in which the file is opened
3. f.closed → Returns a boolean value whether the file is closed or not
4. f.readable() → Returns a boolean value whether the file is readable or not
5. f.writable() → Returns a boolean value whether the file is writable or not
Program: Opening and closing a file in Python (demo1.py)

f=open("abc.txt", 'w')
print("File Name: ", f.name)
214
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
print("File Mode: ", f.mode)
print("Is File Readable: ", f.readable())
print("Is File Writable: ", f.writable())
print("Is File Closed : ", f.closed)
f.close()
print("Is File Closed : ", f.closed)
Output:

An empty file created with the name of abc.txt will be created in current
directory after executing the above code.
Writing data to a File in Python:
We can write character data to the text files by using the following 2 methods:
1. write(str)
2. writelines(str)
Program: Writing data into file in python (demo2.py)

f=open("wish.txt", 'w')
f.write("Welcome\n")
f.write("to\n")
f.write("python world\n")
print("Data written to the file successfully")
f.close()

Output:
File Content: wish.txt
Welcome
to
python world
Appending Content
In the above program, data present in the file will be overridden every time if
we run the program. Instead of overriding, if we want append the data then we
should open the file in append mode as follows:
Syntax: f = open(“wish.txt”, “a”)
Program: Appending content (demo3.py)
f=open("wish.txt", 'a')
f.write("Welcome\n")

215
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
f.write("to\n")
f.write("python world\n")
print("Data written to the file successfully")
f.close()

Output:
File Content: wish.txt
Welcome
to
python world
Welcome
to
python world
While writing data using the write() method, the data will be written in a single
line(demo3.py). If we want the data in different lines (demo4.py) then we need to
use a separator(\n).
Program: Appending content in new line (demo4.py)

f=open("wish.txt", 'a')
f.write("Welcome ")
f.write("to ")
f.write("python world")
print("Data written to the file successfully")
f.close()

Output:
File Content: wish.txt
Welcome
to
python world
Welcome
to
python world
Welcome to python world
Writelines(argument) method in python:
We can write lines of text into the file by using writelines method
Program: writelines method (demo5.py)
f=open("names.txt", 'w')

216
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
list=["Ramesh\n" ,"Arjun\n", "Senthil\n", "Vignesh"]
f.writelines(list)
print("List of lines written to the file successfully")
f.close()

Output:
File names.txt:
Ramesh
Arjun
Senthil
Vignesh
Reading data From a File in Python:
We can read character data from text file by using the following read methods:
1. read() → To read total data from the file.
2. read(n) → To read ‘n’ characters from the file.
3. readline() → To read only one line.
4. readlines() → To read all lines into a list.
File abc.txt content
Hello everyone!!
This topic is very important
Please don't sleep
Once this topic done
Then happily you can sleep
Thanks for cooperating
Program: read() method (demo6.py)

f=open("abc.txt", 'r')
data=f.read()
print(data)
f.close()
Output:

Program: read(n) method (demo7.py)

f=open("abc.txt", 'r')
data=f.read(20)
217
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
print(data)
f.close()
Output:

Readline() method in Python:


By using readline() we can read line by line from file
Program: readline() method (demo8.py)
f=open("abc.txt", 'r')
line1=f.readline()
print(line1, end='')
line2=f.readline()
print(line2, end='')
line3=f.readline()
print(line3, end='')
f.close()
Output:

Readlines() method in python:


By using readlines() method we can read all lines
Program: readlines() method (demo9.py)
f=open("abc.txt", 'r')
lines=f.readlines()
for line in lines:
print(line, end='')
f.close()
Output:

218
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
With Keyword in Python:
with is a keyword in python. This keyword can be used while opening a file. We
can use this to group file operation statements within a block.
Advantage of with Keyword:
Earlier, we discussed that, when we open a file programatically, it needs to
closed after doing the operations. The advantage of this ‘with’ keyword is that it
will take care of closing the file. After completing all operations automatically
even in the case of exceptions also, and we are not required to close explicitly.
Program: with keyword in python (demo10.py)
with open("test.txt", "w") as f:
f.write("Welcome\n")
f.write("to\n")
f.write("Python\n")
print("Is File Closed: ", f.closed)
print("Is File Closed: ", f.closed)
Output:

File: test.txt
Welcome
to
Python
Seek and Tell Methods in Python:
tell() method:
We can use the tell() method to return the current position of the cursor(file
pointer) from the beginning of the file. The position(index) of the first character
in files starts from zero just like string index.
File: test.txt
Welcome
to
Python
Program: tell method in Python (demo11.py)

f=open("test.txt", "r")
print(f.tell())
print(f.read(2))
print(f.tell())
print(f.read(3))
print(f.tell())
219
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Output:

Seek() method in python:


We can use seek() method to move cursor(file pointer) to specified location. For
this method we need to provide two arguments: offset, fromwhere. The second
argument is optional.
Syntax: f.seek(offset, fromwhere)
Here, offset represents the number of positions and The allowed values for
second arguments are:
1. 0 —> From beginning of file (default value)
2. 1—->From current position
3. 2 —> From end of the file
Program: seek method (demo12.py)

data="SampurneshBabu movie is excellent"


f=open("abc.txt", "w")
f.write(data)
with open("abc.txt", "r+") as f:
text=f.read()
print(text)
print("The Current Cursor Position: ",f.tell())
f.seek(24)
print("The Current Cursor Position: ",f.tell())
f.write("Britania Bisket")
f.seek(0)
text=f.read()
print("Data After Modification:")
print(text)
Output:

Checking for the existence of a file in Python:


In python, we have a module named ‘os’ which can be used to get information
about files in our computer. The ‘os’ module has submodule ‘path’, which
contains isfile() function to check whether a particular file exists or not
Syntax: os.path.isfile(fname)

220
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Program: Checking for the existence of a file in Python (demo13.py)
import os, sys
fname=input("Enter File Name: ")
if os.path.isfile(fname):
print("File exists:", fname)
f=open(fname, "r")
else:
print("File does not exist:", fname)
sys.exit(0)
print("The content of file is:")
data=f.read()
print(data)
Output:

sys.exit(0)
sys.exit(0) can be used to exit the system without executing the rest of the
program. The argument represents status code and 0 means normal
termination and it is the default value.
Program to print the number of lines, words and characters present
in the given file

import os, sys


fname=input("Enter File Name: ")
if os.path.isfile(fname):
print("File exists:", fname)
f=open(fname, "r")
else:
print("File does not exist:", fname)
sys.exit(0)
lcount=wcount=ccount=0
for line in f:
lcount=lcount+1
ccount=ccount+len(line)
words=line.split()
wcount=wcount+len(words)
221
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
print("The number of Lines:", lcount)
print("The number of Words:", wcount)
print("The number of Characters:", ccount)
Output:

Working with binary files in Python


Working with binary files in Python:
It is very common requirement to read or write binary data like images, video
files, audio files etc.
Program: Binary data (demo14.py)
f1=open("thor.jpeg", "rb")
f2=open("newpic.jpeg", "wb")
bytes=f1.read()
f2.write(bytes)
print("New Image is available with the name: newpic.jpg")

Output:
Working with csv files in Python
Csv means Comma separated values. As the part of programming, it is a very
common requirement to write and read data wrt csv files. Python provides a csv
module to handle csv files.
Program: CSV Files (demo15.py)
import csv
with open("emp.csv", "w", newline='') as f:
w=csv.writer(f)
w.writerow(["EMP NO","EMP NAME","EMP SAL","EMP ADDR"])
n=int(input("Enter Number of Employees:"))
for i in range(n):
eno=input("Enter Employee No:")
ename=input("Enter Employee Name:")
esal=input("Enter Employee Salary:")
eaddr=input("Enter Employee Address:")

222
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
w.writerow([eno, ename, esal, eaddr])
print("Total Employees data written to csv file successfully")
Output:

File: emp.csv content

ZIPPING and UNZIPPING Files in Python:


It is a very common requirement to zip and unzip files. The main advantages
are:
1. To improve memory utilization
2. We can reduce transfer time
3. We can improve performance.
To perform zip and unzip operations, Python contains one in-bulit module
‘zipfile’. This module contains a class ZipFile which we are going to use in the
examples.
Creating a ZipFile in Python:
We have to create an object to the ZipFile class with the name which we want to
give to the zip file, and the mode and a constant ZIP_DEFLATED. This constant
represents we are creating a zip file.
Syntax: f = ZipFile(“files.zip”, “w”, “ZIP_DEFLATED”)
Once we are done with creating ZipFile object, we can add files by using write()
method f.write(filename)
Program: Zip file in Python(demo16.py)
from zipfile import *
f=ZipFile("files.zip", 'w', ZIP_DEFLATED)
f.write("abc.txt")
f.write("thor.jpeg")
f.write("names.txt")
f.close()
print("files.zip file created successfully")
Output:

223
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
You can now check the current directory for the file with name ‘file.zip’ and it
will be there.
To perform unzip operation in Python:
We need to create an object in the same way as we did for zipping the file. But
the argument values here are different.
f = ZipFile(“files.zip”, “r”, ZIP_STORED)
ZIP_STORED represents unzip operation. This is the default value and hence it
will be okay even if we haven’t specified.
Once we created ZipFile object for unzip operation, we can get all file names
present in that zip file by using namelist() method
Program: Unzipping in Python(demo17.py)
from zipfile import *
f=ZipFile("files.zip", 'r', ZIP_STORED)
names=f.namelist()
for name in names:
print( "File Name: ",name)
Output:

Working with Directories in Python:


When working with file system, the common requirements other than
operations on the file, we come through are:
1. To know current working directory
2. To create a new directory
3. To remove an existing directory
4. To rename a directory
5. To list contents of the directory etc…
To achieve the above requirements, in python, we can use the ‘os’ module. It
contains several functions to perform directory related operations.
Program: OS Module Example (demo18.py)
import os
cwd=os.getcwd()
print("Current Working Directory:" ,cwd)

Output:
Program: Working with Directories in Python (demo19.py)

import os
os.mkdir("mysub")
print("mysub directory created in current working directory")

Output:

224
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
You can now check for a folder with name ‘sub1’ in your current working
directory
Program: Create multiple directories in Python (demo20.py)

import os
os.makedirs("sub1/sub2/sub3")
print("sub1 and in that sub2 and in that sub3 directories created")

Output:
Program: Removing a Directory in Python (demo21.py)

import os
os.rmdir("mysub")
print("mysub2 directory deleted")
Output:
Program: Removing all Directories in Python (demo22.py)
import os
os.removedirs("sub1/sub2/sub3")
print("All 3 directories sub1,sub2 and sub3 removed")
Output:
Pickling and Unpickling in Python:
Sometimes we have to write the total state of the object to the file and we have
to read the total object from the file. The process of writing the state of an object
to the file is called pickling and the process of reading the state of an object
from the file is called unpickling.
We can implement pickling and unpickling by using the pickle module of
Python. Pickle module contains a dump() function to perform pickling and
pickle module contains load() function to perform unpickling
pickle.dump(object, file)
obj=pickle.load(file)
Program: Pickling and Unpickling in Python (demo23.py)

import pickle
class Employee:
def __init__(self, eno, ename, esal, eaddr):
self.eno=eno
self.ename=ename
self.esal=esal
self.eaddr=eaddr
def display(self):
print(self.eno,"\t", self.ename,"\t", self.esal,"\t",self.eaddr)

225
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
with open("emp.dat","wb") as f:
e=Employee(100,"Nireekshan",1000,"Hyd")
pickle.dump(e,f)
print("Pickling of Employee Object completed...")
with open("emp.dat","rb") as f:
obj=pickle.load(f)
print("Printing Employee Information after unpickling")
obj.display()
Output:

Regular Expressions in Python


What are Regular Expressions?
A regular expression is a sequence of characters that define a search pattern in
theoretical computer science and formal language.
When should we choose Regular Expressions in Python?
If we want to represent a group of Strings according to a particular
format/pattern then we should go for Regular Expressions. Regular Expression
is a declarative mechanism to represent a group of Strings according to a
particular format/pattern.
Example 1: We can write a regular expression to represent all mobile numbers
Example 2: We can write a regular expression to represent all mail ids.
Application areas of Regular Expressions
1. To develop validation frameworks/validation logic.
2. To develop Pattern matching applications (ctrl-f in windows, grep in
UNIX, etc)
3. To develop Translators like compilers, interpreters, etc
4. To develop digital circuits
5. To develop communication protocols like TCP/IP, UDP, etc
We can develop Regular Expression Based applications by using the python
module: re. This module contains several inbuilt functions to use Regular
Expressions very easily in our applications.
compile():
re module contains a compile() function to compile a pattern into RegexObject.
It returns a pattern object, if the pattern is valid, which can be used for
searching.
pattern_obj = re.compile(“<pattern>”)

226
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
finditer():
This method when called upon the pattern object will return an Iterator object,
which yields Match object for every Match.
matcher = pattern_obj.finditer(<string to be searched for match>)
Program: importing re module and working with methods (demo1.py)

import re
count=0
pattern=re.compile("ab")
matcher=pattern.finditer("abaababa")
for match in matcher :
count+=1
print(match.start(),"...",match.end(),"...", match.group())
print("The number of occurrences: ", count)
Output

Note:
1. start(): This method when called on the match object will returns the
start index of the match.
2. end(): This method when called on the match object will return end+1
index of the match.
3. group(): This method will return the matched string
Note: Instead of creating a pattern object and then searching for a pattern, we
can directly pass patterns as arguments to finditer() function.
matcher = re.finditer(<pattern>, <string to be searched for match>)
Program: pattern as arguments to finditer() function (demo2.py)

import re
count=0
matcher=re.finditer("ab", "abaababa")
for match in matcher :
count+=1
print(match.start(),"...",match.end(),"...", match.group())
print("The number of occurrences: ", count)
Output:

227
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training

CHARACTER CLASSES:
We can use character classes to search for a group of characters

Program: Character Classes (demo3.py)


import re
matcher=re.finditer("[abc]","a7b@k9z")
for match in matcher :
print(match.start(),"......",match.group())
Output

Program: demo4.py

import re
matcher=re.finditer("[^abc]","a7b@k9z")
for match in matcher :
print(match.start(),"......",match.group())
Output

Program: demo5.py

import re
matcher=re.finditer("[a-z]","a7b@k9z")
for match in matcher :
print(match.start(),"......",match.group())
228
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Output

Program: demo6.py

import re
matcher=re.finditer("[0-9]","a7b@k9z")
for match in matcher:
print(match.start(),"......",match.group())
Output

Program: demo7.py

import re
matcher=re.finditer("[a-zA-Z0-9]","a7b@k9z")
for match in matcher:
print(match.start(),"......",match.group())
Output

Program: demo8.py

import re
matcher=re.finditer("[^a-zA-Z0-9]","a7b@k9z")
for match in matcher:
print(match.start(),"......",match.group())

Output:
Predefined Character classes in Python:

229
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Program: demo9.py
import re
matcher=re.finditer("\s","a7b @k9z")
for match in matcher:
print(match.start(),"......",match.group())

Output:
Program: demo10.py

import re
matcher=re.finditer("\S","a7b @k9z")
for match in matcher:
print(match.start(),"......",match.group())
Output:

Program: demo11.py

import re
matcher=re.finditer("\d","a7b @k9z")
for match in matcher:
print(match.start(),"......",match.group())
Output

Program: demo12.py

import re
matcher=re.finditer("\D","a7b @k9z")
for match in matcher:
print(match.start(),"......",match.group())
Output

230
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Program: demo13.py

import re
matcher=re.finditer("\w","a7b @k9z")
for match in matcher:
print(match.start(),"......",match.group())
Output

Program: demo14.py

import re
matcher=re.finditer("\W","a7b @k9z")
for match in matcher:
print(match.start(),"......",match.group())
Output:

Program: demo15.py

import re
matcher=re.finditer(".","a7b @k9z")
for match in matcher:
print(match.start(),"......",match.group())
Output:

Quantifiers in Python:
A quantifier has the form {m,n} where m and n are the minimum and maximum
times the expression to which the quantifier applies must match. We can use
quantifiers to specify the number of occurrences to match.

231
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training

Program: demo16.py

import re
matcher=re.finditer("a","abaabaaab")
for match in matcher:
print(match.start(),"......",match.group())
Output

Program: demo17.py

import re
matcher=re.finditer("a+","abaabaaab")
for match in matcher:
print(match.start(),"......",match.group())
Output:

Program: demo18.py

import re
matcher=re.finditer("a*","abaabaaab")
for match in matcher:
print(match.start(),"......",match.group())
Output

232
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Program: demo19.py

import re
matcher=re.finditer("a?","abaabaaab")
for match in matcher:
print(match.start(),"......",match.group())
Output:

Program: demo20.py

import re
matcher=re.finditer("a{3}","abaabaaab")
for match in matcher:
print(match.start(),"......",match.group())

Output:
Program: demo21.py

import re
matcher=re.finditer("a{2,4}","abaabaaab")
for match in matcher:
print(match.start(),"......",match.group())
Output

Regular Expression Methods in Python


we are going to discuss the following Regular Expression Important Methods in
Python.

match():
We can use the match function to check the given pattern at the beginning of
the target string. If the match is available then we will get a Match object,
otherwise we will get None.
Program: demo22.py
233
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
import re
s=input("Enter pattern to check: ")
m=re.match(s, "abcabdefg")
if m != None:
print("Match is available at the beginning of the String")
print("Start Index:", m.start(), "and End Index:", m.end())
else:
print("Match is not available at the beginning of the String")
Output1:

Output2:

fullmatch():
We can use fullmatch() function to match a pattern to all of target string i.e the
complete string should be matched according to the given pattern. If complete
string matched, then this function returns Match object otherwise it returns
None.
Program: demo23.py
import re
s=input("Enter pattern to check: ")
m=re.fullmatch(s, "ababab")
if m != None :
print("Full String Matched")
else :
print("Full String not Matched")
Output1:

Output2:

search():
We can use the search() function to search the given pattern in the target
string. If the match is available, then it returns the Match object which
represents the first occurrence of the match. If the match is not available, then
it returns None
Program: demo24.py
import re
234
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
s=input("Enter pattern to check: ")
m=re.search(s, "abaaaba")
if m != None:
print("Match is available")
print("First Occurrence of match with start index:",m.start(),"and end
index:", m.end())
else:
print("Match is not available")
Output1:

Output2:

findall():
To find all occurrences of the match. This function returns a list object which
contains all occurrences.
Program: demo25.py
import re
l=re.findall("[0-9]","a7b9c5kz")
print(l)

Output:
finditer():
Returns the iterator yielding a match object for each match. On each match
object we can call start(), end() and group() functions. Many examples have been
covered with this method at the starting of the chapter.
Program: demo26.py
import re
itr=re.finditer("[a-z]","a7b9c5k8z")
for m in itr:
print(m.start(),"...",m.end(),"...", m.group())
Output

sub():
sub means substitution or replacement
235
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
re.sub(regex, replacement, targetstring)
In the target string every matched pattern will be replaced with provided
replacement.
Program: demo27.py
import re
s=re.sub("[a-z]","#","a7b9c5k8z")
print(s)

Output:
subn():
It is exactly the same as sub except it can also return the number of
replacements. This function returns a tuple where the first element is the result
string and second element is the number of replacements.
(resultstring, number of replacements)
Program: demo28.py
import re
t=re.subn("[a-z]","#","a7b9c5k8z")
print(t)
print("The Result String:", t[0])
print("The number of replacements:", t[1])
Output

split():
If we want to split the given target string according to a particular pattern then
we should go for the split() function. This function returns a list of all tokens.
Program: demo29.py
import re
l=re.split("," , "KGF,BB1,BB2")
print(l)
for t in l:
print(t)
Output

Note: ^ symbol: We can use ^ symbol to check whether the given target string
starts with our provided pattern or not. If the target string starts with Learn
then it will return Match object, otherwise returns None.
res=re.search(“^Learn”, s)

236
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Program: demo31.py
import re
s="Learning Python is Very Easy"
res=re.search("^Learn", s)
if res !=None:
print("Target String starts with Learn")
else:
print("Target String Not starts with Learn")

Output:
$ symbol:
We can use $ symbol to check whether the given target string ends with our
provided pattern or not. If the target string ends with Easy then it will return
Match object, otherwise returns None.
res=re.search(“Easy$”, s)
Program: demo32.py
import re
s="Learning Python is Very Easy"
res=re.search("Easy$", s)
if res !=None:
print("Target String ends with Easy")
else:
print("Target String Not ends with Easy")

Output:
If we want to ignore case then we have to pass 3rd argument re.IGNORECASE
for search() function.
res = re.search(“easy$”, s, re.IGNORECASE)
Program: demo33.py

import re
s="Learning Python is Very Easy"
res=re.search("easy$", s, re.IGNORECASE)
if res !=None:
print("Target String ends with Easy by ignoring case")
else:
print("Target String Not ends with Easy by ignoring case")

Output:

237
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
SAMPLE PROGRAMS
PROGRAM 1:
Let’s consider the following requirement to create a regex object.
1. The allowed characters are a-z, A-Z, 0-9,#
2. The first character should be a lower-case alphabet symbol from a to k
3. The second character should be a digit divisible by 3.
4. The length of the identifier should be at least 2.
Regular expression: [a-k][0369][a-zA-Z0-9#]*.
Write a python program to check whether the given string is following
requirement1 rules or not?
import re
s=input("Enter string:")
m=re.fullmatch("[a-k][0369][a-zA-Z0-9#]*",s)
if m!= None:
print(s, "Entered regular expression is matched")
else:
print(s, " Entered regular expression is not matched ")
Output1:

Output2:

Output:

PROGRAM 2:
Write a Regular Expression to represent all 10 digit mobile numbers
Rules:
1. Every number should contain exactly 10 digits
2. The first digit should be 7 or 8 or 9
Regular Expressions:
[7-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]
or
[7-9][0-9]{9}
or
[7-9]\d{9}
import re
n=input("Enter number:")
m=re.fullmatch("[7-9]\d{9}",n)
if m!=None:
print("Valid Mobile Number")

238
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
else:
print("Please enter valid Mobile Number")
Output1:

Output2:

PROGRAM 3:
Write a python program to extract all mobile numbers present in input.txt
where numbers are mixed with normal text data
import re
f1=open("input.txt", "r")
f2=open("output.txt", "w")
for line in f1:
items = re.findall("[7-9]\d{9}",line)
for n in items:
f2.write(n+"\n")
print("Extracted all Mobile Numbers into output.txt")
f1.close()
f2.close()
Output:
input.txt

output.txt

PROGRAM 4:
Write a Python Program to check whether the given mail id is valid gmail id or
not?
import re
s=input("Enter Mail id:")
m=re.fullmatch("\w[a-zA-Z0-9_.]*@gmail[.]com", s)
if m!=None:
print("Valid Mail Id")
else:
print("Invalid Mail id")
239
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Output1:

Output2:

Logging Module in Python


What is logging?
The process of saving or storing the complete application flow and exception
information to a file is called logging.
Why do we need logging?
In real time, application logging is very important and mandatory. When any
action is being carried out using a program and if we save all the steps that are
being executed for that particular action in a file. Then we will have the privilege
to check what has happened for which action and how it happened.
For example, when you transfer money, it’s good to save the corresponding
steps in a log file to monitor if something goes wrong while transferring. When a
program crashes, if there is no logging record then it’s more pain to track or
understand what actually has happened.
Advantages of logging
Log files help us while debugging code when an issue occurs.
1. We can know which user has logged in and which operations are carried
by him etc.
2. We can provide statistics like number of requests per day etc.
Logging Module in Python:
In python, if we want to implement logging for our code, we can use an inbuilt
module by name ‘logging’. Before getting into the logging module details, let’s
understand some logging levels which are available.

240
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Logging Module Implementation in Python:
In order to implement logging in our code, we have to import the logging
module.
import logging

After importing, we are required to create a file to store messages and we have
to specify which level log messages should be stored. This can be done by using
basicConfig() method available in the logging module
logging.basicConfig(filename=’log.txt’, level=logging.WARNING)
The above line, when executed, will create a file log.txt and will store log
messages which are of either WARNING level or higher-level.
After creating a log file, we can write log messages to that file by using the
following methods.
1. logging.debug(message)
2. logging.info(message)
3. logging.warning(message)
4. logging.error(message)
5. logging.critical(message)
Program: logging Implementation in python (demo1.py)

import logging
logging.basicConfig(filename='sample_log.txt', level=logging.WARNING)
print('Logging started')
logging.debug('Debug Information')
logging.info('info Information')
logging.warning('warning Information')
logging.error('error Information')
logging.critical('critical Information')
print('Logging end')
Output:

File sample_log.txt:

In the above program, we have set the logging level to ‘logging.WARNING’, hence
in the log file only the logs of level warning and above will be stored. This is the
default logging level, the python takes, if we don’t specify any level.
Debug level:
If we want level of logs to be saved, then we need to set the the level to ‘DEBUG’
Program: Debug level logging Implementation in python (demo2.py)
import logging

241
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
logging.basicConfig(filename='sample_log2.txt', level=logging.DEBUG)
print('Logging started')
logging.debug('Debug Information')
logging.info('info Information')
logging.warning('warning Information')
logging.error('error Information')
logging.critical('critical Information')
print('Logging end')
Output:

File sample_log2.txt

In the above program, since we have used a different file name from the first
example, a new file has been created. If we had used the same file name as in
the first one i.e ‘sample_txt.log’ instead of ‘sample_txt2.log’, then the log
messages could have been appended to the file.
How to configure a log file in overriding mode?
When we create a log file using the basicConfig() method, the file will be created,
by default, in appending mode if we don’t mention any file mode. Instead of
appending if we want to overwrite data then we have to mention it in the
basicConfig() filemode property.
logging.basicConfig(filename=’log.txt’,
level=logging.WARNING,filemode=’w’)
Note: logging.basicConfig(filename=’log.txt’,
level=logging.WARNING,filemode=’w’)
1. If we don’t mention the file name in the above statement, then by default,
the log messages will be printed to the console rather than a file.
2. If we don’t mention the logging level, then by default, the warning level is
considered.
3. If we don’t mention the file mode, then by default, append mode is
considered.
Program: configure a log file in overriding mode (demo3.py)

import logging
logging.basicConfig()
print('Logging started')
logging.debug('Debug Information')
logging.info('info Information')
242
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
logging.warning('warning Information')
logging.error('error Information')
logging.critical('critical Information')
print('Logging end')
Output:

The log messages are printed to the console because we haven’t mentioned the
file in the basicConfig() method. The messages printed to the console are of
warning and above level, because the default level is taken as warning.
Formatting Log Messages in Python:
By using format keyword-argument in the basicConfig() method, we can format
log messages as per our requirement. Let’s see some common formattings:
To display only level name:
logging.basicConfig(format=’%(levelname)s’)
Program: Display only level name (demo4.py)
import logging
logging.basicConfig(format='%(levelname)s')
print('Logging started')
logging.debug('Debug Information')
logging.info('info Information')
logging.warning('warning Information')
logging.error('error Information')
logging.critical('critical Information')
print('Logging end')
Output:

To display level name and message


logging.basicConfig(format=’%(levelname)s:%(message)s’)
Program: Display level name and message (demo5.py)
import logging
logging.basicConfig(format='%(levelname)s:%(message)s')
print('Logging started')
logging.debug('Debug Information')
243
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
logging.info('info Information')
logging.warning('warning Information')
logging.error('error Information')
logging.critical('critical Information')
print('Logging end')
Output:

Add timestamp in the log messages


logging.basicConfig(format=’%(asctime)s:%(levelname)s:%(message)s’)
Program: Add timestamp in the log messages (demo6.py)
import logging
logging.basicConfig(format='%(asctime)s:%(levelname)s:%(message)s')
print('Logging started')
logging.debug('Debug Information')
logging.info('info Information')
logging.warning('warning Information')
logging.error('error Information')
logging.critical('critical Information')
print('Logging end')
Output:

Change date and time format


logging.basicConfig(format=’%(asctime)s:%(levelname)s:%(message)s’,
datefmt=’%d/%m/%Y %I:%M:%S %p’)
datefmt=’%d/%m/%Y %I:%M:%S %p’ → case is important
%I → 12 hours time scale
%H → 24 hours time scale
Program: Change date and time format in the log messages (demo7.py)
import logging
logging.basicConfig(format='%(asctime)s:%(levelname)s:%(message)s',date
fmt='%d/%m/%Y %I:%M:%S %p')
print('Logging started')

244
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
logging.debug('Debug Information')
logging.info('info Information')
logging.warning('warning Information')
logging.error('error Information')
logging.critical('critical Information')
print('Logging end')
Output:

Writing Exceptions to Log File in Python:


By using the following function, we can write exception information to the log
file.
logging.exception(msg)
Program: Writing Exceptions to Log File in Python (demo8.py)
import logging
logging.basicConfig(filename='demo.txt',level=logging.INFO,format='%(asc
time)s:%(levelname)s:%(message)s', datefmt='%d/%m/%Y%I:%M:%S %p')
logging.info('A new Request Came')
try:
x=int(input('Enter First Number:'))
y=int(input('Enter Second Number:'))
print('The Result:',x/y)
except ZeroDivisionError as msg:
print('Cannot divide with zero')
logging.exception(msg)
except ValueError as msg:
print('Please provide int values only')
logging.exception(msg)
logging.info('Request Processing Completed')
Output1:

Output2:

245
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
File demo.txt:

Customized Logging in Python


Root Logger in Python Logging Module
In all the above examples, the logger we have initialized is root logger. When we
use basicConfig() method, then, by default we are initializing the root logger.
In general, it is advised not to use the root logger. Instead, we should define and
customize our own logger for each module or package. The examples shown
above are only for basic understanding of what a logger is.
Problems with root logger:
1. Once we set basic configuration then that configuration is final, and we
cannot change it in the course of the program.
2. It will always work for only one handler at a time, either console or file,
but not both simultaneously.
3. It is not possible to configure a logger with different configurations at
different levels.
To overcome these problems, we should go for our own customized loggers.
Customized Logging in Python:
In python, the logging module has mainly four components: loggers, handlers,
filters and formatters. Loggers are the objects of the logging module with which
we handle the logging functionality. Handlers are those which specify where the
logging should go to i.e console or files etc. Filters are those with which we can
tell the logger what logs to record i.e levels of logging. Formatters are those
which are used to customize the log messages.
Steps for creating a custom logger
Step1: Create a logger
First we need to create a logger, which is nothing but an object to the logger
class. We can create this by using getLogger() method. After creating the logger
object we have to set the log level using setLevel() method.
logger = logging.getLogger(‘demologger’)
logger.setLevel(logging.INFO)
We can give any name to the logger as we wish. In the above example, a logger
with name ‘demologger’ will be created.
246
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Step2: Creating handler
The next step is to create a handler object and set the logging level. There are
several types of Handlers like StreamHandler, FileHandler etc. If we use
StreamHandler then log messages will be printed to the console. If we use
FileHandler, then the log messages will be printed into file.
For Stream Handler,
consoleHandler = logging.StreamHandler()
consoleHandler.setLevel(logging.INFO)
For File Handler,
fileHandler = logging.FileHandler(‘test.log’)
fileHandler.setLevel(logging.INFO)
Step3: Creating Formatter
The next step is to create a formatter object.
formatter = logging.Formatter(‘%(asctime)s – %(name)s – %(levelname)s:
%(message)s’, datefmt=’%d/%m/%Y %I:%M:%S %p’)
Step4: Adding Formatter to Handler
Now we have to add the Formatter (object) to Handler (object) using
setFormatter() method.
consoleHandler.setFormatter(formatter)
Step5: Adding Handler object to the Logger
Then the handler object should be added to the logger object using
addHandler() method.
logger.addHandler(fileHandler)
logger.addHandler(streamHandler)
Step6: Writing the log messages
The last step is writing the log messages to the file using the methods and
logger object which we created.
1. logger.debug(‘debug message’)
2. logger.info(‘info message’)
3. logger.warn(‘warn message’)
4. logger.error(‘error message’)
5. logger.critical(‘critical message’)
Points to note:
1. We have set the logging level for the logger object and the handler object
as well.
2. If we haven’t set any level for the logger object then, by default, the logger
object will be set to WARNING level.
3. If we haven’t set any level for the handler object then, by default, the
logger object’s level will be considered for the handler object also.
4. If we are not satisfied with logger level, then we can set log level explicitly
at handler level.
5. If we have set different log levels for the logger and handler then, the
handler level should be supported by the logger. i.e logger log level should
be lower than handler level. If this is not satisfied, the only logger log
level will be considered.

247
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
For example,
logger → DEBUG
handler → INFO ⇒ Valid and INFO level will be considered for the handler
logger → INFO
handler → DEBUG ⇒ Invalid and INFO level will be considered for the handler
Program: Customized Logging in Python (demo9.py)

import logging
class LoggerDemoConsole:
def testLog(self):
logger = logging.getLogger('demologger')
logger.setLevel(logging.INFO)
consoleHandler = logging.StreamHandler()
consoleHandler.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(name)s%(levelname)s:
%(message)s', datefmt='%m/%d/%Y %I:%M:%S%p')
consoleHandler.setFormatter(formatter)
logger.addHandler(consoleHandler)
logger.debug('debug message')
logger.info('info message')
logger.warn('warn message')
logger.error('error message')
logger.critical('critical message')
demo = LoggerDemoConsole()
demo.testLog()
Output:

If we want to use class name as logger name, then we have to create logger
object as follows
Program: class name as logger name in Python (demo10.py)

import logging
class LoggerDemoConsole:
def testLog(self):
#logger = logging.getLogger('demologger')
logger = logging.getLogger(LoggerDemoConsole.__name__)
logger.setLevel(logging.INFO)

248
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
consoleHandler = logging.StreamHandler()
consoleHandler.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(name)s%(levelname)s:
%(message)s', datefmt='%m/%d/%Y %I:%M:%S%p')
consoleHandler.setFormatter(formatter)
logger.addHandler(consoleHandler)
logger.debug('debug message')
logger.info('info message')
logger.warn('warn message')
logger.error('error message')
logger.critical('critical message')
demo = LoggerDemoConsole()
demo.testLog()
Output:

Program: using file handler in Python (demo11.py)

import logging
class LoggerDemoConsole:
def testLog(self):
#logger = logging.getLogger('demologger')
logger = logging.getLogger(LoggerDemoConsole.__name__)
logger.setLevel(logging.INFO)
fileHandler = logging.FileHandler("demo.log",mode='a')
fileHandler.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(name)s%(levelname)s:
%(message)s', datefmt='%m/%d/%Y %I:%M:%S%p')
fileHandler.setFormatter(formatter)
logger.addHandler(fileHandler)
logger.debug('debug message')
logger.info('info message')
logger.warn('warn message')
logger.error('error message')
logger.critical('critical message')

249
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
demo = LoggerDemoConsole()
demo.testLog()
print("Done")
Output:
File demo.log

Multithreading in Python
What is Multitasking?
The process of executing many tasks simultaneously is called the concept of
multitasking. The multitasking can be done in two ways:
1. Process based Multitasking
2. Thread based Multitasking
Process based Multitasking:
Executing several tasks simultaneously where each task is a separate
independent process is called Process based multitasking. For example,
1. Typing the program
2. Download the file
These tasks are executing simultaneously and independently of each other. It is
process based multitasking. This type of multi-tasking is best suitable at
operating system level.
Thread based Multitasking:
Executing several tasks simultaneously where each task is a separate
independent part of the same program, is called Thread based multitasking.
Here, each independent part is called a thread. This type of multi-tasking is
best suitable at programmatic level.
Note: Whether it is process based or thread based, the main advantage of
multi-tasking is to improve performance of the system by reducing response
time.
In this article, we are going to discuss in detail about multithreading, the
thread based multitasking, and its implementation in python.
Area of Multithreading:
The main important application areas of multithreading are:
1. To implement Multimedia graphics
2. To develop animations
3. To develop video games
4. To develop web and application servers etc.

250
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
How to implement Multithreading in Python?
Where-ever a group of independent jobs are available, then it is highly
recommended to execute them simultaneously instead of executing one by one
using the concept of multithreading.
Python provides one inbuilt module named “threading” to provide support for
implementing multithreading concepts.
So, developing multi-threaded Programs is very easy in python. The key point to
remember is that, every Python Program by default contains one thread which
is nothing but MainThread.
Program: Introduction to Multithreading (demo1.py)
import threading
print("Current Executing Thread:",threading.current_thread().getName())
Output:
The threading module contains function current_thread() which returns the
current executing Thread object. We need to call getName() method by using
thread object to know the current executing thread name.
Different Ways to Create a Thread in Python
There are two ways in which we can create a thread in python. They are as
follows:
1. Creating a Thread with pre-defined ‘Thread’ class
2. Creating a our own thread class by inheriting Thread class
Creating a Thread using Thread class:
There is a pre-defined class named ‘Thread’ available within the ‘threading’
module. We can create threads by using that inbuilt class.
Program: Creating a Thread with pre-defined ‘Thread’ class in python
(demo2.py)
from threading import *
def display():
for i in range(6):
print("Child Thread")
t=Thread(target=display)
t.start()
for i in range(6):
print("Main Thread")
Output:

251
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training

We created an object ‘t’ for the class ‘Thread’ with the target as display()
method. Whenever we call start() method using the object ‘t’, the thread
execution starts. The display() method will be executed parallely along with the
other parts of the program.
If multiple threads are present in our program, then we cannot expect exact
execution order in output. Because of this we cannot provide exact output order
for the above program. It varies from machine to machine while running.
Program: Creating a Thread with pre-defined ‘Thread’ class in python
(demo3.py)

from threading import *


class Demo:
def display(self):
for i in range(6):
print("Child Thread")
obj=Demo()
t=Thread(target=obj.display)
t.start()
for i in range(6):
print("Main Thread")
Output:

The demo3.py, is the similar program to demo2.py. The main intention is to


show how threading can be implemented to methods and classes.

252
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Creating a Thread class by inheriting Thread class:
We can create a thread by predefined Thread class. Here our class should
inherit Thread predefined class in python. Predefined Thread class contains
run() method. In our child class we need to override the run() method with our
required functionality. Whenever we call start() method then automatically run()
method will be executed and performs our job.
Program: Creating a Thread class by inheriting Thread class in python
(demo4.py)
from threading import *
class MyThread(Thread):
def run(self):
for i in range(6):
print("Child Thread")
t=MyThread()
t.start()
for i in range(6):
print("Main Thread")
Output:

Advantage of multithreading:
As told, the main advantage of multi-tasking is to improve performance of the
system by reducing response time. Let’s see it in the example below
Program: Multithreading in python (demo5.py)
from threading import *
import time
def divison(numbers):
for n in numbers:
time.sleep(1)
print("Double:", n/5)
def multiplication(numbers):
for n in numbers:
253
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
time.sleep(1)
print("Square:", n*5)
numbers=[10,20,30,40,50]
begintime=time.time()
divison(numbers)
multiplication(numbers)
print("The total time taken:", time.time()-begintime)
Output:

Program: multithreading in python (demo6.py)

from threading import *


import time
def divison(numbers):
for n in numbers:
time.sleep(1)
print("Double:", n/5)
def multiplication(numbers):
for n in numbers:
time.sleep(1)
print("Square:", n*5)
numbers=[10,20,30,40,50]
begintime=time.time()
t1=Thread(target=divison,args=(numbers,))
t2=Thread(target=multiplication, args=(numbers,))
t1.start()
t2.start()
t1.join()
t2.join()
print("The total time taken:", time.time()-begintime)
254
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Output:

In the above two programs, the execution time of the demo6.py (with
multithreading) is nearly half the time of demo5.py (without multithreading). In
real time, this would bring a great advantage in terms of execution time.
Note: In order to show some notable time, in the program we have used the
sleep(n) method which delays or stops the program execution for n seconds.
‘time’ is an in-built python module and time.time() will give us the current time
and time.sleep() will delay the execution.
Naming a Thread in Python:
Every thread in python has some name associated with it. It might be the
default name generated by Python or a name which can also be customized.
object.setName(<name>) : To set our own name
object.getName() – Returns Name of Thread
Program: set and get the name of a thread in python (demo7.py)
from threading import *
print("Main thread name",current_thread().getName())
current_thread().setName("MyThread")
print("After customise the thread name: ",current_thread().getName())
Output:

As already stated, current_thread() will return an object to the current thread.


By the default the program runs on Main Thread.
Thread Identification Number (ident):
For every thread internally, a unique identification number will be available. We
can access this by using implicit variable “ident”.
Program: Thread Identification Number in python (demo8.py)
from threading import *
def m():
print("Child Thread")
t=Thread(target=m)
t.start()
print("Main Thread Identification Number:", current_thread().ident)
print("Child Thread Identification Number:", t.ident)
255
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Output:

Methods of Thread class in Python


we are going to discuss the following important methods of Thread class in
detail.
1. active_count()
2. enumerate()
3. isAlive()
4. join()
5. join(seconds)
active_count() method:
This function returns the number of active threads currently running.
Program: active_count() method of Thread class in Python (demo9.py)
from threading import *
import time
def display():
print(current_thread().getName(), "...started")
time.sleep(3)
print(current_thread().getName(), "...ended")
print("The Number of active Threads:", active_count())
t1=Thread(target=display, name="ChildThread1")
t2=Thread(target=display, name="ChildThread2")
t3=Thread(target=display, name="ChildThread3")
t1.start()
t2.start()
t3.start()
print("The Number of active Threads:", active_count())
time.sleep(5)
print("The Number of active Threads:", active_count())
Output:

256
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training

Initially, the number of active threads is only the Main thread. Later, when we
created three threads to the target, then the total thread would become four.
enumerate() function:
This function returns a list of the objects of all active threads currently
running.
Program: enumerate() function of Thread class (demo10.py)
from threading import *
import time
def display():
print(current_thread().getName(), "...started")
time.sleep(3)
print(current_thread().getName(), "...ended")
t1=Thread(target=display, name="ChildThread1")
t2=Thread(target=display, name="ChildThread2")
t3=Thread(target=display, name="ChildThread3")
t1.start()
t2.start()
t3.start()
l=enumerate()
for t in l:
print("Thread Name:", t.name)
time.sleep(5)
l=enumerate()
for t in l:
print("Thread Name:", t.name)
Output:

257
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training

After starting the display() function to run in three threads, a total of three plus
one main threads would be running at the same time. After three seconds, the
sleep time, the child threads would end. So, after that time, only the main
thread would be in the execution.
isAlive() method:
This method is used to check whether a thread is still executing or not.
Program: isAlive() method in Python (demo11.py)
from threading import *
import time
def display():
print(current_thread().getName(), "...started")
time.sleep(3)
print(current_thread().getName(), "...ended")
print("The Number of active Threads:", active_count())
t1=Thread(target=display, name="ChildThread1")
t2=Thread(target=display, name="ChildThread2")
t1.start()
t2.start()
print(t1.name,"is Alive :",t1.isAlive())
print(t2.name,"is Alive :",t2.isAlive())
time.sleep(5)
print(t1.name,"is Alive :",t1.isAlive())
print(t2.name,"is Alive :",t2.isAlive())
Output:

258
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
join() method:
If we want a particular thread to wait for another thread to complete, then we
can use join() method.
Program: join() method of Thread class (demo12.py)
from threading import *
import time
def display():
for i in range(5):
print("First Thread")
t=Thread(target=display, name="ChildThread")
t.start()
t.join() #This is executed by Main Thread
for i in range(5):
print("Second Thread")
Output:

Here the main thread will wait until the child thread gets completed.
join(seconds) method:
The join method above can also be used by passing the argument ,in the
seconds, time period also. In this case thread will wait only specified amount of
time.
Program: join(seconds) method in Python (demo13.py)
from threading import *
import time
def display():
for i in range(5):
print("First Thread")
time.sleep(2)
t=Thread(target=display, name="ChildThread")
t.start()
t.join(5) #This is executed by Main Thread

259
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
for i in range(5):
print("Second Thread")
Output:

Daemon Threads in Python


What are Daemon threads?
When a program is running there are some process, related to the program,
that will be running in the background supporting the program execution. Such
threads or processes which are running in the background are called Daemon
Threads. The main objective of Daemon Threads is to provide support for Non-
Daemon Threads (like main thread)
Example: Garbage Collector
Whenever Main Thread runs with low memory, immediately PVM runs Garbage
Collector to destroy useless objects and to provide free memory, so that Main
Thread can continue its execution without having any memory problems.
We can check whether the thread is Daemon or not, by using isDaemon()
method of Thread class and also by using daemon property.
Program: Checking whether the Thread is Daemon or not in Python
(demo14.py)
from threading import *
print(current_thread().isDaemon())
print(current_thread().daemon)
Output:

Note: The main thread is always Non-Daemon thread


setDaemon() method in python:
We can change Daemon nature by using the setDaemon() method of Thread
class. In this perspective, let’s know some points.
We have to set a thread as a Daemon before starting it. Once a thread starts,
we cannot change its Daemon nature. If we try to change, we will get
RuntimeError: cannot set daemon status of active thread
Program: setDaemon() method of Thread class in Python (demo15.py)
from threading import *
260
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
def display():
print("Child Thread")
t=Thread(target=display)
t.start()
t.setDaemon(True)
Output:
Some points to note:
1. When we start the execution of a program, the Main Thread will
automatically start. We don’t explicitly start the Main Thread.
2. Since, by default, the Main Thread is a Non Daemon, and it starts
automatically at the start to program execution, we can’t change its Non
Daemon nature to Daemon.
3. Hence, the Main Thread will always be a Non Daemon thread.
4. The threads, which we create in the program, will inherit their Daemon
nature from the parent thread, by default.
5. If the Parent Thread is Daemon, then child thread is also Daemon by
default.
6. If the Parent Thread is Non-Daemon, then ChildThread is also Non-
Daemon by default.
7. Whenever the last Non-Daemon Thread terminates, automatically all
Daemon Threads will be terminated
Program: Main Thread is always Non-Daemon in Python (demo16.py)

from threading import *


import time
def display():
for i in range(5):
print("Child Thread")
time.sleep(2)
t=Thread(target=display)
#t.setDaemon(True)
t.start()
time.sleep(5)
print("End Of Main Thread")
Output:

261
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
In the above program, the child thread, will inherit its daemon nature from
parent thread i.e Main Thread, by default. Since both the parent and child are
non daemon they will be executed completely.
Program: Main Thread is always Non-Daemon Thread in Python (demo17.py)

from threading import *


import time
def display():
for i in range(5):
print("Child Thread")
time.sleep(2)
t=Thread(target=display)
t.setDaemon(True)
t.start()
time.sleep(5)
print("End Of Main Thread")
Output:

In this program, we have changed the daemon status of the child thread to True
before starting it.
The main thread, non daemon, gets completed faster than the child thread, a
non daemon. After the execution of a non daemon thread, immediately the
daemon thread execution is stopped.

Synchronization in Python
Synchronization in Python:
If multiple threads are executing simultaneously on object or data then there
may be a chance of data inconsistency problems.
Let’s understand it through an example:
Consider a couple who is having a Joint account and both are having their ATM
cards. They come to different ATMs and try to withdraw some amount at the
same time. Let’s say the total balance in the account is 500 and Wife tries to
withdraw 450 and the husband tries to withdraw 100. When they swipe the
card for withdrawing money, the balance shown will be 500. Two threads will be
created for the transaction, out of which only one thread should be successful
and the other should fail. If both the threads get successful then its a loss to
the bank. So, the threads should be in synchronization so that one fails and the
other wins.

262
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Let us consider another example:
Consider an online bus booking website, being accessed by two users at the
same time to book tickets in the same bus and route. Assume that there are
only three seats left and both of them trying to book those at the same time.
Only one should be able to proceed and others should fail.
Understandings
In both the examples, trouble arises when different threads try to work on the
same data at same time. To avoid such troubles and process the threads safely
without any problems, the code synchronization should be implemented which
restricts multiple threads to work on the same code at the same time.
Program: Inconsistent data (demo18.py)

from threading import *


import time
def wish(name,age):
for i in range(3):
print("Hi",name)
time.sleep(2)
print("Your age is",age)
t1=Thread(target=wish, args=("Sireesh",15))
t2=Thread(target=wish, args=("Nitya",20))
t1.start()
t2.start()
Output:

My requirement here is to print the ‘hi’ message and the age of that person at
the same time. But since both the threads are executing simultaneously we are
getting an irregular output, hence making it difficult to know the age of Sireesh
and Nitya.
How to overcome data inconsistency problems?
We can solve these inconsistency problems by synchronizing the threads such
that they will be executed one by one. The main application areas of
synchronization are,
263
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
1. Online Reservation system
2. Funds Transfer from joint accounts etc.
How to implement synchronization in python?
In Python, we can implement synchronization by using the following concepts
1. Lock
2. RLock
3. Semaphore
Synchronization By using Lock concept in python:
Locks are the most fundamental synchronization mechanism provided by the
threading module. We can create Lock object as follows,
l=Lock()
The Lock object can be held by only one thread at a time. If any other thread
wants the same lock then it will have to wait until the other one releases it. It’s
similar to waiting in line to book a train ticket, public telephone booth etc.
acquire() method: A Thread can acquire the lock by using acquire() method
l.acquire()
release() method: A Thread can release the lock by using release() method.
l.release()
Note: Only the thread currently holding the lock is allowed to call the release()
method thread, otherwise we will get Runtime Error saying, RuntimeError:
release unlocked lock
Program: lock acquiring and releasing in python (demo19.py)
from threading import *
l=Lock()
l.acquire()
print("lock acquired")
l.release()
print("lock released")
Output:

Program: Synchronization using lock acquiring and releasing in python


(demo20.py)

from threading import *


l=Lock()
l.release()
print("lock released")
Output:
Program: Synchronization By using Lock concept in Python (demo21.py)
from threading import *
import time
264
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
l=Lock()
def wish(name,age):
for i in range(3):
l.acquire()
print("Hi",name)
time.sleep(2)
print("Your age is",age)
l.release()
t1=Thread(target=wish, args=("Sireesh",15))
t2=Thread(target=wish, args=("Nitya",20))
t1.start()
t2.start()
Output:

Problem with Simple Lock in Python:


The standard lock object does not care which thread is currently holding that
lock. If the lock is being held by one thread, and if any other thread tries to
accquire the lock, then it will be blocked, even if it’s the same thread that is
already holding the lock.
So, if the Thread calls recursive functions or nested access to resources, then
the thread may try to acquire the same lock again and again, which may result
in blocking of our thread. Hence Traditional Locking mechanism won’t work for
executing recursive functions.
Synchronization By using RLock concept in Python:
To overcome the above problem of Simple Lock, we should go for
RLock(Reentrant Lock). Reentrant means the thread can acquire the same lock
again and again. This will block the thread only if the lock is held by any other
thread. Reentrant facility is available only for owner thread but not for other
threads.
This RLock keeps track of recursion level and hence for every acquire() there
should be a release() call available.
The number of acquire() calls and release() calls should be matched then for the
lock to be released i.e if there are two accquire calls then there should be two
265
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
release calls for the lock to be released. If there is only one release call for two
accquire calls then the lock wont be released.
Program: Synchronization By using RLock concept in Python (demo22.py)
from threading import *
import time
l=RLock()
def factorial(n):
l.acquire()
if n==0:
result=1
else:
result=n*factorial(n-1)
l.release()
return result
def results(n):
print("The Factorial of", n, "is:", factorial(n))
t1=Thread(target=results, args=(5,))
t2=Thread(target=results, args=(9,))
t1.start()
t2.start()
Output:

Difference between Lock and RLock in Python:

Synchronization by using Semaphore in Python:


Semaphore is advanced Synchronization Mechanism. Sometimes there might be
requirements where at a time a particular number of threads should be allowed
to access the resources. Like, at a time 10 members are allowed to access the
database server or at a time 4 members are allowed to access Network
266
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
connection. We can’t handle this requirement, using Lock and RLock concepts.
Hence, we should go for the Semaphore concept in such cases.
Creating a Semaphore object
We can create a Semaphore object as follows.
s=Semaphore(counter)
Here counter represents the maximum number of threads are allowed to access
simultaneously. The default value of counter is 1.
Whenever thread executes the acquire() method then the counter value will be
decremented by 1 and if the thread executes the release() method then the
counter value will be incremented by 1.
Program: Synchronization By using Semaphore in Python (demo23.py)

from threading import *


import time
s=Semaphore(2)
def wish(name,age):
for i in range(3):
s.acquire()
print("Hi",name)
time.sleep(2)
s.release()
t1=Thread(target=wish, args=("Sireesh",15))
t2=Thread(target=wish, args=("Nitya",20))
t3=Thread(target=wish, args=("Shiva",16))
t4=Thread(target=wish, args=("Ajay",25))
t1.start()
t2.start()
t3.start()
t4.start()
Output:

267
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
In the above program, since the counter for Semaphore is 2, the threads t1 and
t2 will be executed parallely and after their execution is completed then the
other threads t3 and t4 will start.
Bounded Semaphore in Python:
In Normal Semaphore, discussed above, the release method can be called any
number of times to increase the counter, irrespective of the acquire method.
Sometimes, the number of release() calls can exceed the number of acquire()
calls also.
Program: Bounded Semaphore in Python (demo24.py)
from threading import *
s=Semaphore(2)
s.acquire()
s.acquire()
s.release()
s.release()
s.release()
s.release()
print("End")

Output:
It is valid because in normal semaphore we can call release() any number of
times. This may result in programming errors or may raise confusions. So, it is
always recommended to use Bounded Semaphore which raises an error if the
number of release() calls exceeds the number of acquire() calls.
Program: Bounded Semaphore in Python (demo25.py)

from threading import *


s=BoundedSemaphore(2)
s.acquire()
s.acquire()
s.release()
s.release()
s.release()
s.release()
print("End")

Output:
Conclusion:
The major idea of synchronization is to overcome data inconsistency problems.
But the disadvantage of synchronization is it increases waiting time of threads
and creates performance problems. Hence it is recommended to use
synchronization only if the requirement demands.
268
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training

Inter Thread communication in Python


What is Inter Thread communication in Python?
Sometimes one thread may be required to communicate to another thread
depending on the requirement. This is called inter thread communication. In
Python, we can implement inter thread communication by using the following
ways:
1. Event
2. Condition
3. Queue
Inter Thread communication by using Event Objects
Event object is the simplest communication mechanism between the threads.
One thread signals an event and other threads wait for it. We need to create an
Event object as follows
event = threading.Event()
Event manages some internal flags which can be set or cleared using the
methods on event object
set():
When we call for this method an internal flag will become True and it
represents a GREEN signal for all waiting threads.
event.set()
clear():
When we call for this method an internal flag value will become False and it
represents a RED signal for all waiting threads.
event.clear()
isSet():
This method can be used to check whether the event is set or not.
event.isSet()
wait() or wait(seconds):
This method can be used to make a thread wait until an event is set.
event.wait()
Program: Inter Thread communication by using Event Objects in python
(demo26.py)

from threading import *


import time
def traffic_police():
while True:
time.sleep(5)
print("Traffic Police Giving GREEN Signal")

269
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
event.set()
time.sleep(10)
print("Traffic Police Giving RED Signal")
event.clear()
def driver():
num=0
while True:
print("Drivers waiting for GREEN Signal")
event.wait()
print("Traffic Signal is GREEN...Vehicles can move")
while event.isSet():
num=num+1
print("Vehicle No:", num," Crossing the Signal")
time.sleep(2)
print("Traffic Signal is RED...Drivers have to wait")
event=Event()
t1=Thread(target=traffic_police)
t2=Thread(target=driver)
t1.start()
t2.start()
Output:

270
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
In the above program driver thread has to wait until Trafficpolice thread sets
the event. i.e until a green signal is given. Once the Traffic police thread sets an
event (giving GREEN signal), vehicles can cross the signal. Again, when the
traffic police thread clears the event (giving RED Signal) then the driver thread
has to wait.
The traffic police thread sets the event for a period of 10 seconds before clearing
it. After clearing the event it again sets it after a period of 5 seconds. The driver
thread will be executed in that period of 10 seconds, event set period, and waits
for the event to be set in the event clear period. Here, the event object is
communicating between both the threads for the expected execution of the
code.
The above program will never stop because the condition in the while loop is
always True. You need to do Ctrl+c to stop the execution
Inter Thread communication by using Condition Object:
Condition is the more advanced version of Event object for inter thread
communication. A Condition object can be created as follows
condition = threading.Condition()
Condition object allows one or more threads to wait until notified by another
thread. Condition is always associated with a lock (ReentrantLock). A condition
object has acquire() and release() methods that call the corresponding methods
of the associated lock.
acquire():
This method is used to acquire the condition object. i.e thread acquiring the
internal lock.
condition.acquire()
release():
This method is used to release the condition object i.e thread releases internal
lock
condition.release()
wait()|wait(time):
This method is used to wait until getting notification or until the mentioned
time expires
condition.wait()
notify():
This method is used to give notification for one waiting thread
condition.notify()
notifyAll():
This method is used to give notification for all waiting threads
condition.notifyAll()
Let’s consider the following use case where there are two threads, a producer
thread and a consumer thread,
Producer Thread:
The producer thread needs to acquire the Condition object before producing
items and should notify the remaining thread (in our case consumer thread)
about it.
271
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
1. Acquire the condition object i.e lock (Step 1.1)
2. Produce the item (Step 1.2)
3. Add the item to the resource (Step 1.3)
4. Notify the other threads about it (Step 1.4)
5. Release the condition object i.e lock (Step 1.5)
Consumer Thread:
The consumer thread must acquire the condition and then have to wait for the
notification from the other thread(in our case producer thread).
1. Acquire the condition object i.e lock (Step 2.1)
2. Wait for the notification (Step 2.2)
3. Use or consume the items (Step 2.3)
4. Release the condition object i.e lock (Step 2.4)
Program: Inter Thread communication by using Condition Objects (demo27.py)

from threading import *


import time
import random
items=[]
def produce(c):
while True:
c.acquire() #Step 1.1
item=random.randint(1,10) #Step 1.2
print("Producer Producing Item:", item)
items.append(item) #Step 1.3
print("Producer giving Notification")
c.notify() #Step 1.4
c.release() #Step 1.5
time.sleep(5)
def consume(c):
while True:
c.acquire() #Step 2.1
print("Consumer waiting for update")
c.wait() #Step 2.2
print("Consumer consumed the item", items.pop()) #Step 2.3
c.release() #Step 2.4
time.sleep(5)
c=Condition()
t1=Thread(target=consume, args=(c,))
t2=Thread(target=produce, args=(c,))

272
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
t1.start()
t2.start()
Output:

The above program will never stop because the condition in the while loop is
always True. You need to do Ctrl+c to stop the execution
Inter Thread communication by using Queue in python:
Queues Concept is the most enhanced Mechanism for inter thread
communication and to share data between threads. Queue internally has
Condition functionality which inturn includes the Lock functionality. Hence
whenever we are using Queue we are not required to worry about
Synchronization.
If we want to use Queues we should import the queue module. import queue
We can create Queue object as: q = queue.Queue()
Two important methods of the queue module
1. put(): To put an item into the queue.
2. get(): To remove and return an item from the queue.
Lets understand how this works with the previous use case of
producer and consumer threads
Producer Thread can use the put() method to insert data in the queue.
Whenever the producer method calls the put method, internally, first it will
acquire the lock and then insert the data into the queue and then release the
lock automatically. The put method also checks whether the queue is full or not
and if queue is full then the Producer thread will enter into the waiting state by
calling wait() method internally.
Consumer Thread can use the get() method to remove and get data from the
queue. Whenever the consumer method calls the get method, internally, first it
will acquire the lock and then get/remove the data from the queue and then
release the lock automatically. If the queue is empty then the consumer thread
will enter into the waiting state by calling wait() method internally. Once the
queue is updated with data then the thread will be notified automatically.
Program: Inter Thread communication by using Queue in python (demo28.py)

from threading import *


import time
import random
import queue
273
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
items=[]
def produce(c):
while True:
item=random.randint(1,10) #Step 1.2
print("Producer Producing Item:", item)
q.put(item)
print("Producer giving Notification")
time.sleep(5)
def consume(c):
while True:
print("Consumer waiting for update")
print("Consumer consumed the item", q.get())
time.sleep(5)
q=queue.Queue()
t1=Thread(target=consume, args=(q,))
t2=Thread(target=produce, args=(q,))
t1.start()
t2.start()
Output:

The above program will never stop because the condition in the while loop is
always True. You need to do Ctrl+c to stop the execution
Types of Queues in Python
Python supports 3 Types of Queues:
1. FIFO Queue
2. LIFO Queue
3. Priority Queue

274
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
FIFO Queue in Python:
This is the default behavior of the queue. The order in which we get the items
from the queue, is the order in which the items are put(FIFO-First In First Out).
Program: FIFO Queue in python (demo29.py)
import queue
q=queue.Queue()
q.put(10)
q.put(5)
q.put(20)
q.put(15)
while not q.empty():
print(q.get())
Output:

LIFO Queue in Python:


The order in which we get the items in the queue, is the reverse order of the
items in which they are inserted (Last In First Out).
q=queue.LifoQueue()
Program: LIFO Queue in python (demo30.py)
import queue
q=queue.LifoQueue()
q.put(10)
q.put(5)
q.put(20)
q.put(15)
while not q.empty():
print(q.get())
Output:

Priority Queue in Python:


This queue stores the items based on some priority and returns the items
according to that priority. In order to decide that priority to save the elements in
the queue, python uses some sorting mechanisms.
Program: Priority Queue in python (demo31.py)

275
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
import queue
q=queue.PriorityQueue()
q.put(10)
q.put(5)
q.put(20)
q.put(15)
while not q.empty():
print(q.get())
Output:

If the data is non-numeric, then the internal sorting mechanisms will be able to
decide on the priority for the items. In such cases, we can associate the
elements with some weights based on which priority can be decided.
Program: Priority Queue in python (demo32.py)

import queue
q=queue.PriorityQueue()
q.put((1,'Ruhan'))
q.put((3,'Sharuk'))
q.put((4,'Ajay'))
q.put((2,'Siva'))
while not q.empty():
print(q.get()[1])
Output:

We can see from the output that the values are popped according to the ordered
which we provided. The point to be noted here is the data should be inserted in
the form of tuples as shown above. Even while getting the data, we can access
both the weight as well as value using indexing. i.e q.get()[0] will give the weight
and 1.get()[1] will give the value.

276
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Database Connectivity in Python
Introduction:
Every application requires someplace to store the data like customer’s
information, billing information, calling information, etc. To store the data we
need storage areas. There are two storage areas normally. They are:
1. Temporary Storage Areas
2. Permanent Storage Areas
Temporary storage area:
These are the Memory Areas where Data will be stored temporarily. For
example, Python objects like list, tuple, dictionary. Once the Python program
completes its execution then these objects will be destroyed automatically, and
data will be lost.
Permanent Storage Areas:
Also known as Persistent Storage Areas. Here we can store Data permanently.
For example File Systems, Databases, Data warehouses, Big Data Technologies,
etc
File Systems:
File Systems can be provided by a Local operating System. File Systems are
best suitable to store very little Amount of Information.
Limitations of File Systems:
1. We cannot store a huge amount of Information.
2. There is no Query Language support and hence operations will become
very complex.
3. There is no Security for Data.
4. There is no Mechanism to prevent duplicate Data. Hence there may be a
chance of data Inconsistency Problems.
Overcoming limitations
To overcome the above Problems of File Systems, we should go for Databases.
Database:
The data in the database is stored in the form of a table. We can store a Huge
Amount of Information in Databases. Query Language Support is available for
every Database and hence we can perform Database Operations very easily.
To access Data present in the Database, a username and password are
required, hence making it secured.
While creating Database Table Schema, Database Admin follows various
Normalization Techniques and can implement various Constraints like Unique
Key Constraint, Primary Key Constraints, etc which prevent Data Duplication.
Limitations of Databases
1. Databases cannot hold a Huge Amount of Information like Terabytes of
Data.
2. The database can provide support only for Structured Data (Tabular Data
OR Relational Data)

277
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
3. The database cannot provide support for Semi-Structured Data (like XML
Files) and
4. Unstructured Data (like Video Files, Audio Files, Images, etc)
Overcoming the limitations
To overcome these problems, we should go for more Advanced Storage Areas
like Big Data storage-related like HDFS (Hadoop), Data warehouses, etc.
Python Database Programming
Sometimes as the part of Programming requirement, we have to connect to the
database programmatically and we have to perform several operations like,
1. creating tables,
2. inserting data,
3. updating data,
4. deleting data,
5. selecting data etc.
The above operations in the database will be performed using SQL, a query
language. In Python, we use some modules and send the queries/SQL
commands to the database.
Python provides inbuilt support for several databases like
1. Oracle,
2. MySql,
3. SqlServer,
4. GadFly,
5. SQLite, etc
The support python provides for each database is through different modules for
each like cx_Oralce module for communicating with Oracle database, pymssql
module for communicating with Microsoft SQL Server.
Standard steps for Python database Programming:
1. import database-specific module
2. Establish a Connection towards the database with credentials in a
secured way.
3. Create a Cursor object
4. Use In-built methods to execute the SQL queries
5. Commit or rollback
6. Fetch the result from the Cursor
7. Close the resources
we will discuss Python - MySQL connectivity, and we
will perform the database operations in python. We will
also cover the Python connectivity with the databases
like MongoDB and SQLite.

Install mysql.connector

278
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
To connect the python application with the MySQL database, we must
import the mysql.connector module in the program.

The mysql.connector is not a built-in module that comes with the python
installation. We need to install it to get it working.

Execute the following command to install it using pip installer.

1. > python -m pip install mysql-connector

Or follow the following steps.

1. Click the link:

https://files.pythonhosted.org/packages/8f/6d/fb8ebcbbaee68b172ce3dfd
08c7b8660d09f91d8d5411298bcacbd309f96/mysql-connector-python-
8.0.13.tar.gz to download the source code.

2. Extract the archived file.

3. Open the terminal (CMD for windows) and change the present working
directory to the source code directory.

1. $ cd mysql-connector-python-8.0.13/

4. Run the file named setup.py with python (python3 in case you have also
installed python 2) with the parameter build.

1. $ python setup.py build

6. Run the following command to install the mysql-connector.

1. python setup.py install

This will take a bit of time to install mysql-connector for python. We can verify the
installation once the process gets over by importing mysql-connector on the python
shell.

Hence, we have successfully installed mysql-connector for python on our system.

Database Connection
In this section of the tutorial, we will discuss the steps to connect the python application to
the database.
279
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
There are the following steps to connect a python application to our database.

1. Import mysql.connector module


2. Create the connection object.
3. Create the cursor object
4. Execute the query

Creating the connection


To create a connection between the MySQL database and the python application, the
connect() method of mysql.connector module is used.

Pass the database details like HostName, username, and the database password in the method
call. The method returns the connection object.

The syntax to use the connect() is given below.

1. Connection-Object= mysql.connector.connect(host = <host-


name> , user = <username> , passwd = <password> )

Consider the following example.

Eg:
import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="root",
password="pavan"
)
print(mydb)

Output:
<mysql.connector.connection.MySQLConnection object at 0x7fb142edd780>

Here, we must notice that we can specify the database name in the connect() method
if we want to connect to a specific database.

<mysql.connector.connection.MySQLConnection object at
0x7fb142edd780>

280
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Creating a cursor object
The cursor object can be defined as an abstraction specified in the Python DB-API
2.0. It facilitates us to have multiple separate working environments through the
same connection to the database. We can create the cursor object by calling the
'cursor' function of the connection object. The cursor object is an important aspect of
executing queries to the databases.

The syntax to create the cursor object is given below.

Eg:
import mysql.connector
#Create the connection object
myconn = mysql.connector.connect(host="localhost",
user="root", password="pavan", database = "mydb")
#printing the connection object
print(myconn)
#creating the cursor object
cur = myconn.cursor()
print(cur)

Creating new databases


In this section, we will create the new database PythonDB.

Getting the list of existing databases


We can get the list of all the databases by using the following MySQL query.

1. > show databases;

Eg:
import mysql.connector

#Create the connection object


myconn = mysql.connector.connect(
host="localhost",

281
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
user="root",
password="pavan"
)
#creating the cursor object
cur = myconn.cursor()

try:
dbs = cur.execute("show databases")
except:
myconn.rollback()
for x in cur:
print(x)
myconn.close()
Output:
('EmployeeDB',)
('Test',)
('TestDB',)
('information_schema',)
('mydb',)
('mysql',)
('performance_schema',)
('testDB',)

Creating the new database


The new database can be created by using the following SQL query.

create database <database-name>

import mysql.connector

#Create the connection object


myconn = mysql.connector.connect(
host="localhost",
user="root",
password="pavan"
)

#creating the cursor object


cur = myconn.cursor()

282
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
try:
#creating a new database
cur.execute("create database Pythondb")

#getting the list of all the databases which will now include the new
database PythonDB
dbs = cur.execute("show databases")

except:
myconn.rollback()
print("Database Already Exits")

for x in cur:
print(x)

myconn.close()

Creating the table


In this section, we will create the new table Employee. We have to mention
the database name while establishing the connection object.
We can create the new table by using the CREATE TABLE statement of SQL.
In our database PythonDB, the table Employee will have the four columns,
i.e., name, id, salary, and department_id initially.
The following query is used to create the new table Employee.
1. > create table Employee (name varchar(20) not null, id int primary key, salary float not
null, Dept_Id int not null)
Example:
import mysql.connector

#Create the connection object


myconn = mysql.connector.connect(host = "localhost",
database="testdb", user = "root",password = "pavan")

#creating the cursor object


cur = myconn.cursor()

try:
#Creating a table with name Employee having four columns i.e.,
name, id, salary, and department id
dbs = cur.execute("create table Employee(name varchar(20) not null,
id int(20) not null primary key, salary float not null, Dept_id int not
null)")
except:
myconn.rollback()
print("Table Already Exists");
283
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training

myconn.close()

Now, we may check that the table Employee is present in the database.

Alter Table
Sometimes, we may forget to create some columns, or we may need to
update the table schema. The alter statement used to alter the table schema
if required. Here, we will add the column branch_name to the table
Employee. The following SQL query is used for this purpose.

alter table Employee add branch_name varchar(20) not null

Consider the following example.

Example:
import mysql.connector

#Create the connection object


myconn = mysql.connector.connect(host = "localhost",
database="testdb", user = "root",password = "pavan")

#creating the cursor object


cur = myconn.cursor()

try:
#adding a column branch name to the table Employee
cur.execute("alter table Employee add loc varchar(20) not null")
#cur.execute("desc employee")
except:
myconn.rollback()
print("Column not added")

print("Table Altered Successfully")

myconn.close()

Insert Operation
Adding a record to the table
The INSERT INTO statement is used to add a record to the table. In python,
we can mention the format specifier (%s) in place of values.
We provide the actual values in the form of tuple in the execute() method of
the cursor.
Consider the following example.
284
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
import mysql.connector
#Create the connection object

myconn = mysql.connector.connect(host = "localhost",


database="testdb", user = "root",password = "pavan")
#creating the cursor object
cur = myconn.cursor()
sql = "insert into Employee(name, id, salary, dept_id, branch_name,loc)
values (%s, %s, %s, %s, %s,%s)"

#The row values are provided in the form of tuple


val = ("Zaheer", 116, 20009.99, 122,"UNION","UK")

try:
#inserting the values into the table
cur.execute(sql,val)

#commit the transaction


myconn.commit()

except:
myconn.rollback()

print(cur.rowcount,"record inserted!")
myconn.close()

Output: 1 record inserted!!

Insert multiple rows


We can also insert multiple rows at once using the python script. The
multiple rows are mentioned as the list of various tuples.
Each element of the list is treated as one particular row, whereas each
element of the tuple is treated as one particular column value (attribute).
Consider the following example.
Example:
import mysql.connector

#Create the connection object


myconn = mysql.connector.connect(host = "localhost",
database="pavandb", user = "root",password = "python")

#creating the cursor object


cur = myconn.cursor()
sql = "insert into Employee(name, id, salary, dept_id, branch_name,loc)
values (%s, %s, %s, %s, %s)"
285
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
val = [("Manish", 111, 17500.00, 101,"ICICI", "Swithzerland"),
("sreenu",112,19000.00,103,"AXIS","Port of spain"),
("Nick",113,90000.00,104,"HDFC","Newzeland")]

try:
#inserting the values into the table
cur.execute(sql,val)

#commit the transaction


myconn.commit()
print(cur.rowcount,"records inserted!")

except:
myconn.rollback()
print("Error in inserting");

myconn.close()

Output: 3 Records Inserted

Row ID
In SQL, a particular row is represented by an insertion id which is known as
row id. We can get the last inserted row id by using the attribute lastrowid of
the cursor object.
Consider the following example.
Example
import mysql.connector
#Create the connection object
myconn = mysql.connector.connect(host = "localhost",
database="pavandb", user = "root",password = "python")
#creating the cursor object
cur = myconn.cursor()

sql = "insert into Employee(name, id, salary, dept_id, branch_name)


values (%s, %s, %s, %s, %s)"

val = ("Mike",105,28000,202,"Guyana")

try:
#inserting the values into the table
cur.execute(sql,val)

#commit the transaction


myconn.commit()

286
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
#getting rowid
print(cur.rowcount,"record inserted! id:",cur.lastrowid)

except:
myconn.rollback()

myconn.close()

Read Operation
The SELECT statement is used to read the values from the databases. We
can restrict the output of a select query by using various clause in SQL like
where, limit, etc.
Python provides the fetchall() method returns the data stored inside the
table in the form of rows. We can iterate the result to get the individual
rows.
In this section of the tutorial, we will extract the data from the database by
using the python script. We will also format the output to print it on the
console.
Example:
import mysql.connector

#Create the connection object


myconn = mysql.connector.connect(host = "localhost",
database="pavandb", user = "root",password = "python")

#creating the cursor object


cur = myconn.cursor()

try:
#Reading the Employee data
cur.execute("select * from Employee")

#fetching the rows from the cursor object


result = cur.fetchall()
#printing the result

for x in result:
print(x);
except:
myconn.rollback()

myconn.close()

Output:

('John', 101, 25000.0, 201, 'Newyork')

287
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
('John', 102, 25000.0, 201, 'Newyork')

('David', 103, 25000.0, 202, 'Port of spain')

('Nick', 104, 90000.0, 201, 'Newyork')

('Mike', 105, 28000.0, 202, 'Guyana')

Reading specific columns


We can read the specific columns by mentioning their names instead of
using star (*).
In the following example, we will read the name, id, and salary from the
Employee table and print it on the console.
Example:
import mysql.connector

#Create the connection object


myconn = mysql.connector.connect(host = "localhost", user =
"root",password = "python",database = "pavandb")

#creating the cursor object


cur = myconn.cursor()

try:
#Reading the Employee data
cur.execute("select name, id, salary from Employee where name like
'%A%'")

#fetching the rows from the cursor object


result = cur.fetchall()

print("Name id Salary");

for row in result:


print("%s %d %d"%(row[0],row[1],row[2]))
except:
myconn.rollback()

myconn.close()

The fetchone() method


The fetchone() method is used to fetch only one row from the table. The
fetchone() method returns the next row of the result-set.
288
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Consider the following example.
Example:
import mysql.connector

#Create the connection object


myconn = mysql.connector.connect(host = "localhost", user =
"root",password = "python",database = "Pavandb")

#creating the cursor object


cur = myconn.cursor()

try:
#Reading the Employee data
cur.execute("select name, id, salary from Employee")

#fetching the first row from the cursor object


result = cur.fetchone()

#printing the result


print(result)

except:
myconn.rollback()

myconn.close()

Formatting the result


We can format the result by iterating over the result produced by the
fetchall() or fetchone() method of cursor object since the result exists as the
tuple object which is not readable.
Consider the following example.
Example:
import mysql.connector

#Create the connection object


myconn = mysql.connector.connect(host = "localhost", user =
"root",passwd = "google",database = "PythonDB")

#creating the cursor object


cur = myconn.cursor()

try:

289
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
#Reading the Employee data
cur.execute("select name, id, salary from Employee")

#fetching the rows from the cursor object


result = cur.fetchall()

print("Name id Salary");
for row in result:
print("%s %d %d"%(row[0],row[1],row[2]))
except:
myconn.rollback()

myconn.close()

Output:

Name id Salary

John 101 25000

John 102 25000

David 103 25000

Nick 104 90000

Mike 105 28000

Using where clause


We can restrict the result produced by the select statement by using the
where clause. This will extract only those columns which satisfy the where
condition.
Consider the following example.
Example: printing the names that start with j
import mysql.connector

#Create the connection object


myconn = mysql.connector.connect(host = "localhost", user =
"root",passwd = "google",database = "PythonDB")

#creating the cursor object


cur = myconn.cursor()

try:
290
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
#Reading the Employee data
cur.execute("select name, id, salary from Employee where name like
'J%'")

#fetching the rows from the cursor object


result = cur.fetchall()

print("Name id Salary");

for row in result:


print("%s %d %d"%(row[0],row[1],row[2]))
except:
myconn.rollback()

myconn.close()

Output:
Name id Salary
John 101 25000
John 102 25000

Example: printing the names with id = 101, 102, and 103


import mysql.connector

#Create the connection object


myconn = mysql.connector.connect(host = "localhost", user =
"root",passwd = "google",database = "PythonDB")

#creating the cursor object


cur = myconn.cursor()

try:
#Reading the Employee data
cur.execute("select name, id, salary from Employee where id in
(101,102,103)")

#fetching the rows from the cursor object


result = cur.fetchall()

print("Name id Salary");

for row in result:


print("%s %d %d"%(row[0],row[1],row[2]))
except:
myconn.rollback()

myconn.close()
291
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training

Output:

Name id Salary

John 101 25000

John 102 25000

David 103 2500

Ordering the result


The ORDER BY clause is used to order the result. Consider the following
example.

Example:
import mysql.connector

#Create the connection object


myconn = mysql.connector.connect(host = "localhost", user =
"root",password = "python",database = "pavandb")

#creating the cursor object


cur = myconn.cursor()

try:
#Reading the Employee data
cur.execute("select name, id, salary from Employee order by name")

#fetching the rows from the cursor object


result = cur.fetchall()

print("Name id Salary");

for row in result:


print("%s %d %d"%(row[0],row[1],row[2]))
except:
myconn.rollback()
print("Unable to Fetch Data");

myconn.close()

Output:
Name id Salary
292
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
David 103 25000
John 101 25000
John 102 25000
Mike 105 28000
Nick 104 90000

Order by DESC
This orders the result in the decreasing order of a particular column.

Example:
import mysql.connector

#Create the connection object


myconn = mysql.connector.connect(host = "localhost", user =
"root",password = "python",database = "pavandb")

#creating the cursor object


cur = myconn.cursor()

try:
#Reading the Employee data
cur.execute("select name, id, salary from Employee order by name
desc")

#fetching the rows from the cursor object


result = cur.fetchall()

#printing the result


print("Name id Salary");
for row in result:
print("%s %d %d"%(row[0],row[1],row[2]))

except:
myconn.rollback()

myconn.close()
Output:

Name id Salary
Nick 104 90000
Mike 105 28000
John 101 25000
293
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
John 102 25000
David 103 25000

Update Operation
The UPDATE-SET statement is used to update any column inside the table.
The following SQL query is used to update a column.

update Employee set name = 'alex' where id = 110

Consider the following example.

Example:
import mysql.connector

#Create the connection object


myconn = mysql.connector.connect(host = "localhost", user = "root",password
= "python",database = "pavandb")

#creating the cursor object


cur = myconn.cursor()

try:
#updating the name of the employee whose id is 110
cur.execute("update Employee set name = 'alex' where id = 110")
myconn.commit()
except:
myconn.rollback()
print("Record Updation Failed");

print("Record Updated Successfully");

myconn.close()

Delete Operation
The DELETE FROM statement is used to delete a specific record from the
table. Here, we must impose a condition using WHERE clause otherwise all
the records from the table will be removed.

The following SQL query is used to delete the employee detail whose id is
110 from the table.

294
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
delete from Employee where id = 110

Consider the following example.

Example:
import mysql.connector

#Create the connection object


myconn = mysql.connector.connect(host = "localhost", user =
"root",passwd = "google",database = "PythonDB")
#creating the cursor object
cur = myconn.cursor()
try:
#Deleting the employee details whose id is 110
cur.execute("delete from Employee where id = 110")
myconn.commit()
except:
myconn.rollback()
myconn.close()

Join Operation
We can combine the columns from two or more tables by using some
common column among them by using the join statement.

We have only one table in our database, let's create one more table
Departments with two columns department_id and department_name.

create table Departments (Dept_id int(20) primary key not null, Dep
t_Name varchar(20) not null);
As we have created a new table Departments, Let's insert some
Departments ids and departments names so that we can map this to our
Employee table.

1. insert into Departments values (201, "CS");


2. insert into Departments values (202, "IT");
295
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training

Now, let's create a python script that joins the two tables on the common column, i.e.,
dept_id.
Example:
import mysql.connector

#Create the connection object


myconn = mysql.connector.connect(host = "localhost", user =
"root",passwd = "google",database = "PythonDB")

#creating the cursor object


cur = myconn.cursor()

try:
#joining the two tables on departments_id
cur.execute("select Employee.id, Employee.name, Employee.salary,
Departments.Dept_id, Departments.Dept_Name from Departments join
Employee on Departments.Dept_id = Employee.Dept_id")
print("ID Name Salary Dept_Id Dept_Name")
for row in cur:
print("%d %s %d %d %s"%(row[0],
row[1],row[2],row[3],row[4]))

except:
myconn.rollback()

myconn.close()

Output:
ID Name Salary Dept_Id Dept_Name
101 John 25000 201 CS
102 John 25000 201 CS
103 David 25000 202 IT
104 Nick 90000 201 CS
105 Mike 28000 202 IT

Right Join
Right join shows all the columns of the right-hand side table as we have two
tables in the database PythonDB, i.e., Departments and Employee. We do
296
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
not have any Employee in the table who is not working for any department
(Employee for which department id is null). However, to understand the
concept of right join let's create the one.

Execute the following query on the MySQL server.

insert into Employee(name, id, salary, branch_name) values ("Alex",


108,29900,"Mumbai");

This will insert an employee Alex who doesn't work for any department
(department id is null).

Now, we have an employee in the Employee table whose department id is not


present in the Departments table. Let's perform the right join on the two
tables now.

Example:
import mysql.connector

#Create the connection object


myconn = mysql.connector.connect(host = "localhost", user =
"root",passwd = "google",database = "PythonDB")
#creating the cursor object
cur = myconn.cursor()
try:
#joining the two tables on departments_id
result = cur.execute("select Employee.id, Employee.name,
Employee.salary, Departments.Dept_id, Departments.Dept_Name from
Departments right join Employee on Departments.Dept_id =
Employee.Dept_id")

print("ID Name Salary Dept_Id Dept_Name")


for row in cur:
print(row[0]," ", row[1]," ",row[2]," ",row[3]," ",row[4])
except:
myconn.rollback()
myconn.close()
Output:
ID Name Salary Dept_Id Dept_Name
297
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
101 John 25000.0 201 CS
102 John 25000.0 201 CS
103 David 25000.0 202 IT
104 Nick 90000.0 201 CS
105 Mike 28000.0 202 IT
108 Alex 29900.0 None None

Left Join
The left join covers all the data from the left-hand side table. It has just
opposite effect to the right join. Consider the following example.

Example:
import mysql.connector

#Create the connection object


myconn = mysql.connector.connect(host = "localhost", user =
"root",passwd = "google",database = "PythonDB")

#creating the cursor object


cur = myconn.cursor()

try:
#joining the two tables on departments_id
result = cur.execute("select Employee.id, Employee.name,
Employee.salary, Departments.Dept_id, Departments.Dept_Name from
Departments left join Employee on Departments.Dept_id =
Employee.Dept_id")
print("ID Name Salary Dept_Id Dept_Name")
for row in cur:
print(row[0]," ", row[1]," ",row[2]," ",row[3]," ",row[4])
except:
myconn.rollback()

myconn.close()
Output:

298
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
ID Name Salary Dept_Id Dept_Name
101 John 25000.0 201 CS
102 John 25000.0 201 CS
103 David 25000.0 202 IT
104 Nick 90000.0 201 CS
105 Mike 28000.0 202 IT

Python Tkinter Tutorial


Tkinter tutorial provides basic and advanced concepts of Python Tkinter. Python provides the
standard library Tkinter for creating the graphical user interface for desktop based
applications.

Developing desktop based applications with python Tkinter is not a complex task. An
empty Tkinter top-level window can be created by using the following steps.

1. import the Tkinter module.


2. Create the main application window.
3. Add the widgets like labels, buttons, frames, etc. to the window.
4. Call the main event loop so that the actions can take place on the user's
computer screen.

Example:
1. # !/usr/bin/python3
2. from tkinter import *
3. #creating the application main window.
4. top = Tk()
5. #Entering the event main loop
6. top.mainloop()

299
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training

Tkinter widgets
There are various widgets like button, canvas, checkbutton, entry, etc. that are used
to build the python GUI applications.

SN Widget Description

1 Button The Button is used to add various kinds of buttons to the python
application.

2 Canvas The canvas widget is used to draw the canvas on the window.

3 Checkbutton The Checkbutton is used to display the CheckButton on the window.

4 Entry The entry widget is used to display the single-line text field to the user.
It is commonly used to accept user values.

5 Frame It can be defined as a container to which, another widget can be added


and organized.

6 Label A label is a text used to display some message or information about the
other widgets.

300
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
7 ListBox The ListBox widget is used to display a list of options to the user.

8 Menubutton The Menubutton is used to display the menu items to the user.

9 Menu It is used to add menu items to the user.

10 Message The Message widget is used to display the message-box to the user.

11 Radiobutton The Radiobutton is different from a checkbutton. Here, the user is


provided with various options and the user can select only one option
among them.

12 Scale It is used to provide the slider to the user.

13 Scrollbar It provides the scrollbar to the user so that the user can scroll the
window up and down.

14 Text It is different from Entry because it provides a multi-line text field to the
user so that the user can write the text and edit the text inside it.

14 Toplevel It is used to create a separate window container.

15 Spinbox It is an entry widget used to select from options of values.

16 PanedWindow It is like a container widget that contains horizontal or vertical panes.

17 LabelFrame A LabelFrame is a container widget that acts as the container

18 MessageBox This module is used to display the message-box in the desktop based
applications.

301
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
Python Tkinter Geometry
The Tkinter geometry specifies the method by using which, the widgets are
represented on display. The python Tkinter provides the following geometry
methods.

1. The pack() method


2. The grid() method
3. The place() method

Let's discuss each one of them in detail.

Python Tkinter pack() method


The pack() widget is used to organize widget in the block. The positions widgets
added to the python application using the pack() method can be controlled by using
the various options specified in the method call.

However, the controls are less and widgets are generally added in the less organized
manner.

The syntax to use the pack() is given below.

Syntax:
widget.pack(options)

A list of possible options that can be passed in pack() is given below.

o expand: If the expand is set to true, the widget expands to fill any space.
o Fill: By default, the fill is set to NONE. However, we can set it to X or Y to
determine whether the widget contains any extra space.
o size: it represents the side of the parent to which the widget is to be placed
on the window.

Example:
1. # !/usr/bin/python3
2. from tkinter import *
3. parent = Tk()
4. redbutton = Button(parent, text = "Red", fg = "red")

302
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
5. redbutton.pack( side = LEFT)
6. greenbutton = Button(parent, text = "Black", fg = "black")
7. greenbutton.pack( side = RIGHT )
8. bluebutton = Button(parent, text = "Blue", fg = "blue")
9. bluebutton.pack( side = TOP )
10. blackbutton = Button(parent, text = "Green", fg = "red")
11. blackbutton.pack( side = BOTTOM)
12. parent.mainloop()

Python Tkinter grid() method


The grid() geometry manager organizes the widgets in the tabular form. We can
specify the rows and columns as the options in the method call. We can also specify
the column span (width) or rowspan(height) of a widget.

This is a more organized way to place the widgets to the python application. The
syntax to use the grid() is given below.

Syntax
widget.grid(options)

A list of possible options that can be passed inside the grid() method is given below.

o Column
The column number in which the widget is to be placed. The leftmost column
is represented by 0.
o Columnspan
The width of the widget. It represents the number of columns up to which, the
column is expanded.
o ipadx, ipady
It represents the number of pixels to pad the widget inside the widget's
border.
o padx, pady
It represents the number of pixels to pad the widget outside the widget's
border.
303
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
o row
The row number in which the widget is to be placed. The topmost row is
represented by 0.
o rowspan
The height of the widget, i.e. the number of the row up to which the widget is
expanded.
o Sticky
If the cell is larger than a widget, then sticky is used to specify the position of
the widget inside the cell. It may be the concatenation of the sticky letters
representing the position of the widget. It may be N, E, W, S, NE, NW, NS, EW,
ES.

Example:
1. # !/usr/bin/python3
2. from tkinter import *
3. parent = Tk()
4. name = Label(parent,text = "Name").grid(row = 0, column = 0)
5. e1 = Entry(parent).grid(row = 0, column = 1)
6. password = Label(parent,text = "Password").grid(row = 1, column = 0)
7. e2 = Entry(parent).grid(row = 1, column = 1)
8. submit = Button(parent, text = "Submit").grid(row = 4, column = 0)
9. parent.mainloop()

Output:

Python Tkinter place() method


The place() geometry manager organizes the widgets to the specific x and y
coordinates.

Syntax
1. widget.place(options)

304
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training
A list of possible options is given below.

o Anchor: It represents the exact position of the widget within the container.
The default value (direction) is NW (the upper left corner)
o bordermode: The default value of the border type is INSIDE that refers to
ignore the parent's inside the border. The other option is OUTSIDE.
o height, width: It refers to the height and width in pixels.
o relheight, relwidth: It is represented as the float between 0.0 and 1.0
indicating the fraction of the parent's height and width.
o relx, rely: It is represented as the float between 0.0 and 1.0 that is the offset in
the horizontal and vertical direction.
o x, y: It refers to the horizontal and vertical offset in the pixels.

Example:
1. # !/usr/bin/python3
2. from tkinter import *
3. top = Tk()
4. top.geometry("400x250")
5. name = Label(top, text = "Name").place(x = 30,y = 50)
6. email = Label(top, text = "Email").place(x = 30, y = 90)
7. password = Label(top, text = "Password").place(x = 30, y = 130)
8. e1 = Entry(top).place(x = 80, y = 50)
9. e2 = Entry(top).place(x = 80, y = 90)
10. e3 = Entry(top).place(x = 95, y = 130)
11. top.mainloop()
Output:

305
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.
22+ Years of Excellence in IT Training

306
# 7-20, 4th Floor, Beside Konark Theater, Dilsukhnagar, Hyderabad, Telangana, India – 500 060.
+91-9399974756 / 9030061377 / 8712991377. +91-406625 2272 / 73 / 74.

You might also like