Python Complete Material
Python Complete Material
COURSE
MATERIAL
https://svinfotech.in/
22+ Years of Excellence in IT Training
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
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
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.
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.
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’.
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:
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:
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
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
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
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
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
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
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:
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
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:
a = True
b = False
print(a and b)
print(a or b)
print(not a)
print(a and a)
Output:
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:
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
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
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("Nireekshan" in names)
print("Hari" in names)
a = 25
b = 25
print(id(a))
print(id(b))
Output:
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:
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
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
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
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.
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
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:
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
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
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:
num = 1
print("num==1 condition gives: ", (num==1))
if num == 1:
print("if block statements executed")
Output:
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:
num = 1
print("num==1 condition gives: ", (num==1))
if num == 1:
print("if block statements executed")
else:
print("else block statements executed")
Output:
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:
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:
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)
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:
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:
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= "python"
for ch in x:
print(ch)
Output:
Example: Printing elements by using range() function and for loop (demo16.py)
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)
while True:
print("Hello")
Output:
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).
values = range(5)
for x in values:
print("item is available")
else:
print("sorry boss, item is not available")
Output:
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:
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)
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.
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)
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:
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
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:
name ="Python"
for a in name:
print(a)
Output:
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)
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:
a = "Python"
b=3
print(a*b)
Output: PythonPythonPython
Example: Multiplication (Demo16.py)
a = "Python"
b = "3"
print(a*b)
Output:
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:
Output2:
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:
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:
s1 = "abcd"
s2 = "abcd "
print(s1 == s2)
if(s1 == s2):
print("Both are same")
else:
print("not same")
Output:
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:
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)
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:
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:
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:
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.
# 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:
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:
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:
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
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)
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)
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:
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:
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:
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:
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)
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)
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)
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:
def m():
yield 'Mahesh'
yield 'Suresh'
g = m()
print(g)
print(type(g))
for y in g:
print(y)
Output:
def m():
yield 'Mahesh'
yield 'Suresh'
g = m()
print(type(g))
print(next(g))
print(next(g))
Output:
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
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)
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:
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)
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:
import module1
import addmultiplication
print(dir(module1))
print(dir(addmultiplication))
Output:
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
l1 = []
print(l1)
print(type(l1))
Output:
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:
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:
Note: IndexError: If we are trying to access beyond the range of list index, then
we will get IndexError.
Example: List Indexing (demo5.py)
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:
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
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:
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)
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)
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:
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:
n=[1, 2, 3, 4, 5]
print(n.pop(10))
Output:
Difference between remove() and pop()
n=[1, 2, 3, 4, 'two']
print(n)
n.reverse()
print(n)
Output:
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:
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)
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:
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)
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)
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)
a = [80, 90]
b = [10, 20, 30, a]
print(b[0])
print(b[1])
print(b[2])
print(b[3])
Output:
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
employee_ids = 1, 2, 3, 4, 5
print("same type of objects:",employee_ids)
print(type(employee_ids))
Output
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
name =("Sushanth",)
print(name)
print(type(name))
Output
emp_id = ()
print(emp_id)
print(type(emp_id))
Output
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
Output:
Example: Using Tuple Function (demo11.py)
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:
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:
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)
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)
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
s = {10,20,30,40}
print(s)
print(type(s))
Output:
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)
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:
d={}
print(d)
print(type(d))
s=set()
print(s)
print(type(s))
Output:
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:
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:
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:
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:
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:
s= {1, 2, 3, "Sharuk"}
print(s)
print(1 in s)
print('S' in s)
print(2 not in s)
Output:
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
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)
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)
While accessing, if the specified key is not available then we will get KeyError
Example: KeyError (demo4.py)
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={}
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
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)
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
Output:
dict([tuple1,tuple2]):
This function creates a dictionary with the given list of tuple elements
Example:
Output:
len() function:
This function returns the number of items in the dictionary
Example:
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:
Example:
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:
Example:
d= {}
d.popitem()
print("After popitem:", d)
Output:
keys() method:
This method returns all keys associated with the dictionary.
Example:
values() method:
This method returns all values associated with the dictionary
Example:
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:
copy() method:
To create an exactly duplicate dictionary (cloned copy)
Example:
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
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:
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:
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:
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:
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:
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:
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:
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
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:
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:
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:
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:
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:
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:
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:
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:
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
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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
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:
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
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:
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:
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:
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:
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:
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:
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:
Output2:
Output3:
Output4:
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
Output2:
Output3:
Output4:
Output2:
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:
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
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
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:
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:
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:
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:
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:
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:
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:
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
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:
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:
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:
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: 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
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:
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:
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:
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:
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:
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)
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:
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:
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:
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)
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)
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:
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)
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
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)
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)
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:
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.
https://files.pythonhosted.org/packages/8f/6d/fb8ebcbbaee68b172ce3dfd
08c7b8660d09f91d8d5411298bcacbd309f96/mysql-connector-python-
8.0.13.tar.gz to download the source code.
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.
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.
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.
Pass the database details like HostName, username, and the database password in the method
call. The method returns the connection object.
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.
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)
Eg:
import mysql.connector
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',)
import mysql.connector
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()
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.
Example:
import mysql.connector
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")
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
try:
#inserting the values into the table
cur.execute(sql,val)
except:
myconn.rollback()
print(cur.rowcount,"record inserted!")
myconn.close()
try:
#inserting the values into the table
cur.execute(sql,val)
except:
myconn.rollback()
print("Error in inserting");
myconn.close()
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()
val = ("Mike",105,28000,202,"Guyana")
try:
#inserting the values into the table
cur.execute(sql,val)
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
try:
#Reading the Employee data
cur.execute("select * from Employee")
for x in result:
print(x);
except:
myconn.rollback()
myconn.close()
Output:
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')
try:
#Reading the Employee data
cur.execute("select name, id, salary from Employee where name like
'%A%'")
print("Name id Salary");
myconn.close()
try:
#Reading the Employee data
cur.execute("select name, id, salary from Employee")
except:
myconn.rollback()
myconn.close()
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")
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
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%'")
print("Name id Salary");
myconn.close()
Output:
Name id Salary
John 101 25000
John 102 25000
try:
#Reading the Employee data
cur.execute("select name, id, salary from Employee where id in
(101,102,103)")
print("Name id Salary");
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
Example:
import mysql.connector
try:
#Reading the Employee data
cur.execute("select name, id, salary from Employee order by name")
print("Name id Salary");
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
try:
#Reading the Employee data
cur.execute("select name, id, salary from Employee order by name
desc")
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.
Example:
import mysql.connector
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");
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
Example:
import mysql.connector
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.
Now, let's create a python script that joins the two tables on the common column, i.e.,
dept_id.
Example:
import mysql.connector
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.
This will insert an employee Alex who doesn't work for any department
(department id is null).
Example:
import mysql.connector
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
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
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.
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.
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.
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.
10 Message The Message widget is used to display the message-box 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.
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.
However, the controls are less and widgets are generally added in the less organized
manner.
Syntax:
widget.pack(options)
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()
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:
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.