0% found this document useful (0 votes)
7 views74 pages

PDF Python Notes Compress

The document provides an extensive overview of exception handling in Python, detailing the types of errors (syntax and runtime), the concept of exceptions, and the importance of handling them gracefully. It explains the structure of try-except blocks, the exception hierarchy, and various methods for managing exceptions, including multiple except blocks and handling multiple exceptions in a single block. Additionally, it emphasizes the significance of maintaining normal program flow despite errors and includes examples to illustrate these concepts.

Uploaded by

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

PDF Python Notes Compress

The document provides an extensive overview of exception handling in Python, detailing the types of errors (syntax and runtime), the concept of exceptions, and the importance of handling them gracefully. It explains the structure of try-except blocks, the exception hierarchy, and various methods for managing exceptions, including multiple except blocks and handling multiple exceptions in a single block. Additionally, it emphasizes the significance of maintaining normal program flow despite errors and includes examples to illustrate these concepts.

Uploaded by

priyaranjan
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

INDEX

1) Exception Handling …………………………………………………………………………… 2

2) Logging Module ……………………………………………………………………………… 26

3) Assertions ……………………………………………………………………………………… 30

4) File Handling …………………………………………………………………………………… 32

5) OOPs ………………………………………………………………………………………………. 52

6) Multi-Threading ……………………………………………………………………………. 141

7) Regular Expressions
Expressions ………………………………………………………………….…… 174

8) Python Data base Connectivity (PDBC) …………………………………………..


………………………………………….. 190

9) Decorators

10) Generators

11) Introduction to Web Application Development with DJango

n
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
1 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
Exception Handling
-->In any programming language there are 2-types of errors are possible
1).Syntax Errors
2).Runtime Errors

1).Syntax Errors:
-----------------------
The errors which are occurs because of invalid syntax are called as syntax errors.
Ex:
-----
x=10
if x==10
print("Hello")
SyntaxError: invalid syntax

Ex:
----
print "Hello"
SyntaxError: Missing parentheses in call to 'print'.

Note:
Programmer is responsible to correct these errors. Once all the syntax errors are
corrected then only program execution will be started.

2).Runtime Errors:
---------------------------
-->Also called as exceptions.
-->While executing the program if something goes wrong because of end user input or
programming logic or memory peoblem etc we will get Runrime
Runri me Errors.

Ex:
print(10/0)==>ZeroDivisionError: division by zero

print(10/"ten")==>TypeError: unsupported operand type(s) for /: 'int' and 'str'

x=int(input("Enter Number:"))
print(x)
D:\pythonclasses>py [Link]
Enter some umber:ten
ValueError: invalid literal for int() with base 10: 'ten'

n
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
2 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
Note: Exception handling concept applicable for Runtime Errors but not for syntax errors.

What is an Exception:
====================
An unwanted and unexpected event that distrubs normal flow of the program is
called as an exception.
Ex:
-----
ZeroDivisionError
TypeError
ValueError
FileNOtFoundError
EOFError
TyrePuncheredError
SleepingError

-->It is highly recommended


r ecommended to handle exceptions. The main objective of exception
handling is Graceful Termination of the program(i.e we should not block our resources
and we should not miss anything).

-->Exception handling does not mean repairing exception. We have to define alternative
way to continue rest of the program normally.

Ex:
----
For example our programming requirement is reading data from the remote file
locating at london. At the runtime if london file is not available then the program should
not be terminated abnormally. We have to provide local file to continue rest of the
program normally. This way of defining alternative is nothing but exception handling.

try:
read data from remote file locating at london
except FileNotFoungError:
use local file and continue rest of the program normally.

Q:What is an Exception?
Q:What is purpose of Exception Handling?
Q:What is the meaning of Exception Handling?

n
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
3 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
Default Exception Handling in Python:
-------------------------------------------------------
-->Every Exception in python is an object. For every exception type the corresponding
classes are available.
-->Whenever an exception occurs PVM will create the corresponding exception object and
will check for handling code. If the handling code is not available then python interpreter
terminates the program abnormally and prints pri nts corresponding exception information to
the console.
-->The rest of the program won't be executed.

Ex:
---

1) print("Hello")
2) print(10/0)
3) print("Hi")

o/p:D:\pythonclasses>py [Link]
Hello
Traceback (most recent call last):
File "[Link]", line 2, in <module>
print(10/0)
ZeroDivisionError: division by zero

n
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
4 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
Python's Exception Hierarchy:
------------------------------------------

BaseException

Exception SystemExit GeneratorExit KeyboardInterrupt

Attribute Arithmetic EOF Name Lookup OS Type Value


Error Error Error Error Error Error Error Error

ZeroDivision Index FileNotFound


Error Error Error

FloatingPoint Key Interrupted


Error Error Error

Overflow Permission
Error Error

TimeOut
Error

-->Every Exception in python is a class.


-->All exception classes are child classes of BaseException i.e every exception class extends
BaseException either directly or indirectly. Hence BaseException acts as root for python
Exception Hierarchy.
-->Most of the times being a programmer we have to concentrate exception and its child
classes.

Customized Exception Handling by using try-except:


--------------------------------------------------------------------------
-->It is highly recommended to handle exceptions.
-->The code which may raise exception is called as risky code and we have to take risky
code inside the try block. The corresponding handling code we have to take inside except
block.

n
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
5 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
Syn:
-----
try:
Risky code
except XXXXXX:
Handling code/alternative code

without try-except:
---------------------------

1) print("stmt-1")
2) print(10/0)
3) print("stmt-3")

o/p:D:\pythonclasses>py [Link]
stmt-1
ZeroDivisionError: division by zero

-->Abnormal termination/Non-Graceful Termination

with try-except:
----------------------

1) print("stmt-1")
2) try:
3) print(10/0)
4) except ZeroDivisionError:
5) print(10/2)
6) print("stmt-3")

o/p:
stmt-1
5.0
stmt-3
-->Normal Termination/Graceful Termination.

n
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
6 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
Control flow in try-except block:
--------------------------------------------

Ex:
----
try:
stmt-1
stmt-2
stmt-3
except XXX:
stmt-4
stm-5

case-1: If there is no Exception.


1,2,3,5 Noraml Termination.
Case-2: If an exception is raised at stmt-2 and corresponding except block is matched.
1,4,5 Normal Termination.
Case-3: If an exception is raised at stmt-2 and corresponding except block is not matched.
1, Abnormal Termination.
Case-4: If an exception is raised at stmt-4 or stmt-5 then it always abnormal termination.

Conclusions:
------------------
1).within the try block if anywhere exception raised then rest of the try block won't be
executed eventhough we handled that exception. Hence we have to take only risky code
inside the try block and length of the try block should be as less as possible.

2).In addition to try block, there may be a chance of raising exception inside except block
and finally block also.

3).If any statement which is not part of try block raises an exception then it is always
abnormal termination.

How to print exception information:


---------------------------------------------------

1) try:
2) print(10/0)
3) except ZeroDivisionError as msg:
4) print("exception raised and its description is :",msg)

o/p:
exception raised and its description is : division by zero

n
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
7 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
try with multiple except blocks:
---------------------------------------------
-->The way of handling exception is varied exception to exception. Hence for every
exception type a separate except block we have to provide. i.e try with multiple except
block is possible and recommended.
-->If try with multiple except blocks are available then based on raised exception the
corresponding except block will be executed.

Ex:
----

1) try:
2) x=int(input("Enter First Number:"))
3) y=int(input("Enter Second Number:"))
4) print(x/y)
5) except ZeroDivisionError:
6) print("can't devide with zero")
7) except ValueError:
8) print("please provide int value only")

o/p:D:\pythonclasses>py [Link]
Enter First Number:10
Enter Second Number:2
5.0

o/p:D:\pythonclasses>py [Link]
Enter First Number:10
Enter Second Number:0
can't devide with zero

o/p:D:\pythonclasses>py [Link]
Enter First Number:10
Enter Second Number:ten
please provide int value only

-->If try multiple except blocks available then the order of these except blocks is
important. Python interpreter will always consider top to bottom until matched except
block identified.

n
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
8 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
Ex:
----

1) try:
2) x=int(input("Enter First Number:"))
3) y=int(input("Enter Second Number:"))
4) print(x/y)
5) except ArithmeticError:
6) print("ArithmeticError")
7) except ZeroDivisionError:
8) print("can't devide with zero")

o/p:D:\pythonclasses>py [Link]
Enter First Number:10
Enter Second Number:0
ArithmeticError

Ex:
----

1) try:
2) x=int(input("Enter First Number:"))
3) y=int(input("Enter Second Number:"))
4) print(x/y)
5) except ZeroDivisionError:
6) print("can't devide with zero")
7) except ArithmeticError:
8) print("ArithmeticError")

o/p:D:\pythonclasses>py [Link]
Enter First Number:10
Enter Second Number:0
can't devide with zero

Single except block that can handle multiple exceptions:


--------------------------------------------------------------------------------
-->We can write single except block that can be handle multiple diferent types of
exceptions.

except(Exception1,Exception2,Exception3.....)
except(Exception1,Exception2,Exception3.....) as msg

-->Parenthesis are mandatory ans this group of exceptions internally considered as tuple.

n
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
9 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
3)

1) else:
2) print("Hi.....")

4)

1) finally:
2) print("Hi.......")

5)

1) try:
2) print("try")
3) except:
4) print("except")

6)

1) try:
2) print("try")
3) print(10/0)
4) finally:
5) print("finally")

7)

1) try:
2) print("try")
3) except:
4) print("except")
5) else:
6) print("else")

8)

1) try:
2) print("try")
3) else:
4) print("else")

n
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
19 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
9)

1) try:
2) print("try")
3) else:
4) print("else")
5) finally:
6) print("finally")

10)

1) try:
2) print("try")
3) except XXX:
4) print("except1")
5) except YYY:
6) print("except2")

11)

1) try:
2) print("try")
3) except:
4) print("except")
5) else:
6) print("else")
7) else:
8) print("else")

12)

1) try:
2) print("try")
3) except:
4) print("except")
5) finally:
6) print("finally")
7) finally:
8) print("finally")

13)

1) try:
2) print("try")
3) print("Hello....")

n
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
20 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
4) except:
5) print("except")

14)

1) try:
2) print("try")
3) except:
4) print("except")
5) print("Hello")
6) except:
7) print("except")

15)

1) try:
2) print("try")
3) except:
4) print("except")
5) print("Hello")
6) finally:
7) print("finally")

16)

1) try:
2) print("try")
3) except:
4) print("except")
5) print("Hello")
6) else:
7) print("else")

17)

1) try:
2) print("try")
3) except:
4) print("except")
5) try:
6) print("try")
7) except:
8) print("except")

n
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
21 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
18)

1) try:
2) print("try")
3) except:
4) print("except")
5) try:
6) print("try")
7) finally:
8) print("finally")

19)

1) try:
2) print("try")
3) except:
4) print("except")
5) if 10>20:
6) print("if")
7) else:
8) print("else")

20)

1) try:
2) print("try")
3) try:
4) print("inner try")
5) except:
6) print("inner except")
7) finally:
8) print("inner finally")
9) except:
10) print("except")

21)

1) try:
2) print("try")
3) except:
4) print("except")
5) try:
6) print("inner try")
7) except:
8) print("inner except")
n
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
22 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
9) finally:
10) print("inner finally")

22)

1) try:
2) print("try")
3) except:
4) print("except")
5) finally:
6) print("finally")
7) try:
8) print("inner try")
9) except:
10) print("inner except")
11) finally:
12) print("inner finally")

23)

1) try:
2) print("try")
3) except:
4) print("except")
5) try:
6) print("try")
7) else:
8) print("else")

24)

1) try:
2) print("try")
3) try:
4) print("inner try")
5) except:
6) print("except")

25)

1) try:
2) print("try")
3) else:
4) print("else")
5) except:
n
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
23 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
6) print("except")
7) finally:
8) print("finally")

Types of Exceptions:
------------------------------
-->In python there are 2-types of exceptions are possible.
1).Predefined Exception
2).User Defined Exception

1).Predefined Exception:
-----------------------------------
-->Also known as inbuilt exceptions.
-->The exceptions which are raised automatically by python virtual machine whenever a
partucular event occurs, are called as pre defined exceptions.

Ex:Whenevr we are trying to perfrom Division by zero, automatically python will raise
ZeroDivisionError.
print(10/0)==>ZeroDivisionError

Ex: Whenevr we are trying to convert input value to int type and if input value is not int
value python will raise ValueError automatically.
x=int("ten")==>ValueError

2).User Defined Exceptions:


---------------------------------------
-->Also known as Cistomized Exceptions or programatic Exceptions.
-->Some times we have to define and raise exceptions explicitly to indicate that something
goes wrong, such type of exceptions are called as user defined exceptions or customized
exceptions.
-->Programmer is responsible to define these exceptions and python not having any idea
about these. Hence we have to raise explicitly based on our requirement by using "raise"
keyword.

Ex:
----
InSufficientFundsException
InvalidInputException
TooYoungException
TooOldException

n
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
24 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
How to Define and Raised Customized Exceptions:
----------------------------------------------------------------------
-->Every exception in python is a class that extends Exception class either directly or
indirectly.

Syn:
------
class classname(parent Exception class name):
def __init__(self,arg):
[Link]=arg

Ex:
----

1) class TooYoungException(Exception):
2) def __init__(self,arg):
3) [Link]=arg
4) class TooOldException(Exception):
5) def __init__(self,arg):
6) [Link]=arg
7) age=int(input("Enter Age:"))
8) if age>60:
9) raise TooYoungException("Plz wait some more time you will get best match
soon!!!!")
10) elif age<18:
11) raise TooOldException("Your age already crossed marriage age...no chance
of getting marriage")
12) else:
13) print("You will get match details soon by email......")

Note:
raise keyword is best suitable for customized exceptions but not for pre defined
exceptions.

n
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
25 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
Logging Module
Logging the Exceptions:
=====================
-->It is highly recommended to store complete application flow and exceptions
information to a file. This process is called as logging.
-->The main advantages of logging are:
1).We can use log files while perfroming debugging.
2).We can provide statsics like number of requests per day etc...
-->To implement logging, Python provides one inbuilt module logging.

logging levels:
--------------------
-->Depending on type of information, logging data is divided according to the following 6-
levels in python.

1).CRITICAL==>50==>Represents a very seroius problem that needs hogh attention.


2).ERROR==>40==>Represents a seroius error.
3).WARNING==>30==>Represents a warning message, some caution needed. It is an alert
to the programmer.
4).INFO==>20==>Represents a message with some important information.
5).DEBUG==>10==>Represents a message with debugging iformation.
6).NOTSET==>0==>Represents that level is not set.

How to implement logging:


--------------------------------------
-->To perform logging, first we required to create a file to store messages and we have to
specify which level messages we have to store.
-->We can do this by using basicConfig() function of logging module.
-->[Link](filename='[Link]',level=[Link])
-->The above line will create a file [Link] and we can store either WARNING level or
higher level messages to that file.
-->After creating log file, we can write messages to that file by using the following
methods.
[Link](message)
[Link](message)
[Link](message)
[Link](message)
[Link](message)

n
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
26 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
File Handling
-->As part of the programming requirement, we have to store our data permanently for
future purpose. For this requirement we should go for files.
-->Files are are very common permenant storage areas to store our data.

Types of Files:
----------------------
-->There are 2-tyes of files.
1).Text Files
2).Binary Files

1).Text Files:
-------------------
-->Usually we can use text files to store characters data.
Ex: [Link]

2).Binary Files:
---------------------
-->Usually we can use binary files to store binary data like images, video files,audio files
etc...

Opening a file:
---------------------
-->Before performing any operation(like read or write) on the file, first we have to open
that file. For this we should use python's inbuilt function open().
-->But the time of the open, we have to specify mode, which represents
repr esents the purpose of
opening file.

Syn: f=open(filename,mode)

-->The allowed modes in python are

1).r-->Open an exidting file for read operations. The filepointer is positioned at the
beginning ofthe file. If the specified file does not exist then we will get FileNotFoundError.
This is default mode.

2).w-->Open an existing file for write operation. If the file already contains some data
then it will be overridden. If the specified file is not already available then this mode will
create the file.

n
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
32 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
3).a-->Open an existing file for append operation. It won't override existing data. If the
specified file is not already available then this mode will create a new file.

4).r+-->To read and write data into the file. The prevoius data in the file will not be
deleted. The file pointer is placed at the beggining of the file.

5).w+-->To write andread data. It will override existing data.

6).a+-->To append and read data from the file. It won't override existing data.

7).x-->To open a file in exclusive creating mode for write operation. Ifthe file already exists
then we will get FileExistError.

Note:
All the baove modes are applicable for text files. Ifthe above modes suffixed with
'b' then these represents for binary files.

Ex:rb,wb,ab,r+b,w+b,a+b,xb

Ex:f=open("[Link]","w")
-->We are pening [Link] file for writting data.

Closing a File:
--------------------
-->After completing our operations on the file, it is highly recommended to close the file.
For this we have to use close() function.
[Link]()

Various properties of File Object:


-----------------------------------------------
-->Once we opened a file and we got file object, we can get various details related to that
file byusing its properties.

name-->Name of the opened file.


mode-->Mode in which the file is opened.
closed-->returns boolean value indicates that file is closed or not.
readable()-->Returns a boolean value indicates that whether file is readable or not.
writable()-->Returns a boolean value indicates that whether file is writable or not.

n
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
33 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
Ex:
----

1) f=open("[Link]","w")
2) print("File Name:",[Link])
3) print("File Mode:",[Link])
4) print("Is File Readable:",[Link]())
5) print("Is File Writable:",[Link]())
6) print("Is File Closed:",[Link])
7) [Link]()
8) print("Is File Closed:",[Link])

o/p:D:\pythonclasses>py [Link]
File Name: [Link]
File Mode: w
Is File Readable: False
Is File Writable: True
Is File Closed: False
Is File Closed: True

Writting data to text file:


-------------------------------------
-->We can write character data to the text files by using the following 2-methods.
1).write(str)
2).writelines(list of lines)
Ex:
-----

1) f=open("[Link]","w")
2) [Link]("Durga\n")
3) [Link]("Software\n")
4) [Link]("Solutions\n")
5) print("Data written to the file successfully")
6) [Link]()

[Link]:
------------
Durga
Software
Solutions

Note: In the above program, data present in the file will be overridden everytime if we are
run the program. Instead of overriding if we want to append operation then we should
open the file as follows. f=open("[Link]","a")

n
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
34 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
Ex-2:
-------

1) f=open("[Link]","w")
2) list=["sunny\n","bunny\n","chinny\n","pinny"]
3) [Link](list)
4) print("List of lines written to the file successfully")
5) [Link]()

[Link]:
------------
sunny
bunny
chinny
pinny

Note:
while writting data by using write() methods, compulsory we have to provide line
separator(\n), otherwise total data should be written in a single line.

Reading character data from the text files:


------------------------------------------------------------
-->We can read character data from the text file by using following methods.
read()==>To read all data from the file.
read(n)==>To read 'n' characters from the file.
readline()==>To read only one line.
readlines()==>To read all lines into a list.

Ex-1: To readtotal data from the file


--------------------------------------------------

1) f=open("[Link]","r")
2) data=[Link]()
3) print(data)
4) [Link]()

o/p:
sunny
bunny
chinny
pinny

n
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
35 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
Ex-2:To read only first 10 characters
----------------------------------------------------

1) f=open("[Link]","r")
2) data=[Link](10)
3) print(data)
4) [Link]()

o/p:
sunny
bunn

Ex-3:To read data line by line


------------------------------------------

1) f=open("[Link]",'r')
2) line1=[Link]()
3) print(line1,end='')
4) line2=[Link]()
5) print(line2,end='')
6) line3=[Link]()
7) print(line3,end='')
8) [Link]()

o/p:
sunny
bunny
chinny

Ex-4:To read all lines into list:


------------------------------------------

1) f=open("[Link]","r")
2) lines=[Link]()
3) print(type(lines))
4) for line in lines:
5) print(line,end='')
6) [Link]()

o/p:D:\pythonclasses>py [Link]
<class 'list'>
sunny
bunny
chinny
pinny
n
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
36 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
Ex-5:
-------

1) f=open("[Link]","r")
2) print([Link](3))
3) print([Link]())
4) print([Link](4))
5) print("Remaining Data")
6) print([Link]())
7) [Link]()

o/p:D:\pythonclasses>py [Link]
sun
ny

bunn
Remaining Data
y
chinny
pinny

The with statement:


-----------------------------
-->The with statement can be used while opening a file. we acn use this to group file
operation statements with a block.
-->The advantage of with statement is it will take care closing of file, after completing all
operations automatically even in case of exceptions also, and we are not required to close
explicitly.

Ex:
----

1) with open("[Link]","w") as f:
2) [Link]("Durrgs\n")
3) [Link]("Software\n")
4) [Link]("Solutions\n")
5) print("Is file is closed:",[Link])
6) print("Is file is closed:",[Link])

o/p:D:\pythonclasses>py [Link]
Is file is closed: False
Is file is closed: True

n
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
37 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
The tell() and seek() methods:
-------------------------------------------

tell():
-------
We can use tell() method to return current position of the cursor(file pointer) from
beginning of the file.[can u please tell current position]

The position(index) of first character in file is zero just like string index.
Ex:
-----

1) f=open("[Link]","r")
2) print([Link]())
3) print([Link](3))
4) print([Link]())
5) print([Link](5))
6) print([Link]())

[Link]:
-----------

1) Durga
2) Software
3) Solutions

o/p:D:\pythonclasses>py [Link]
0
Dur
3
ga
So
9

seek():
---------
We can use seek() method to move cursor(file pointer)to specifed location.
[can u please seek the cursor to a particular location]
[Link](offset,fromwhere)
offset represents the number of positions.
-->The allowed values for second attribute(from where) are:
0-->From beginning of file(default value)
1-->From current position
2-->From end of the file

n
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
38 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
o/p:D:\pythonclasses>py [Link]
Employee deatils:
100 Mahesh Hyd
102 Durga Hyd
104 Sunny Hyd
All employees completed

n
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
51 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
Python's Object Oriented Programming (OOP's)
=====================================================
What is class:
-------------------
-->In python every thing is an object. To create objects we required some Model or plan or
Blue print, which is nothing but a class.
-->We can write a class to represent properties(attributes) and actions(behaviour)
ofobject.
-->Properties can be represented by variables.
-->Actions can be represented by methods.
-->Hence class contains both variables and methods.

How to define a class?


--------------------------------
-->We can define a class by using class keyword.

Syn:
------
class className:
'''documentation string'''
variables:Instance, static and local variables
methods:Instance, static, class methods

-->Documentation string represents description of the class. Within the class doc string is
always optional. We can get doc string by using following 2-ways.
1).print(classname.__doc__)
2).help(classname)

Ex:
----

1) class Student:
2) '''''This is student class with required data'''
3) print(Student.__doc__)
4) help(Student)

-->With in the python classes we can represent data by using variables.


-->There are 3-types of variables are allowed.
1).Instance Variables(Object Level Variables)
2).Static Variables(Class Level Variables)
3).Local Variables(Method Level Variables)

-->Within the python class we can represent operations by using methods. The following
are various types of allowed methods.

n
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
52 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
1).Instance Methods
2).Class Methods
3).Static Methods

Example for a class:


----------------------------

1) class Student:
2) '''Developed by mahesh for python demo'''
3) def __init__(self):
4) [Link]="Mahesh"
5) [Link]=30
6) [Link]=100
7) def talk(self):
8) print("Hello I Am:",[Link])
9) print("My Age Is:",[Link])
10) print("My Marks Are:",[Link])

What is an object?
-------------------------
-->Physicalexistance of class is nothing but object. We can create any number of objects
for a class.
Syn:
ReferenceVariable=ClassName()
Ex:
s=Student()

What is a Reference Variable?


------------------------------------------
-->The variable which can be used to refer an object is called as referenece variable.
-->By using reference variable, we can access properties and methods of an object.

Ex:
w.a.p to create a Student class and creates an object to it. Call the method talk() to
display student details.

1) class Student:
2)
3) def __init__(self,name,rollno,marks):
4) [Link]=name
5) [Link]=rollno
6) [Link]=marks
7)
8) def talk(self):

n
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
53 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
9) print("Hello My Name Is:",[Link])
10) print("My Roll No:",[Link])
11) print("My Marks Are:",[Link])
12)
13) s=Student("Mahesh",101,90)
14) [Link]()

self Variable:
------------------
-->self is a default variable which is always pointing to current object(like this keyword in
java).
-->By using self we can access instance variables and instance methods of object.

Note:
-------
1).self should be first parameter inside constructor.
def __init__(self):

2).self should be first parameter inside instance methods.


def talk(self):

Constructor Concept:
===================
-->Constructor is a special method in Python.
-->The name of the constructor should be __init__(self).
-->Constructor will be executed automatically at the time of object creation.
-->The main purpose of constructor is to declare and initialize instance variables.
-->Per object constructor will be executed once.
-->Constructor can take atleast one argument(atleast self).
-->Constructor is optional and if we are not providing any constructor python will provide
default constructor.

Ex:
-----

1) def __init__(self,name,rollno,marks):
2) [Link]=name
3) [Link]=rollno
4) [Link]=marks

n
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
54 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
Program to demonistrate constructor will execute only once per object:
-----------------------------------------------------------------------------------------------------

1) class Test:
2) def __init__(self):
3) print("Constructor exeuction...")
4) def m1(self):
5) print("Method execution...")
6) t1=Test()
7) t2=Test()
8) t3=Test()
9) t1.m1()

Output:
----------
Constructor exeuction...
Constructor exeuction...
Constructor exeuction...
Method execution...

Program:
-------------

1) class Student:
2) ''''' This is student class with required data'''
3) def __init__(self,x,y,z):
4) [Link]=x
5) [Link]=y
6) [Link]=z
7) def display(self):
8) print("Student Name:{}\nRollno:{}
\nMarks:{}".format([Link],[Link],[Link]))
9) s1=Student("Mahesh",101,80)
10) [Link]()
11) s2=Student("Sunny",102,100)
12) [Link]()

Output:
Student Name:Mahesh
Rollno:101
Marks:80
Student Name:Sunny
Rollno:102
Marks:100

n
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
55 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
Types of Methods:
================
Inside Python class 3 types of methods are allowed
1. Instance Methods
2. Class Methods
3. Static Methods

1. Instance Methods:
==================
Inside method implementation if we are using instance variables then such type of
methods are called instance methods. Inside instance method declaration,we have to pass
self variable.

def m1(self):

By using self variable inside method we can able to access instance variables.

Within the class we can call instance method by using self variable and from outside of the
class we can call by using object reference.

1) class Student:
2) def __init__(self,name,marks):
3) [Link]=name
4) [Link]=marks
5) def display(self):
6) print("Hi",[Link])
7) print("Your marks are:",[Link])
8) def grade(self):
9) if [Link]>=60:
10) print("You got First Grade")
11) elif [Link]>=50:
12) print("You got Second Grade")
13) elif [Link]>=35:
14) print("You got Third Grade")
15) else:
16) print("You are failed")
17) n=int(input("Enter number of students:"))
18) for i in range(n):
19) name=input("Enter Name:")
20) marks=int(input("Enter Marks:"))
21) s=Student(name,marks)
22) [Link]()
23) [Link]()
24) print()

n
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
71 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
ouput:
D:\pythonclasses>py [Link]
Enter number of students:2
Enter Name:Mahesh
Enter Marks:90
Hi Mahesh Your Marks are: 90
You got First Grade

Enter Name:Sunny
Enter Marks:12
Hi Sunny Your Marks are: 12
You are Failed

Setter and Getter Methods:


========================
We can set and get the values of instance variables by using getter and setter methods.

Setter Method:
=============

Setter methods can be used to set values to the instance variables. setter methods also
known as mutator methods.

Syntax:

def setVariable(self,variable):
[Link]=variable

Example:

def setName(self,name):
[Link]=name

Getter Method:
==============
Getter methods can be used to get values of the instance variables. Getter methods also
al so
known as accessor methods.

Syntax:
def getVariable(self):
return [Link]
Example:
def getName(self):
return [Link]

n
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
72 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
Program:
-------------

1) class Student:
2) def setName(self,name):
3) [Link]=name
4)
5) def getName(self):
6) return [Link]
7)
8) def setMarks(self,marks):
9) [Link]=marks
10)
11) def getMarks(self):
12) return [Link]
13) l=[]
14) n=int(input("Enter Number of students:"))
15) for i in range(n):
16) s=Student()
17) name=input("Enter Name:")
18) [Link](name)
19) marks=int(input("Enter Marks:"))
20) [Link](marks)
21) [Link](s)
22)
23) for s in l:
24) print("Studnet Name:",[Link]())
25) print("Student Marks:",[Link]())

output:
-----------
D:\pythonclasses>py [Link]
Enter Number of students:2
Enter Name:Mahesh
Enter Marks:90
Enter Name:Durga
Enter Marks:100

Studnet Name: Mahesh


Student Marks: 90
Studnet Name: Durga
Student Marks: 100

n
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
73 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
2. Class Methods:
=================

Inside method implementation if we are using only class variables (static variables), then
such type of methods we should declare as class method.

We can declare class method explicitly by using @classmethod decorator. For class
method we should provide cls variable at the time of declaration

We can call classmethod by using classname or object reference variable.

Demo program:
---------------------

1) class Animal:
2) legs=4
3) @classmethod
4) def walk(cls,name):
5) print("{} walks with {}legs......".format(name,[Link]))
6) [Link]("Dog")
7) [Link]("Cat")

o/p:D:\pythonclasses>py [Link]
Dog walks with 4legs......
Cat walks with 4legs......

w.a.p to track the number of objects created for a class


------------------------------------------------------------------------------

1) class Test:
2) count=0
3) def __init__(self):
4) [Link]=[Link]+1
5) @classmethod
6) def no_of_objects(cls):
7) print("The number of objects created for test class:",[Link])
8) t1=Test()
9) t2=Test()
10) Test.no_of_objects()
11) t3=Test()
12) t4=Test()
13) t5=Test()
14) Test.no_of_objects()

n
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
74 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
o/p:D:\pythonclasses>py [Link]
The number of objects created for test class: 2
The number of objects created for test class: 5

3. Static Methods:
=================
In general these methods are general utility methods. Inside these methods we won't use
any instance or class variables. Here we won't provide self or cls arguments at the time of
declaration.

We can declare static method explicitly by using @staticmethod decorator We can access
static methods by using classname or object reference

Note: In general we can use only instance and static [Link] static method we can
access class level variables by using class name.

class methods are most rarely used methods in python.

Program:
-------------

1) class MaheshMath:
2) @staticmethod
3) def add(x,y):
4) print("The sum is:",x+y)
5)
6) @staticmethod
7) def product(x,y):
8) print("The sum is:",x*y)
9)
10) @staticmethod
11) def average(x,y):
12) print("The sum is:",(x+y)/2)
13)
14) [Link](10,20)
15) [Link](10,20)
16) [Link](10,20)

o/p:D:\pythonclasses>py [Link]
The sum is: 30
The sum is: 200
The sum is: 15.0

n
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
75 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
Passing members of one class to another class:
------------------------------------------------------------------
We can access members of one class inside another class.

Ex:
-----

1) class Employee:
2) def __init__(self,eno,ename,esal):
3) [Link]=eno
4) [Link]=ename
5) [Link]=esal
6) def display(self):
7) print("Employee Number:",[Link])
8) print("Employee Name:",[Link])
9) print("Employee Salary:",[Link])
10)
11) class Test:
12) def modify(emp):
13) [Link]=[Link]+10000
14) [Link]()
15)
16) e=Employee(100,"Mahesh",10000)
17) [Link](e)

o/p:D:\pythonclasses>py [Link]
Employee Number: 100
Employee Name: Mahesh
Employee Salary: 20000

Inner classes:
=============
Sometimes we can declare a class inside another class,such type of classes are called inner
classes.

Without existing one type of object if there is no chance of existing another type of
object,then we should go for inner classes.

Example:
Without existing Car object there is no chance of existing Engine object. Hence Engine
class should be part of Car class.

n
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
76 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
Class Car:
.....
class Engine:
......

Example:
Without existing university object there is no chance of existing Department object

class University:
.....
class Department:
......

eg3: Without existing Human there is no chance of existin Head. Hence Head should be
part of Human.

class Human:

class Head:

Note: Without existing outer class object there is no chance of existing inner class object.
Hence inner class object is always associated with outer class object.

program:
-------------

1) class Outer:
2) def __init__(sel):
3) print("Outer class object creation")
4)
5) class Inner:
6) def __init__(self):
7) print("Inner class object creation")
8) def m1(self):
9) print("Inner class method")
10)
11) o=Outer()
12) i=[Link]()
13) i.m1()

Note:

The following are various possible syntaxes for calling inner class method
1. o=Outer() i=[Link]() i.m1()

n
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
77 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
Garbage Collection
In old languages like C++, programmer is responsible for both creation and destruction of
[Link] programmer taking very much care while creating object, but neglecting
destruction of useless objects. Because of his neglectance, total memory can be filled with
useless objects which creates memory problems and total application will be down with
Out of memory error.

But in Python, We have some assistant which is always running in the background to
destroy useless [Link] this assistant the chance of failing Python program with
memory problems is very less. This assistant is nothing but Garbage Collector.

Hence the main objective of Garbage Collector is to destroy useless objects.

If an object does not have any reference variable then that object eligible for Garbage
Collection.

How to enable and disable Garbage Collector in our program:


======================================================

By default Gargbage collector is enabled, but we can disable based on our requirement. In
this context we can use the following functions of gc module.

1. [Link]()
Returns True if GC enabled

2. [Link]() To disable GC explicitly

3. [Link]() To enable GC explicitly

Example:

1) import gc
2) class Test:
3) print([Link]())
4) [Link]()
5) print([Link]())
6) [Link]()
7) print([Link]())

n
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
80 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
Destructors:
============
Destructor is a special method and the name should be __del__ Just before destroying an
object Garbage Collector always calls destructor to perform clean up activities (Resource
deallocation activities like close database connection etc).
Once destructor execution completed then Garbage Collector automatically destroys that
object.

Note: The job of destructor is not to destroy object and it is just to perform clean up
activities.

Example:

1) import time
2) class Test:
3) def __init__(self):
4) print("Object Initialization.....")
5) def __del__(self):
6) print("Fullfilling last wish and performing clean up activities....")
7) t1=Test()
8) t1=None
9) [Link](10)
10) print("End of application")

o/p:D:\pythonclasses>py [Link]
Object Initialization.....
Fullfilling last wish and performing clean up activities....
End of application

Note: If the object does not contain any reference variable then only it is eligible fo GC. ie
if the reference count is zero then only object eligible for GC

Example:
------------

1) import time
2) class Test:
3) def __init__(self):
4) print("Object Initialization.....")
5) def __del__(self):
6) print("Fullfilling last wish and performing clean up activities....")
7) t1=Test()
8) t2=t1
9) t3=t2

n
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
81 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
10) del t1
11) [Link](10)
12) print("object not yest destroyed after deleting t1")
13) del t2
14) print("object not yest destroyed after deleting t2")
15) del t3
16) print("By this time object will be destroyed")
17) print("End of application")

o/p:D:\pythonclasses>py [Link]
Object Initialization.....
object not yest destroyed after deleting t1
object not yest destroyed after deleting t2
Fullfilling last wish and performing clean up activities....
By this time object will be destroyed
End of application

Example:
=========

1) import time
2) class Test:
3) def __init__(self):
4) print("Constructor Execution.........")
5) def __del__(self):
6) print("Destructor Execution......")
7)
8) list=[Test(),Test(),Test()]
9) del list
10) [Link](5)
11) print("End of application")

o/p:D:\pythonclasses>py [Link]
Constructor Execution.........
Constructor Execution.........
Constructor Execution.........
Destructor Execution......
Destructor Execution......
Destructor Execution......
End of application

n
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
82 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
-->Similarly variables also

1) class P:
2) a=10
3) def __init__(self):
4) self.b=20
5) class C(P):
6) c=30
7) def __init__(self):
8) super().__init__()===>Line-1
9) self.d=30
10) c1=C() 1
11) print(c1.a,c1.b,c1.c,c1.d)

o/p:
10 20 30 40

-->If we comment Line-1 then variable b is not available to the child class.

Demo Program:
----------------------

1) class Person:
2) def __init__(self,name,age):
3) [Link]=name
4) [Link]=age
5) def eat_n_drink(self):
6) print("Drink Beer and Eat Biryani")
7)
8) class Employee(Person):
9) def __init__(self,name,age,eno,sal):
10) super().__init__(name,age)
11) [Link]=eno
12) [Link]=sal
13) def work(self):
14) print("Coding Python is vsery easy just like drinking chilled beer")
15) def emp_info(self):
16) print("Employee Name:",[Link])
17) print("Employee Age:",[Link])
18) print("Employee Number:",[Link])
19) print("Employee Salary:",[Link])
20)
21) e=Employee("Mahesh",50,100,100000)
22) e.eat_n_drink()

n
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
89 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
23) [Link]()
24) e.emp_info()

o/p:D:\pythonclasses>py [Link]
Drink Beer and Eat Biryani
Coding Python is vsery easy just like drinking chilled beer
Employee Name: Mahesh
Employee Age: 50
Employee Number: 100
Employee Salary: 100000

IS-A vs HAS-A Relationship:


---------------------------------------
-->If we want to extend existing functionality with some more extra functionality then we
should go for IS-A Relationship.

-->If we dont want to extend and just we have to use existing functionality then we should
go for HAS-A Relationship.

Eg: Employee class extends Person class Functionality


But Employee class just uses Car functionality but not extending

Person

IS - A

HAS - A
Employee Car

Program:
-------------

1) class Car:
2) def __init__(self,name,model,color):
3) [Link]=name
4) [Link]=model
5) [Link]=color
6) def get_info(self):
7) print("\tCar
name:{}\n\tModel:{}\n\tColor={}".format([Link],[Link],[Link]))
8)

n
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
90 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
9) class Person:
10) def __init__(self,name,age):
11) [Link]=name
12) [Link]=age
13) def eat_n_drink(self):
14) print("Drink Beer and Eat Biryani")
15)
16) class Employee(Person):
17) def __init__(self,name,age,eno,sal,car):
18) super().__init__(name,age)
19) [Link]=eno
20) [Link]=sal
21) [Link]=car
22) def work(self):
23) print("Coding Python is vsery easy just like drinking chilled beer")
24) def emp_info(self):
25) print("Employee Name:",[Link])
26) print("Employee Age:",[Link])
27) print("Employee Number:",[Link])
28) print("Employee Salary:",[Link])
29) print("Employee Car Info:")
30) [Link].get_info()
31)
32) c=Car("Innova","2.5v","Grey")
33) e=Employee("Mahesh",50,100,100000,c)
34) e.eat_n_drink()
35) [Link]()
36) e.emp_info()

o/p:D:\pythonclasses>py [Link]
Drink Beer and Eat Biryani
Coding Python is vsery easy just like drinking chilled beer
Employee Name: Mahesh
Employee Age: 50
Employee Number: 100
Employee Salary: 100000
Employee Car Info:
Car name:Innova
Model:2.5v
Color=Grey

-->In the above example Employee class extends Person class functionality but just uses
Car class functionality.

n
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
91 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
4).Multiple Inheritance:
---------------------------------
The concept of inheriting the properties from multiple classes into a single class at
a time, is known as multiple inheritance.

C1 C2

Hierarchical
Inheritance

Ex:
----

1) class P1:
2) def m1(self):
3) print("Parent1 Method")
4) class P2:
5) def m2(self):
6) print("Parent2 Method")
7) class C(P1,P2):
8) def m3(self):
9) print("Child Method")
10) c=C()
11) c.m1()
12) c.m2()
13) c.m3()

o/p:D:\pythonclasses>py [Link]
Parent1 Method
Parent2 Method
Child Method

-->If the same method is inherited from both parent classes,then Python will always
consider the order of Parent classes in the declaration of the child class.

class C(P1,P2): ===>P1 method will be considered


class C(P2,P1): ===>P2 method will be considered

n
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
98 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
Ex-2:
-------

1) class P1:
2) def m(self):
3) print("Parent1 Method")
4) class P2:
5) def m(self):
6) print("Parent2 Method")
7) class C(P2,P1):
8) def m1(self):
9) print("Child Method")
10) c=C()
11) c.m()
12) c.m1()

o/p:
Parent2 Method
Child Method

5).Hybrid Inheritance:
--------------------------------
Combination of Single, Multi level, multiple and Hierarchical inheritance is known
as Hybrid Inheritance.

A B C

G H

n
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
99 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
6).Cyclic Inheritance:
-------------------------------
The concept of inheriting properties from one class to another class in cyclic way, is
called Cyclic [Link] won't support for Cyclic Inheritance of course it is really
not required.

Ex-1:
--------
class A(A):pass
NameError: name 'A' is not defined

Ex-2:
-------

1) class A(B):
2) pass
3) class B(A):
4) pass
5) NameError: name 'B' is not defined

Method Resolution Order (MRO):


---------------------------------------------
-->In Hybrid Inheritance the method resolution order is decided based on MRO algorithm.
-->This algorithm is also known as C3 algorithm.
-->Samuele Pedroni proposed this algorithm.
-->It follows DLR (Depth First Left to Right)
-->i.e Child will get more priority than Parent.
-->Left Parent will get more priority than Right Parent

MRO(X)=X+Merge(MRO(P1),MRO(P2),...,ParentList)

n
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
100 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
Head Element vs Tail Terminology:
--------------------------------------------------
Assume C1,C2,C3,...are classes.
In the list : C1C2C3C4C5....
C1 is considered as Head Element and remaining is considered as Tail.

How to find Merge:


---------------------------
-->Take the head of first list.
-->If the head is not in i n the tail part of any other list,then add this head to the result and
remove it from the lists in the merge.
-->If the head is present in the tail part of any other list,then consider the head element of
the next list and continue the same process.

Note: We can find MRO of any class by using mro() function.


Syn:print([Link]())

Demo Program-1 for Method Resolution Order:


-----------------------------------------------------------------

B C

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

[Link]
----------

1) class A:pass
2) class B(A):pass
3) class C(A):pass

n
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
101 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
4) class D(B,C):pass
5) print([Link]())
6) print([Link]())
7) print([Link]())
8) print([Link]())

o/p:
[<class '__main__.A'>, <class 'object'>]
[<class '__main__.B'>, <class '__main__.A'>, <class 'object'>]
[<class '__main__.C'>, <class '__main__.A'>, <class 'object'>]
[<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>,
<class 'object'>]

Demo Program-2 for Method Resolution Order:


-----------------------------------------------------------------

Object

A B C

X Y

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

n
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
102 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
Finding mro(P) by using C3 algorithm:
------------------------------------------------------
Formula: MRO(X)=X+Merge(MRO(P1),MRO(P2),...,ParentList)

1) mro(p)= P+Merge(mro(X),mro(Y),mro(C),XYC)
2) = P+Merge(XABO,YBCO,CO,XYC)
3) = P+X+Merge(ABO,YBCO,CO,YC)
4) = P+X+A+Merge(BO,YBCO,CO,YC)
5) = P+X+A+Y+Merge(BO,BCO,CO,C)
6) = P+X+A+Y+B+Merge(O,CO,CO,C)
7) = P+X+A+Y+B+C+Merge(O,O,O)
8) = P+X+A+Y+B+C+O

[Link]:
-----------

1) class A:pass
2) class B:pass
3) class C:pass
4) class X(A,B):pass
5) class Y(B,C):pass
6) class P(X,Y,C):pass
7) print([Link]())#AO
8) print([Link]())#XABO
9) print([Link]())#YBCO
10) print([Link]())#PXAYBCO

Output:
-----------
[<class '__main__.A'>, <class 'object'>]
[<class '__main__.X'>, <class '__main__.A'>, <class '__main__.B'>, <class 'object'>]
[<class '__main__.Y'>, <class '__main__.B'>, <class '__main__.C'>, <class 'object'>]
[<class '__main__.P'>, <class '__main__.X'>, <class '__main__.A'>, <class '__main__.Y'>,
<class '__main__.B'>, <class '__main__.C'>, <class 'object'>]

[Link]:
-----------

1) class A:
2) def m1(self):
3) print('A class Method')
4) class B:
5) def m1(self):
6) print('B class Method')

n
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
103 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
7) class C:
8) def m1(self):
9) print('C class Method')
10) class X(A,B):
11) def m1(self):
12) print('X class Method')
13) class Y(B,C):
14) def m1(self): 1
15) print('Y class Method')
16) class P(X,Y,C):
17) def m1(self):
18) print('P class Method')
19) p=P()
20) p.m1()

Output:
-----------
P class Method

-->In the above example P class m1() method will be considered.


-->If P class does not contain m1() method then as per MRO, X class method will be
considered.
-->If X class does not contain then A class method will be considered and this process will
be continued.

-->The method resolution in the following order:PXAYBCO

Demo Program-3 for Method Resolution Order:


------------------------------------------------------------------

Object

D E F

B C

A
n
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
104 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
1) mro(o)=object
2) mro(D)=D,object
3) mro(E)=E,object
4) mro(F)=F,object
5) mro(B)=B,D,E,object
6) mro(C)=C,D,F,object
7) mro(A)=A+Merge(mro(B),mro(C),BC)
8) =A+Merge(BDEO,CDFO,BC)
9) =A+B+Merge(DEO,CDFO,C)
10) =A+B+C+Merge(DEO,DFO)
11) =A+B+C+D+Merge(EO,FO)
12) =A+B+C+D+E+Merge(O,FO)
13) =A+B+C+D+E+F+Merge(O,O)
14) =A+B+C+D+E+F+O

[Link]:
----------

1) class D:pass
2) class E:pass
3) class F:pass
4) class B(D,E):pass
5) class C(D,F):pass
6) class A(B,C):pass
7) print([Link]())
8) print([Link]())
9) print([Link]())
10) print([Link]())

Output:
-----------
[<class '__main__.D'>, <class 'object'>]
[<class '__main__.B'>, <class '__main__.D'>, <class '__main__.E'>, <class 'object'>]
[<class '__main__.C'>, <class '__main__.D'>, <class '__main__.F'>, <class 'object'>]
[<class '__main__.A'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.D'>,
<class '__main__.E'>, <class '__main__.F'>, <class 'object'>]

n
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
105 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
super() Method:
----------------------
super() is a built-in method which is useful to call the super class
constructors,variables and methods from the child class.

Demo Program-1 for super():


----------------------------------------

1) class Person:
2) def __init__(self,name,age):
3) [Link]=name
4) [Link]=age 5)
5) def display(self):
6) print('Name:',[Link])
7) print('Age:',[Link])
8) class Student(Person):
9) def __init__(self,name,age,rollno,marks):
10) super().__init__(name,age)
11) [Link]=rollno
12) [Link]=marks
13) def display(self):
14) super().display() 17)
15) print('Roll No:',[Link])
16) print('Marks:',[Link])
17) s1=Student('Mahesh',22,101,90)
18) [Link]()

Output:
Name: Mahesh
Age: 22
Roll No: 101
Marks: 90

-->In the above program we are using super() method to call parent class constructor and
display() method.

Demo Program-2 for super():


----------------------------------------

1) class P:
2) a=10
3) def __init__(self):
4) self.b=10
5) def m1(self):

n
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
106 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
2. Method Overloading:
---------------------------------
-->If 2 methods having same name but different type of arguments then those methods
are said to be overloaded methods.

Ex: m1(int a)
m1(double d)

-->But in Python Method overloading is not possible.


-->If we are trying to declare multiple methods with same name and different number of
arguments then Python will always consider only last method.

Demo Program:
----------------------

1) class Test:
2) def m1(self):
3) print('no-arg method')
4) def m1(self,a):
5) print('one-arg method')
6) def m1(self,a,b):
7) print('two-arg method')
8) t=Test()
9) #t.m1()
10) #t.m1(10)
11) t.m1(10,20)

Output: two-arg method

-->In the above program python will consider only last method.

How we can handle overloaded method requirements in Python:


------------------------------------------------------------------------------------------
-->Most of the times, if method with variable number of arguments required then we can
handle with default arguments or with variable number of argument methods.

1) class Test:
2) def sum(self,a=None,b=None,c=None):
3) if a!=None and b!= None and c!= None:
4) print('The Sum of 3 Numbers:',a+b+c)
5) elif a!=None and b!= None:
6) print('The Sum of 2 Numbers:',a+b)
7) else: 8) print('Please provide 2 or 3 arguments')
8) t=Test()

n
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
121 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
Output:
-----------
The Sum of 2 Numbers: 30
The Sum of 3 Numbers: 60
Please provide 2 or 3 arguments

Demo Program with Variable Number of Arguments:


-------------------------------------------------------------------------

1) class Test:
2) def sum(self,*a):
3) total=0
4) for x in a:
5) total=total+x
6) print('The Sum:',total)
7) t=Test()
8) [Link](10,20)
9) [Link](10,20,30)
10) [Link](10) 13)
11) [Link]()

3. Constructor Overloading:
---------------------------------------
-->Constructor overloading is not possible in Python.
-->If we define multiple constructors then the last constructor will be considered.

1) class Test:
2) def __init__(self):
3) print('No-Arg Constructor')
4)
5) def __init__(self,a):
6) print('One-Arg constructor')
7)
8) def __init__(self,a,b):
9) print('Two-Arg constructor')
10)
11) #t1=Test()
12) #t1=Test(10)
13) t1=Test(10,20)

Output: Two-Arg constructor


-->In the above program only Two-Arg Constructor is available.
-->But based on our requirement we can declare constructor with default arguments and
variable number of arguments.

n
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
122 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
Constructor with Default Arguments:
----------------------------------------------------

1) class Test:
2) def __init__(self,a=None,b=None,c=None):
3) print('Constructor with 0|1|2|3 number of arguments')
4)
5) t1=Test()
6) t2=Test(10)
7) t3=Test(10,20)
8) t4=Test(10,20,30)

Output:
-----------
Constructor with 0|1|2|3 number of arguments
Constructor with 0|1|2|3 number of arguments
Constructor with 0|1|2|3 number of arguments
Constructor with 0|1|2|3 number of arguments

Constructor with Variable Number of Arguments:


---------------------------------------------------------------------

1) class Test:
2) def __init__(self,*a):
3) print('Constructor with variable number of arguments')
4)
5) t1=Test()
6) t2=Test(10)
7) t3=Test(10,20)
8) t4=Test(10,20,30)
9) t5=Test(10,20,30,40,50,60)

Output:
-----------
Constructor with variable number of arguments
Constructor with variable number of arguments
Constructor with variable number of arguments
Constructor with variable number of arguments
Constructor with variable number of arguments

n
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
123 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
Method overriding:
---------------------------
-->What ever members available in the parent class are bydefault available to the child
class through inheritance.
-->If the child class 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.

Demo Program for Method overriding:


-----------------------------------------------------

1) class P:
2) def property(self):
3) print('Gold+Land+Cash+Power')
4) def marry(self):
5) print('Appalamma')
6)
7) class C(P):
8) def marry(self):
9) print('Katrina Kaif')
10)
11) c=C()
12) [Link]()
13) [Link]()

Output:
-----------
Gold+Land+Cash+Power
Katrina Kaif

-->From Overriding method of child class,we can call parent class method also by using
super() method.

1) class P:
2) def property(self):
3) print('Gold+Land+Cash+Power')
4) def marry(self):
5) print('Appalamma')
6)
7) class C(P):
8) def marry(self):
9) super().marry()
10) print('Katrina Kaif')

n
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
124 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
11) c=C() 12)
12) [Link]()
13) [Link]()

Output:
-----------
Gold+Land+Cash+Power
Appalamma
Katrina Kaif

Demo Program for Constructor overriding:


------------------------------------------------------------

1) class P:
2) def __init__(self):
3) print('Parent Constructor')
4)
5) class C(P):
6) def __init__(self):
7) print('Child Constructor')
8)
9) c=C()

Output: Child Constructor

-->In the above example,if child class does not contain constructor then parent class
constructor will be executed

-->From child class constuctor we can call parent class constructor by using super()
method.

Demo Program to call Parent class constructor by using super():


------------------------------------------------------------------------------------------

1) class Person:
2) def __init__(self,name,age):
3) [Link]=name
4) [Link]=age
5)
6) class Employee(Person):
7) def __init__(self,name,age,eno,esal):
8) super().__init__(name,age)
9) [Link]=eno
10) [Link]=esal

n
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
125 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
o/p:D:\pythonclasses>py [Link]
Enter Database:Oracle
<class '__main__.Oracle'>
Connecting to Oracle Database......
Disconnecting to Oracle Database......

D:\pythonclasses>py [Link]
Enter Database:Sybase
<class '__main__.Sybase'>
Connecting to Sybase Database......
Disconnecting to Sybase Database......

Note: The inbuilt function globals()[str] converts the string 'str' into a class name and
returns the classname.

Demo Program-2:
------------------------
Reading class name from the file

[Link]:
EPSON

[Link]:
-----------

1) from abc import *


2) class Printer(ABC):
3) @abstractmethod
4) def printit(self,text):
5) pass
6) @abstractmethod
7) def disconnect(self):
8) pass
9)
10) class EPSON(Printer):
11) def printit(self,text):
12) print('Printing from EPSON Printer...')
13) print(text)
14) def disconnect(self):
15) print('Printing completed on EPSON Printer...')
16)
17) class HP(Printer):
18) def printit(self,text):
19) print('Printing from HP Printer...')

n
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
134 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
20) print(text)
21) def disconnect(self):
22) print('Printing completed on HP Printer...')
23)
24) with open('[Link]','r') as f:
25) pname=[Link]()
26)
27) classname=globals()[pname]
28) x=classname()
29) [Link]('This data has to print...')
30) [Link]()

Output:
----------
Printing from EPSON Printer...
This data has to print...
Printing completed on EPSON Printer...

Public, Protected and Private Attributes:


---------------------------------------------------------
-->By default every attribute is public. We can access from anywhere either within the
class or from outside of the class.

Ex: name='Mahesh'

[Link]:
-----------

1) class Test:
2) x=10
3) def __init__(self):
4) self.y=20

[Link]:
-------------

1) from test import Test


2) class Test1:
3) t=Test()
4) print(t.x)
5) print(t.y)

n
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
135 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
o/p:
10
20

-->Protected attributes can be accessed within the class anywhere but from outside of the
class only in child classes. We can specify an attribute as protected by prefexing with _
symbol.

syntax: _variablename=value
Ex: _name='Mahesh'

Ex:

1) class Test:
2) _x=10
3) def __init__(self):
4) self._y=20
5) t=Test()
6) print(t._x)
7) print(t._y)

o/p:
10
20

-->But is is just convention and in reality does not exists protected attributes.

-->private attributes can be accessed only within the class.i.e from outside of the class we
cannot access. We can declare a variable as private explicitly by prefexing with 2
underscore symbols.

syntax: __variablename=value
Ex: __name='Mahesh'

Demo Program:

1) class Test:
2) x=10
3) _y=20
4) __z=30
5) def m1(self):
6) print(Test.x)
7) print(Test._y)
8) print(Test.__z)

n
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
136 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
9) t=Test()
10) t.m1()
11) print(Test.x)
12) print(Test._y)
13) print(Test.__z)

Output:
----------
10
20
30
10
20
Traceback (most recent call last):
File "[Link]", line 14, in <module>
print(Test.__z)
AttributeError: type object 'Test' has no attribute '__z'

How to access private variables from outside of the class:


---------------------------------------------------------------------------------
-->We cannot access private variables directly from outside of the class.
-->But we can access indirectly as follows

objectreference._classname__variablename

Ex:

1) class Test:
2) __x=10
3) def __init__(self):
4) self.__y=20
5) t=Test()
6) print(t.__dict__)#{'_Test__y': 20}
7) print(t._Test__y)#20
8) print(Test._Test__x)#10

__str__() method:
===============
-->Whenever we are printing any object reference internally __str__() method will be
called which is returns string in the following format

<__main__.classname object at 0x022144B0>

-->To return meaningful string representation we have to override __str__() method.

n
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
137 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
Demo Program:
----------------------

1) class Student:
2) def __init__(self,name,rollno):
3) [Link]=name
4) [Link]=rollno
5) def __str__(self):
6) return 'This is Student with Name:{} and
Rollno:{}'.format([Link],[Link])
7)
8) s1=Student('Mahesh',101)
9) s2=Student('Durga',102)
10) print(s1)
11) print(s2)

o/p:D:\pythonclasses>py [Link]
This is student name:Mahesh and Roll no:101
This is student name:Durga and Roll no:102

output without overriding __str__():


-------------------------------------------------
<__main__.Student object at 0x022144B0>
<__main__.Student object at 0x022144D0>

output with overriding __str__():


--------------------------------------------
This is Student with Name:Durga and Rollno:101
This is Student with Name:Mahesh and Rollno:102

Difference between str() and repr() (OR) Difference between __str__() and __repr__():
--------------------------------------------------------------------------------------------------------------------

-->str() internally calls __str__() function and hence functionality of both is same.

-->Similarly,repr() internally calls __repr__() function and hence functionality of both is


same.

-->str() returns a string containing a nicely printable representation object.

-->The main purpose of str() is for [Link] may not possible to convert result string to
original object.

n
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
138 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
Q. What is the advantage of using with statement to acquire a lock in threading?
-----------------------------------------------------------------------------------------------------------------
-->Lock will be released automatically once control reaches end of with block and We are
not required to release explicitly.

Note:
We can use with statement in multithreading for the following cases:

1. Lock
2. RLock
3. Semaphore
4. Condition

n
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
173 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
Regular Expressions
-->If we want to represent a group of Strings according to a particular format/pattern then we
should go for Regular Expressions.

-->i.e Regualr Expressions is a declarative mechanism to represent a group of Strings accroding to


particular format/pattern.

Ex 1: We can write a regular expression to represent all mobile numbers


Ex 2: We can write a regular expression to represent all mail ids.

The main important application areas of Regular Expressions are

1. To develop validation frameworks/validation logic


2. To develop Pattern matching applications (ctrl-f in windows, grep in UNIX etc)
3. To develop Translators like compilers, interpreters etc
4. To develop digital circuits
5. To develop communication protocols like TCP/IP, UDP etc.

We can develop Regular Expression Based applications by using python module: re


This module contains several inbuilt functions to use Regular Expressions very easily in our
applications.

1. compile():
-----------------
re module contains compile() function to compile a pattern into RegexObject.
pattern = [Link]("ab")
2. finditer():
-----------------
Returns an Iterator object which yields Match object for every Match
matcher = [Link]("abaababa")

On Match object we can call the following methods.


1. start():Returns start index of the match
2. end():Returns end+1 index of the match
3. group():Returns the matched string

Ex:
-----

1) import re count=0
2) pattern=[Link]("ab")
3) matcher=[Link]("abaababa")
4) for match in matcher:

n
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
174 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
5) count+=1
6) print([Link](),"...",[Link](),"...",[Link]())
7) print("The number of occurrences: ",count)

Output:
0 ... 2 ... ab
3 ... 5 ... ab
5 ... 7 ... ab
The number of occurrences: 3

Note: We can pass pattern directly as argument to finditer() function.

Ex:
----

1) import re
2) count=0
3) matcher=[Link]("ab","abaababa")
4) for match in matcher:
5) count+=1
6) print([Link](),"...",[Link](),"...",[Link]())
7) print("The number of occurrences: ",count)

Output:
0 ... 2 ... ab
3 ... 5 ... ab
5 ... 7 ... ab
The number of occurrences: 3

Character classes:
-------------------------
We can use character classes to search a group of characters
1. [abc]===>Either a or b or c
2. [^abc] ===>Except a and b and c
3. [a-z]==>Any Lower case alphabet symbol
4. [A-Z]===>Any upper case alphabet symbol
5. [a-zA-Z]==>Any alphabet symbol
6. [0-9] Any digit from 0 to 9
7. [a-zA-Z0-9]==>Any alphanumeric character
8. [^a-zA-Z0-9]==>Except alphanumeric characters(Special Characters)

Ex:
-----

1) import re
2) matcher=[Link]("x","a7b@k9z")
3) for match in matcher:

n
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
175 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
4) print([Link](),"......",[Link]())

x = [abc]
------------
0 ...... a
2 ...... b

x = [^abc]
-------------
1 ...... 7
3 ...... @
4 ...... k
5 ...... 9
6 ...... z

x = [a-z]
-----------
0 ...... a
2 ...... b
4 ...... k
6 ...... z

x = [0-9]
-----------
1 ...... 7
5 ...... 9

x = [a-zA-Z0-9]
--------------------
0 ...... a
1 ...... 7
2 ...... b
4 ...... k
5 ...... 9
6 ...... z

x = [^a-zA-Z0-9]
---------------------
3 ...... @

Pre-defined Character classes:


------------------------------------------
\s==>Space character
\S==>Any character except space character
\d==>Any digit from 0 to 9
\D==>Any character except digit
\w==>Any word character [a-zA-Z0-9]
\W==>Any character except word character (Special Characters)

n
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
176 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
.==>Any character including special characters

Ex:
-----

1) import re
2) matcher=[Link]("x","a7b k@9z")
3) for match in matcher:
4) print([Link](),"......",[Link]())

x = \s:
---------
3 ......

x = \S:
---------
0 ...... a
1 ...... 7
2 ...... b
4 ...... k
5 ...... @
6 ...... 9
7 ...... z

x = \d:
---------
1 ...... 7
6 ...... 9

x = \D:
---------
0 ...... a
2 ...... b
3 ......
4 ...... k
5 ...... @
7 ...... z

x = \w:
----------
0 ...... a
1 ...... 7
2 ...... b
4 ...... k
6 ...... 9
7 ...... z

n
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
177 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
5) while True:
6) eno=int(input("Enter Employee Number:"))
7) ename=input("Enter Employee Name:")
8) esal=float(input("Enter Employee Salary:"))
9) eaddr=input("Enter Employee Address:")
10) sql="insert into employees values(%d,'%s',%f,'%s')"
11) [Link](sql%(eno,ename,esal,eaddr))
12) print("Record inserted successfully.......")
13) option=input("Do you want to insert one more record[Yes|No]:")
14) if option=="No":
15) [Link]()
16) break
17) except cx_Oracle.DatabaseError as e:
18) if con:
19) [Link]()
20) print("There is a problem in sql",e)
21) finally:
22) if cursor:
23) [Link]()
24) if con:
25) [Link]()

App7: Write a program to update employee salaries with increment for the certain range
with dynamic input.
---------------------------------------------------------------------------------------------------------
Ex: Increment all employee salaries by 500 whose salary < 5000

1) import cx_Oracle
2) try:
3) con=cx_Oracle.connect('scott/tiger@localhost')
4) cursor=[Link]()
5) increment=float(input("Enter Increment salary:"))
6) salrange=float(input("Enter Salary Range:"))
7) sql="update employees set esal=esal+%f where esal<%f"
8) [Link](sql%(increment,salrange))
9) print("Records are updated successfully....")
10) [Link]()
11) except cx_Oracle.DatabaseError as e:
12) if con:
13) [Link]()
14) print("There is a problem in sql",e)
15) finally:
16) if cursor:
17) [Link]()

n
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
197 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
18) if con:
19) [Link]()

App8: Write a program to delete employees whose salary greater provided salary as
dynamic input?
-------------------------------------------------------------------------------------------------------
Ex: delete all employees whose salary > 4500

1) import cx_Oracle
2) try:
3) con=cx_Oracle.connect('scott/tiger@localhost')
4) cursor=[Link]()
5) cutoffsal=float(input("Enter Cutoff Salary:"))
6) sql="delete from employees where esal>%f"
7) [Link](sql%(cutoffsal))
8) print("Records are deleted successfully....")
9) [Link]()
10) except cx_Oracle.DatabaseError as e:
11) if con:
12) [Link]()
13) print("There is a problem in sql",e)
14) finally:
15) if cursor:
16) [Link]()
17) if con:
18) [Link]()

App9: Write a program to select all employees info by using fetchone() method?
---------------------------------------------------------------------------------------------------

1) import cx_Oracle
2) try:
3) con=cx_Oracle.connect('scott/tiger@localhost')
4) cursor=[Link]()
5) [Link]("select * from employees")
6) row=[Link]()
7) while row is not None:
8) print(row)
9) row=[Link]()
10) except cx_Oracle.DatabaseError as e:
11) if con:
12) [Link]()
13) print("There is a problem with sql :",e)
14) finally:

n
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
198 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
15) if cursor:
16) [Link]()
17) if con:
18) [Link]()

App10: Write a program to select all employees info by using fetchall() method?
----------------------------------------------------------------------------------------------------

1) import cx_Oracle
2) try:
3) con=cx_Oracle.connect('scott/tiger@localhost')
4) cursor=[Link]()
5) [Link]("select * from employees")
6) data=[Link]()
7) for row in data:
8) print("Employee Number:",row[0])
9) print("Employee Name:",row[1])
10) print("Employee Salary:",row[2])
11) print("Employee Address:",row[3])
12) print()
13) print()
14) except cx_Oracle.DatabaseError as e:
15) if con:
16) [Link]()
17) print("There is a problem with sql :",e)
18) finally:
19) if cursor:
20) [Link]()
21) if con:
22) [Link]()

App11: Write a program to select employees info by using fetchmany() method and the
required number of rows will be provided as dynamic input?
-----------------------------------------------------------------------------------------------------------

1) import cx_Oracle
2) try:
3) con=cx_Oracle.connect('scott/tiger@localhost')
4) cursor=[Link]()
5) [Link]("select * from employees")
6) n=int(input("Enter the number of required rows:"))
7) data=[Link](n)
8) for row in data:
9) print(row)

n
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
199 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
10) except cx_Oracle.DatabaseError as e:
11) if con:
12) [Link]()
13) print("There is a problem with sql :",e)
14) finally:
15) if cursor:
16) [Link]()
17) if con:
18) [Link]()

Working with Mysql database:


===========================
Current version: 5.7.19
Vendor: SUN Micro Systems/Oracle Corporation
Open Source and Freeware
Default Port: 3306
Default user: root

Note: In MySQL, everything we have to work with our own databases, which are also
known as logical Databases.

The following are 4 default databases available in mysql.


1. information_schema
2. mysql
3. performance_schema
4. test

Diagram

In the above diagram only one physical database is available and 4 logical databases are
available.

Commonly used commands in MySql:


-----------------------------------------------------
1. To know available databases:
mysql> show databases;

2. To create our own logical database


mysql> create database maheshdb;

3. To drop our own database:


mysql> drop database maheshdb;

4. To use a particular logical database

n
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
200 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
mysql> use maheshdb; OR mysql> connect maheshdb;

5. To create a table:
create table employees(eno int(5) primary key,ename varchar(10),esal
double(10,2),eaddr varchar(10));

6. To insert data:
insert into employees values(100,'Mahesh',1000,'Hyd');
insert into employees values(200,'Durga',2000,'Mumbai');

-->In MySQL instead of single quotes we can use double quotes also.

Driver/Connector Information:
-------------------------------------------
From Python program if we want to communicates with MySql database,compulsory
some translator is required to convert python specific calls into mysql database specific
calls and mysql database specific calls into python specific calls. This translator is nothing
but Driver or Connector.

Diagram

-->We have to download connector seperately from mysql database.

-->[Link]

How to check installation:


-------------------------------------
From python console we have to use
help("modules")

In the list of modules,compulsory mysql should be there.

Note: In the case of Python3.4 we have to set PATH and PYTHONPATH explicitly

PATH=C:\Python34
PYTHONPATH=C:\Python34\Lib\site-packages

Q:write a program to create Table, insert data and display data by using MySQL Database.
---------------------------------------------------------------------------------------------------------------

1) import pymysql
2) try:
3) con=[Link](host='localhost',database='maheshdb',user='root',pa
ssword='root')

n
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
201 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
4) cursor=[Link]()
5) [Link]("create table employees(eno int(5) primary key, ename
varchar(10), esal double(10,2),eaddr varchar(10))")
6) print("Table is created.......")
7) query="insert into employees (eno,ename,esal,eaddr) values
(%s,%s,%s,%s)"
8) records=[(111,'Katrina',1000,'mumbai'),(222,'Kareena',2000,"mumbai"),(33
3,'Deepika',3000,'Mumbai')]
9) [Link](query,records)
10) [Link]()
11) print("Records are inserted successfully")
12) [Link]("select * from employees")
13) data=[Link]()
14) print(type(data))
15) for row in data:
16) print("Employee Number:",row[0])
17) print("Employee Name:",row[1])
18) print("Employee Salary:",row[2])
19) print("Employee Address:",row[3])
20) print()
21) except [Link] as e:
22) if con:
23) [Link]()
24) print("There is a problem with sql :",e)
25) finally:
26) if cursor:
27) [Link]()
28) if con:
29) [Link]()

o/p:D:\pythonclasses>py [Link]
Table is created.......
Records are inserted successfully
<class 'tuple'>
Employee Number: 111
Employee Name: Katrina
Employee Salary: 1000.0
Employee Address: mumbai

Employee Number: 222


Employee Name: Kareena
Employee Salary: 2000.0
Employee Address: mumbai

n
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
202 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
Employee Number: 333
Employee Name: Deepika
Employee Salary: 3000.0
Employee Address: Mumbai

Q).write a program to copy data present in employees table of MySQL data base into
Oracle Database.
------------------------------

1) import cx_Oracle
2) import pymysql
3) try:
4) con=[Link](host='localhost',database='maheshdb',user='root',pa
ssword='root')
5) cursor=[Link]()
6) [Link]("select * from employees")
7) data=[Link]()
8) print(type(data))
9) list=list(data)
10) print(type(list))
11) print(list)
12) except [Link] as e:
13) if con:
14) [Link]()
15) print("There is a problem with sql :",e)
16) finally:
17) if cursor:
18) [Link]()
19) if con:
20) [Link]()
21) try:
22) con=cx_Oracle.connect('scott/tiger@localhost')
23) cursor=[Link]()
24) query="insert into employees values(:eno,:ename,:esal,:eaddr)"
25) [Link](query,list)
26) [Link]()
27) print("Records copied from Mysql to Oracle database successfully.....")
28) except cx_Oracle.DatabaseError as e:
29) if con:
30) [Link]()
31) print("There is a problem with sql :",e)
32) finally:
33) if cursor:
34) [Link]()

n
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
203 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
35) if con:
36) [Link]()

o/p:D:\pythonclasses>py [Link]
<class 'tuple'>
<class 'list'>
[(111, 'Katrina', 1000.0, 'mumbai'), (222, 'Kareena', 2000.0, 'mumbai'), (333, 'Deepika',
3000.0, 'Mumbai')]
Records copied from Mysql to Oracle database successfully.....

n
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
204 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]

You might also like