0% found this document useful (0 votes)
45 views39 pages

3 Python Notes Aug10 To 22

Uploaded by

khanmdnadim03
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)
45 views39 pages

3 Python Notes Aug10 To 22

Uploaded by

khanmdnadim03
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
You are on page 1/ 39

Python Database Communication Oracle Database view

================================================
Python DataBase Communication (PDBC)
================================================
=>Even we achieved the Data Persistency with Files concept, we have the following limitations.
1. Files Concept of any language does not contain security bcoz files
concept does not contain user names and passwords.
2. To extract or process the data from files is very complex bcoz Files data
must always processed with Indices.
3. The data of the files does not contain Column Names and Very complex to Process / Query
the data.
4. Files are unable to store large Volume of Data.
5. The Architecture of Files Changes from One OS to another OS
(OR) Files are Dependent on OS.
=>To Overcome the limitations of Files, we must use the concept of DataBase Softwares Which are
purely RDBMS Products(Oracle, MySQL, MongoDB,SQLITE3, DB2,SQL SERVER...........)
---------------------------------------------------------------------------------------------------------------------------
=>When we use Data Base Softwares for achieving the data persistency, we get the following
advantages.

1. DataBase Softwares are Fully Secured bcoz they provides User Name and
password
2. To Process or Extract or Querying the data from DataBase Softwares is very easy bcoz
the data present in tables of Database software’s are qualified with Column Names.
3. Data Base Software are able to store large Volume of Data.
4. Data Base Softwares are Independent from OS.
-------------------------------X------------------------------------------------------------------------------

=>If Python Program want to communicate with Any Database Software Product then we must use
pre-defined modules and such pre-defined modules are not present in Python Library. So that
Python Programmer must get / Install the pre-defined modules of Database Software by using a tool
called pip.
=>To Make any Python Program to communicate with any data base software then we must install a
third party module which is related Data base software.
=>For Example, To communicate with Oracle Database, we must install cx_Oracle Module, To
communicate with MySQL data base , we must install mysql-connector.....etc and they must be
installed explicitly by using pip tool

=>Syntax: pip install module name

=>here pip tool present in the following folder


"C:\Users\nareshit\AppData\Local\Programs\Python\Python310\Scripts "

=>If we get an error as " pip is not recognized internal command " then set the path as follows

C:\Users\nareshit>set path="C:\Users\nareshit\AppData\Local\Programs\Python\Python310\Scripts "

Example: intsall cx_Oracle any where from windows cmd prompt


(not from Python cmd prompt)
--------------
pip install cx_Oracle

Example: install mysql-connector


pip install mysql-connector
=================================================================
Communication between Python Program and Oracle Database
=================================================================
=>In order to write python program to communicate with Oracle Database, we must follow 6 steps.
They are

1. import cx_Oracle module


2. Python Program must get the connection from Oracle DB
3. Create an object Cursor
4. Python program must Prepare the Query and Execute the Query in Oracle DB
5. Python Program Process the Result of the Query.
6. Python Program closes the connection.
---------------------------------------------------------------------------------------------------------------------------
Explanation:
-----------------------
1. import cx_Oracle module:
----------------------------------------------------
=>If a python Program want to perform any database operations(insert , delete , update record , read
records..etc) then we must import a pre-defined third party module "cx_Oracle".
=>We know that a module is a collection of Variables, Function Names and Class Names.

Examples: import cx_Oracle


---------------------------------------------------------------------------------------------------------------------------
2. Python Program must get the connection from Oracle DB
---------------------------------------------------------------------------------------------------------------------------
=>To do any Data Base Operations, First python program must get the connection from Oracle.
=>To get the connection from any Database, we use connect() which is present in cx_Oracle module.
=>Syntax:- varame=cx_Oracle.connect("Connection URL")

=>Here connection URL Represents " UserName/Password@DNS/Serviceid "

(OR)
UserName/Password@IPAddress/Serviceid "

=>Here Varname is an object of <class, cx_Oracle.Connection>


=>Here "UserName" represents User Name of Oracle Data Base (Ex: scott )
=>here "password" represents Password of Oracle Data Base (Ex: tiger )
=>here DNS(Domain Naming Service) represents name of the machine where Database
Software Installed. The default Name of Every Machine is "localhost".
=>Here IPAddress (Internet Protocal Address) represents An address of Physical Machine where
Database software Installed. The default IP Address of Every Machine is 127.0.0.1 (Loop back
address)
=>Here "serviceid" represents on which name Oracle data base Installed in current working machine.
To find Service Id in Oracle Data base, we use the following at SQL Environment

SQL> select * from global_name;


GLOBAL_NAME
--------------------------------------
ORCL <---------------Service id
=>When we use / write Invalid Connection URL then we get cx_Oracle.DatabaseError as an
exception and must handle.
---------------------------------------------------------------------------------------------------------------------------
----------
3. Create an object of Cursor
-------------------------------------------------------------------------------------
=>The purpose of creating an object of Cursor is that "To carry the Query from Python Program, hand
over to Database, and obtains Result from Database and Gives to Python Program".
=>To create an object of Cursor, we use cursor() which is present in Connection Object.
=>Syntax: varname=conobject.cursor()
=>Here Varname reprsents an object of <class, cx_Oracle.Cursor>
---------------------------------------------------------------------------------------------------------------------------
4. Python program must Prepare the Query and Execute the Query in Oracle DB
---------------------------------------------------------------------------------------------------------------------------
=>A Query is a statement or Request or Question to database software for obtaining data base results.
=>To execute the query in any Database software, we use execute() which is present in cursor object.
=>Syntax: cursorobj.execute("Query")
=>Here Query is of type str and In any database software we have different Queries
(DDL,DML,DRL )
---------------------------------------------------------------------------------
5. Python Program Process the Result of the Query.
--------------------------------------------------------------------------------
=>After Executing DML statements, the result of DML statements is present in cursor object. To
extract the result from cursor object, we use "rowcount" attribute of cursor object. "rowcount"
attribute gives number of updated / deleted / inserted in the the data base.

=>After Executing DRL statements, the result of DRL statements is present in cursor object. To
extract the from cursor object, have 3 Functions in cursor object. They are
a) fetchone()
b) fetchmany(no. of records)
c) fetchall()
=>fetchone() is used for obtaining One Record at a Time in the form of tuple. if no records found then
we this function returns None.
=>fetchmany(no. of records) is used for obtaining specified number of records.
case-1: if specified number of records==0 then this function obtains all records
case-2: if specified number of records<=Total Number of Records then this function
gives specified number of records
case-3: if specified number of records>Total Number of Records then this function
obtains all records
case-4: if specified number of records<0 then this function never gives any records.

=>fetchall() is used for obtaining all the records from cursor object.
=============================================
Types of Queries in Database Softwares
=============================================
=>In any database, we have 3 types of Queries. They are

1. DDL( Data Definition Language) Queries


2. DML (Data Manipulation Language) Queries
3. DRL (Data Retrieval Language ) Queries

==============================================
1. DDL(Data Definition Language) Queries
==============================================
=>The purpose of DDL Queries is that to deal with Physical Level of Database software such as
creation of Tables, altering column sizes, adding new Columns etc.
=>In any Database software , we have 3 types of DDL Queries. They are

1. create
2. alter
3. drop
-----------------------------------------------------------------------------------------------------------------------
1) create:
---------------------
=>This Query is used for creating a table in Oracle Database
=>Syntax:-
SQL> create table <table-name> ( col name1 database data type, col name2
database data type, ......col name-n database data type )

SQL> create table employee(eno number(2) primary key ,ename varchar2(10) not null , sal number
(6,2) not null);
---------------------------------------------------------------------------------------------------------------------------
2. alter :
-------------------------------------
=>This Query is used for alter the table structure such as modifying (modify) the column sizes and
adding (add) new columns.

Syntax1:- SQL> alter table <table-name> modify ( existing col name1 database data type....
existing col name-n database data type )

Syntax2:- SQL> alter table <table-name> add ( new col name1 database data type....
new col name-n database data type )

Examples: SQL> alter table employee add(cname varchar2(10));


SQL> alter table employee modify(ename varchar2(20), sal number(8,2));
---------------------------------------------------------------------------------------------------------------------------
3) drop:
----------------------------------------------------------------------------
=>This query is used for removing the table from Database Software
=>Syntax:- SQL> drop table <table-name>
=>Example:- SQL> drop table employee
-----------------------------------------------------------------------
Example:
----------------
#Program for obtaining the connection from Oracle DB
#TestOraCon1.py
import cx_Oracle # Step-1
try:
con=cx_Oracle.connect("scott/tiger@localhost/orcl") # Step-2
print("type of con=",type(con)) # <class 'cx_Oracle.Connection'>
print("Python program got connection from Oracle DB:")
except cx_Oracle.DatabaseError as db:
print("problem in db:", db)
--------------------------------------------------------------
Example:
----------------
#Program for obtaining the connection from Oracle DB
#TestOraCon2.py
import cx_Oracle # Step-1
try:
con=cx_Oracle.connect("scott1/[email protected]/orcl") # Step-2
print("type of con=",type(con)) # <class 'cx_Oracle.Connection'>
print("Python program got connection from Oracle DB:")
except cx_Oracle.DatabaseError as db:
print("problem in db:", db)
-------------------------------------------------------------------------------------------------
Example:
----------------
#Program for creating an object of cursor
#createcursor.py
import cx_Oracle # step-1
try:
con=cx_Oracle.connect("scott/tiger@localhost/orcl") #step-2
print("\nType of con=",type(con))
print("Python Prog got connection from Oracle DB")
cur=con.cursor() # step-3
print("\nType of cur=",type(cur))
print("Program created cursor object")
except cx_Oracle.DatabaseError as db:
print("problem in db:", db)
---------------------------------------------------------------------
Program on DDL Queries (Create , alter and drop)
----------------------------------------------------------------------
Example:
----------------
#Program for creating a table employee in Oracle DB
#TableCreate.py
import cx_Oracle
try:
con=cx_Oracle.connect("scott/tiger@localhost/orcl")
cur=con.cursor()
#design and execute the query
ctq="create table employee(eno number(2),ename varchar2(10), sal number(8,2) ) "
cur.execute(ctq)
print("Table Created in Oracle DB successfully!")
except cx_Oracle.DatabaseError as db:
print("prob in db:",db)
-----------------------------------------------------------------------------------------------------
Example:
----------------
#write a python program which will alter the table employee for adding new column
#TableAlterAdd.py
import cx_Oracle
def altertable():
try:
con=cx_Oracle.connect("scott/tiger@localhost/orcl")
cur=con.cursor()
#design and execute the query
atq="alter table employee add(cname varchar2(10))"
cur.execute(atq)
print("Employee Table Altered")
except cx_Oracle.DatabaseError as db:
print("prob in db:",db)

#main program
altertable()
------------------------------------------------------------------------------------------------------
Example:
----------------
#write a python program which will alter the table employee for changing the column sizes
#TableAlterModify.py
import cx_Oracle
def altertable():
try:
con=cx_Oracle.connect("scott/tiger@localhost/orcl")
cur=con.cursor()
#design and execute the query
atq="alter table employee modify(eno number(3),sal number(7,2))"
cur.execute(atq)
print("Employee Table Altered")
except cx_Oracle.DatabaseError as db:
print("prob in db:",db)

#main program
altertable()
----------------------------------------------------------------------------------------------------------------
Example:
----------------
#write a python program which will remove the table permanently from database
#TableDrop.py
import cx_Oracle
def removetable():
try:
con=cx_Oracle.connect("scott/tiger@localhost/orcl")
cur=con.cursor()
#design and execute the query
dtq="drop table employee1"
cur.execute(dtq)
print("Employee1 Table droped")
except cx_Oracle.DatabaseError as db:
print("prob in db:",db)

#main program
removetable()
--------------------------------------------------------------------
DML Queries Program on DML Queries (insert)
----------------------------------------------------------------------------------------------------
================================================
2. DML (Data Manipulation Language) Queries
================================================
=>The purpose of DML operations is that To manipulate the table such Inserting the records, deleting
the records and updating the records.
=>In RDBMS database software’s, we have 3 types of DML Operations. They are
1. insert
2. delete
3. update
=>When we execute any DML Operation through python program, we must use commit() for
permanent change / update / modification and to roll back we use roolback().
=>commit() and rollback() are present in connection object.
-----------------------------------------------------------------------------------------------------------------
1. insert:
------------------------------------
=>This query is used for inserting a record in table of database.
=>Syntax:- SQL> insert into <table-name> values( val1 for column1, val2 for column2.....
val-n for column-n)
Example: SQL> insert into student values (20,'DR',33.45,'C');
SQL>insert into student values (10,'RS',23.45,'Python');
SQL> commit ;
-----------------------------------------------------------------------------------------------------------------
2. delete
-----------------------------------------------------------------------------------------------------------------
=>This query is used for deleting a record .
=>Syntax1: delete from <table name>

=>Syntax2: delete from <table-name> where cond list;

=>Example: SQL> delete from student where sno=70;


---------------------------------------------------------------------------------------------------------------------
3. update
---------------------------------------------------------------------------------------------------------------------
=>This query is used for updating the record values

=>Syntax1:
SQL> update <table-name> set col1=val1,col2=val2.....col-n=val-n;

=>Syntax2:
SQL> update <table-name> set col1=val1,col2=val2.....col-n=val-n where cond
list;

Examples: SQL> update student set marks=marks+marks*0.02;


Examples: SQL> update student set marks=marks+marks*0.05,crs='Django' where sno=90;
-----------------------------------------------------------------------------------------------------------------
Example:
----------------
#write a python program which will insert an employee record in employee table
#RecordInsertEx1.py
import cx_Oracle
def insertrecord():
try:
con=cx_Oracle.connect("scott/[email protected]/orcl")
cur=con.cursor()
iq="insert into employee values(40,'SA',2.5,'TCS')"
cur.execute(iq)
con.commit()
print("{} Record Inserted Sucessfully".format( cur.rowcount))
except cx_Oracle.DatabaseError as db:
print("Prob in db:",db)

#main program
insertrecord()
---------------------------------------------------------------------------------------------------------
Example:
----------------
#write a python program which will insert an employee record in employee table
#RecordInsertEx2.py
import cx_Oracle
def insertrecord():
try:
con=cx_Oracle.connect("scott/[email protected]/orcl")
cur=con.cursor()
#read employee values from KBD
empno=int(input("Enter Employee Number:"))
ename=input("Enter Employee Name:")
esal=float(input("Enter Employee Salary:"))
cname=input("Enter Employee Company Name:")
#Prepare and execute the query
iq="insert into employee values(%d,'%s',%f,'%s') "
cur.execute(iq %(empno,ename,esal,cname) )
#OR
#cur.execute("insert into employee values(%d,'%s',%f,'%s') "
%(empno,ename,esal,cname) )
con.commit()
print("{} Record Inserted Sucessfully".format( cur.rowcount))
except cx_Oracle.DatabaseError as db:
print("Prob in db:",db)

#main program
insertrecord()
-----------------------------------------------------------------------------------------------------------
Example:
----------------
#write a python program which will insert an employee record in employee table
#RecordInsertEx3.py
import cx_Oracle
def insertrecord():
while(True):
try:
con=cx_Oracle.connect("scott/[email protected]/orcl")
cur=con.cursor()
#read employee values from KBD
print("-"*50)
empno=int(input("Enter Employee Number:"))
ename=input("Enter Employee Name:")
esal=float(input("Enter Employee Salary:"))
cname=input("Enter Employee Company Name:")
#Prepare and execute the query
iq="insert into employee values(%d,'%s',%f,'%s') "
cur.execute(iq %(empno,ename,esal,cname) )
#OR
#cur.execute("insert into employee values(%d,'%s',%f,'%s') "
%(empno,ename,esal,cname) )
con.commit()
print("\n{} Record Inserted Sucessfully".format( cur.rowcount))
print("-"*50)
ch=input("Do u want to insert another record(yes/no):")
if(ch.lower()=="no"):
print("Thx for using this program:")
break
except cx_Oracle.DatabaseError as db:
print("Prob in db:",db)

#main program
insertrecord()
----------------------------------------------------------------------------------------------------------
Example:
----------------
#write a python program which will insert an employee record in employee table
#RecordInsertEx4.py
import cx_Oracle ,sys
def insertrecord():
while(True):
try:
con=cx_Oracle.connect("scott/[email protected]/orcl")
cur=con.cursor()
#read employee values from KBD
print("-"*50)
empno=int(input("Enter Employee Number:"))
ename=input("Enter Employee Name:")
esal=float(input("Enter Employee Salary:"))
cname=input("Enter Employee Company Name:")
#Prepare and execute the query
iq="insert into employee values(%d,'%s',%f,'%s') "
cur.execute(iq %(empno,ename,esal,cname) )
#OR
#cur.execute("insert into employee values(%d,'%s',%f,'%s') "
%(empno,ename,esal,cname) )
con.commit()
print("\n{} Record Inserted Sucessfully".format( cur.rowcount))
print("-"*50)
ch=input("Do u want to insert another record(yes/no):")
if(ch.lower()=="no"):
print("Thx for using this program:")
break
while(True):
if(ch.lower()=="no"):
sys.exit()
else:
ch=input("Plz learn Typing, for Inserting record
prees yes and no for exit:")
if(ch.lower()=="yes"):
break
except cx_Oracle.DatabaseError as db:
print("Prob in db:",db)

#main program
insertrecord()
------------------------------------------------------------------------------------------------
DML Queries Program on DML Queries (delete , update) Programs
-------------------------------------------------------------------------------------------------
================================================
2. DML (Data Manipulation Language) Queries
================================================
=>The purpose of DML operations is that To manipulate the table such Inserting the records, deleting
the records and updating the records.
=>In RDBMS database softwares, we have 3 types of DML Operations. They are
1. insert
2. delete
3. update
=>When we execute any DML Operation through python program, we must use commit() for
permanent change / update / modification and to roll back we use roolback().
=>commit() and rollback() are present in connection object.
-----------------------------------------------------------------------------------------------------------------
1. insert:
------------------------------------
=>This query is used for inserting a record in table of database.
=>Syntax:- SQL> insert into <table-name> values( val1 for column1, val2 for column2.....

val-n for column-n)


Example: SQL> insert into student values (20,'DR',33.45,'C');
SQL>insert into student values (10,'RS',23.45,'Python');
SQL> commit ;
-----------------------------------------------------------------------------------------------------------------
2. delete
-----------------------------------------------------------------------------------------------------------------
=>This query is used for deleting a record .
=>Syntax1: delete from <table name>

=>Syntax2: delete from <table-name> where cond list;

=>Example: SQL> delete from student where sno=70; ----One Record will remove
SQL>delete from student; -----------deletes all records
---------------------------------------------------------------------------------------------------------------------
3. update
---------------------------------------------------------------------------------------------------------------------
=>This query is used for updating the record values

=>Syntax1:
SQL> update <table-name> set col1=val1,col2=val2.....col-n=val-n;
=>Syntax2:
SQL> update <table-name> set col1=val1,col2=val2.....col-n=val-n where cond
list;

Examples: SQL> update student set marks=marks+marks*0.02;


Examples: SQL> update student set marks=marks+marks*0.05,crs='Django' where sno=90;
----------------------------------------------------------------------------------------------------------
Example:
----------------
#write a python program which will delete the records from employee table based on employee
number
#RecordDeleteEx.py
import cx_Oracle
def deleterecord():
while(True):
try:
con=cx_Oracle.connect("scott/tiger@localhost/orcl")
cur=con.cursor()
#accept employee number from KBD
empno=int(input("Enter Employee Number:"))
cur.execute("delete from employee where eno=%d" %empno)
con.commit()
if(cur.rowcount>0):
print("{} Record Deleted:".format(cur.rowcount))
else:
print("{} Record Does not Exist".format(empno))
print("-"*50)
ch=input("Do u want to delete another record(yes/no):")
if(ch.lower()=="no"):
print("Thx for using this program:")
break
except cx_Oracle.DatabaseError as db:
print("Prob in DB",db)
except ValueError:
print("Don't enter strs, symbols and alpha-numerics")

#main program
deleterecord()
-------------------------------------------------------------------------------------------------------
Example:
----------------
#write a python program which will update employee salary and employee company name
dynamically
#RecordUpdateEx.py
import cx_Oracle
def updaterecord():
while(True):
try:
con=cx_Oracle.connect("scott/tiger@localhost/orcl")
cur=con.cursor()
#accept employee number,emp name and Salary from KBD
empno=int(input("Enter Employee Number:"))
empcmpname=input("Enter Employee Changed Company Name:")
empnewsal=float(input("Enter Employee New Salary:"))
cur.execute("update employee set sal=%f, cname='%s' where eno=%d"
%(empnewsal,empcmpname,empno) )
con.commit()
if(cur.rowcount>0):
print("{} Record Updated:".format(cur.rowcount))
else:
print("{} Record Does not Exist".format(empno))
print("-"*50)
except cx_Oracle.DatabaseError as db:
print("Prob in DB",db)
except ValueError:
print("Don't enter strs, symbols and alpha-numerics for empno,emp
salary")
finally:
ch=input("Do u want to update another record(yes/no):")
if(ch.lower()=="no"):
print("Thx for using this program:")
break

#main program
updaterecord()
============================================
3. DRL (Data Retrieval Language) Queries
============================================
=>DRL (Data Retrieval Language) Queries are used for Reading the records from table.
=>To read the records from table, we use "select"
=>In Otherwords "select" comes under DRL (Data Retrieval Language ) Query.
=>Syntax1: SQL>select col1,col2,.....col-n from <table-name>
=>Syntax2: SQL>select col1,col2,.....col-n from <table-name> where cond list
=>Syntax3: SQL>select * from <table-name>
=>Syntax4: SQL>select * from <table-name> where cond list
---------------------------------------------------------------------------------------------------------------------------
=>Once the select query executed, all records are present in the object of cursor in Python.
=>To get the records from cusror object, we have 3 functions. They are
1) fetchone()
2) fetchmany(no. of records)
3) fetchall()
-----------------------------------------------------------------------
1) fetchone():
---------------------
=>This function is used obtaining One Record at a time in the form of tuple whereever cursor object
pointing
-----------------------------------------------------------------------------
2) fetchmany(no. of records)
-----------------------------------------------------------------------------
=>fetchmany(no. of records) is used for obtaining specified number of records.
case-1: if specified number of records==0 then this function obtains all records
case-2: if specified number of records<=Total Number of Records then this function
gives specified number of records
case-3: if specified number of records>Total Number of Records then this function
obtains all records
case-4: if specified number of records<0 then this function never gives any records.
-----------------------------------------------------------------------------
3) fetchall()
----------------------------------------------------------------------------------------
=>fetchall() is used for obtaining all the records from cursor object.
----------------------------------------------------------------------------------------
Example:
----------------
#Program for reading the records from employee table----fetchone()
#SelectRecordEx1.py
import cx_Oracle
def selectrecords():
try:
con=cx_Oracle.connect("scott/tiger@localhost/orcl")
cur=con.cursor()
#read all the records from employee table
cur.execute("select * from employee")
while(True):
record=cur.fetchone()
if(record!=None):
for recval in record:
print("\t{}".format(recval),end="")
print()
else:
break
except cx_Oracle.DatabaseError as db:
print("Prob in DB",db)

#main program
selectrecords()
---------------------------------------------------------------------------------------------
Example:
----------------
#Program for reading the records from employee table----fetchmany()
#SelectRecordEx2.py
import cx_Oracle
def selectrecords():
try:
con=cx_Oracle.connect("scott/tiger@localhost/orcl")
cur=con.cursor()
#read all the records from employee table
cur.execute("select * from employee")
records=cur.fetchmany(4)
for record in records:
for recval in record:
print("\t{}".format(recval),end="")
print()
except cx_Oracle.DatabaseError as db:
print("Prob in DB",db)

#main program
selectrecords()
----------------------------------------------------------------------------------------------------
Example:
----------------
#Program for reading the records from employee table----fetchall()
#SelectRecordEx3.py
import cx_Oracle
def selectrecords():
try:
con=cx_Oracle.connect("scott/tiger@localhost/orcl")
cur=con.cursor()
#read all the records from employee table
cur.execute("select * from employee")
records=cur.fetchall()
for record in records:
for recval in record:
print("\t{}".format(recval),end="")
print()
except cx_Oracle.DatabaseError as db:
print("Prob in DB",db)

#main program
selectrecords()
--------------------------------------------------------------------------------------------------
Example:
----------------
#Program for reading the records from employee table----fetchall()
#RandomSelectRecordEx3.py
import cx_Oracle
def selectrecords():
try:
con=cx_Oracle.connect("scott/tiger@localhost/orcl")
cur=con.cursor()
#read all the records from employee table
cur.execute("select * from employee")
records=cur.fetchall()
if(len(records)==0):
print("No records Present:")
else:
for record in records[::-1]:
for recval in record:
print("\t{}".format(recval),end="")
print()
except cx_Oracle.DatabaseError as db:
print("Prob in DB",db)

#main program
selectrecords()
------------------------------------------------------------------------------------
Obtaining Column Names of table in Oracle
-------------------------------------------------------------------------------------
Example:
----------------
#Program for displaying the comun names of employee table
#ColumnsEx1.py
import cx_Oracle
def selectcolnames():
try:
con=cx_Oracle.connect("scott/tiger@localhost/orcl")
cur=con.cursor()
#read all the records from employee table
cur.execute("select * from employee")
colnames=cur.description
print("-"*50)
for cols in colnames:
print(cols[0],end="\t")
print()
print("-"*50)
except cx_Oracle.DatabaseError as db:
print("Prob in DB",db)

#main program
selectcolnames()
-------------------------------------------------------------------------------------------------------
Example:
----------------
#Program for displaying the comun names of employee table
#ColumnsEx2.py
import cx_Oracle
def selectcolnames():
try:
con=cx_Oracle.connect("scott/tiger@localhost/orcl")
cur=con.cursor()
#read all the records from employee table
cur.execute("select * from employee")
print("-"*50)
for cols in cur.description:
print(cols[0],end="\t")
print()
print("-"*50)
except cx_Oracle.DatabaseError as db:
print("Prob in DB",db)

#main program
selectcolnames()
---------------------------------------------------------------------------------------------------------
Example:
----------------
#Program for displaying the comun names of employee table
#ColumnsEx3.py
import cx_Oracle
def selectcolnames():
try:
con=cx_Oracle.connect("scott/tiger@localhost/orcl")
cur=con.cursor()
#read all the records from employee table
cur.execute("select * from employee")
print("-"*50)
for cname in [ cols[0] for cols in cur.description]:
print("{}".format(cname),end="\t")
print()
print("-"*50)
except cx_Oracle.DatabaseError as db:
print("Prob in DB",db)

#main program
selectcolnames()
---------------------------------------------------------------------------------------------------------------
Example:
----------------
#Write a python programm which will accept any table name and print read all the records along with
column names
#TableDisplay.py
import cx_Oracle
def tabledata():
try:
con=cx_Oracle.connect("scott/tiger@localhost/orcl")
cur=con.cursor()
#read all the records from employee table
tname=input("Enter Table Name:")
cur.execute("select * from %s " %tname)
print("-"*50)
#display Column Names
for cname in [ cols[0] for cols in cur.description]:
print("{}".format(cname),end="\t")
print()
print("-"*50)
#display the records
records=cur.fetchall()
if(len(records)!=0):
for record in records:
for recval in record:
print("{}".format(recval),end="\t")
print()
print("-"*50)
else:
print("Table is Empty")
except cx_Oracle.DatabaseError as db:
print("Table Does Not Exist:")

#main program
tabledata()

=================================================================
Communication between Python Program and MySQL Database
================================================================
=>In order to write python program to communicate with MySQL Database, we must follow 6 steps.
They are

1. import mysql. connector module


2. Python Program must get the connection from Oracle DB
3. Create an object Cursor
4. Python program must Prepare the Query and Execute the Query in Oracle DB
5. Python Program Process the Result of the Query.
6. Python Program closes the connection.
---------------------------------------------------------------------------------------------------------------------------
Explanation:
-----------------------
1. import mysql.connector module:
----------------------------------------------------
=>If a python Program want to perform any database operations(insert , delete , update record , read
records..etc) then we must import a pre-defined third party module "mysql-connector ".
=>We know that a module is a collection of Variables, Function Name and Class Names.

Examples: import mysql-connector


---------------------------------------------------------------------------------------------------------------------------
2. Python Program must get the connection from MySQL DB
---------------------------------------------------------------------------------------------------------------------------
=>To do any Data Base Operations, First python program must get the connection from MySQL.
=>To get the connection from any Database, we use connect() which is present in mysql.connector
module.
=>Syntax:- varame=mysql.connector.connect("Connection URL")

=>Here connection URL Represents : host="DNS" , user="User Name" passwd="password"


con=mysql.connector.connect(host="DNS" , user="UserName",
passwd="password" )

Examples: con=mysql.connector.connect(host="localhost" , user="root", passwd="root" )

=>Here Varname is an object of <class, mysql.connector.Connection>


=>Here "UserName" represents User Name of MySQL Data Base (Ex: root )
=>here "passwd" represents Password of MySQL Data Base (Ex: root )
=>here DNS(Domain Naming Service) represents name of the machine where Database
Software Installed. The default Name of Every Machine is "localhost".
=>Here IPAddress (Internet Protocal Address) represents An address of Physical Machine where
Database software Installed. The default IP Address of Every Machine is 127.0.0.1 (Loop back
address)
=>When we use / write Invalid Connection URL then we get mysql.connector.DatabaseError as an
exception and must handle.
------------------------------------------------------------------------------------
3. Create an object of Cursor
-------------------------------------------------------------------------------------
=>The purpose of creating an object of Cursor is that "To carry the Query from Python Program, hand
over to Database, and obtains Result from Database and Gives to Python Program".
=>To create an object of Cursor, we use cursor() which is present in Connection Object.
=>Syntax: varname=conobject.cursor()
=>Here Varname reprsents an object of <class, mysql.connector.Cursor>
---------------------------------------------------------------------------------------------------------------------------
4. Python program must Prepare the Query and Execute the Query in MySQL DB
---------------------------------------------------------------------------------------------------------------------------
=>A Query is a statement or Request or Question to database software for obtaining data base results.
=>To execute the query in any Database software, we use execute() which is present in cursor object.
=>Syntax: cursorobj.execute("Query")
=>Here Query is of type str and In any database software we have different Queries
(DDL,DML,DRL )
-------------------------------------------------------------------------------
5. Python Program Process the Result of the Query.
--------------------------------------------------------------------------------
=>After Executing DML statements, the result of DML statements is present in cursor object. To
extract the result from cursor object, we use "rowcount" attribute of cursor object. "rowcount"
attribute gives number of updated / deleted / inserted in the the data base.

=>After Executing DRL statements, the result of DRL statements is present in cursor object. To
extract the from cursor object, have 3 Functions in cursor object. They are
a) fetchone()
b) fetchmany(no. of records)
c) fetchall()
=>fetchone() is used for obtaining One Record at a Time in the form of tuple. if no records found then
we this function returns None.
=>fetchmany(no. of records) is used for obtaining specified number of records.
case-1: if specified number of records==0 then this function obtains all records
case-2: if specified number of records<=Total Number of Records then this function
gives specified number of records
case-3: if specified number of records>Total Number of Records then this function
obtains all records
case-4: if specified number of records<0 then this function never gives any records.

=>fetchall() is used for obtaining all the records from cursor object.
-------------------------------------------------------------------------------------------
Example:
----------------
#Program creating a data base in mysql on the name of batch6pm
#DatabaseCreate.py
import mysql.connector
con=mysql.connector.connect(host="localhost",

user="root",

passwd="root")
cur=con.cursor()
#prepare qurey and execute
dcq="create database batch6pm"
cur.execute(dcq)
print("Database created successfully in MySQL")
-----------------------------------------------------------------------------------------------------------
Example:
----------------
#write a python program which will accept emp compnay name from the keyboard ad delete a record
from employee table
#EmpDeleteEx.py
import mysql.connector
def emprecorddelete():
try:
con=mysql.connector.connect(host="localhost",

user="root",

passwd="root",

database="batch6pm" )
cur=con.cursor()
#accept employee values from KBD
print("-"*50)
empno=int(input("Enter Employee Number:"))
#prepare query and execute
cur.execute("delete from employee where eno=%d " %empno)
con.commit()
print("-"*50)
if (cur.rowcount>0):
print("{} Emplyee Record Deleted:".format(cur.rowcount))
else:
print("Employee Record Does not Exist:")
except mysql.connector.DatabaseError as db:
print("Problem in Database:",db)

#main program
emprecorddelete()
----------------------------------------------------------------------------------------------------------------
Example:
----------------
#Program for inserting a record(s) in employee table
#EmpInsertEx1.py
import mysql.connector
def emprecordinsert():
try:
con=mysql.connector.connect(host="localhost",

user="root",

passwd="root",

database="batch6pm" )
cur=con.cursor()
#accept employee values from KBD
print("-"*50)
empno=int(input("Enter Employee Number:"))
ename=input("Enter Employee Name:")
sal=float(input("Enter Employee Salary:"))
cname=input("Enter Employee Company Name:")
#prepare query and execute
iq="insert into employee values (%d,'%s',%f,'%s') "
cur.execute(iq %(empno,ename,sal,cname))
con.commit()
print("-"*50)
print("{} Emplyee Record Inserted:".format(cur.rowcount))
except mysql.connector.DatabaseError as db:
print("Problem in Database:",db)

#main program
emprecordinsert()
------------------------------------------------------------------------------------------------------------------
Example:
----------------
#write a python program which will insert a record in employee table by accepting employee values
from Keyboard
#EmpInsertEx2.py
import mysql.connector
def emprecordinsert():
while(True):
try:
con=mysql.connector.connect(host="localhost",

user="root",

passwd="root",

database="batch6pm" )
cur=con.cursor()
#accept employee values from KBD
print("-"*50)
empno=int(input("Enter Employee Number:"))
ename=input("Enter Employee Name:")
sal=float(input("Enter Employee Salary:"))
cname=input("Enter Employee Company Name:")
#prepare query and execute
iq="insert into employee values (%d,'%s',%f,'%s') "
cur.execute(iq %(empno,ename,sal,cname))
#OR
#cur.execute("insert into employee values (%d,'%s',%f,'%s')"
%(empno,ename,sal,cname))
con.commit()
print("-"*50)
print("{} Emplyee Record Inserted:".format(cur.rowcount))
print("-"*50)
ch=input("Do u want to insert another employee record(yes/no):")
if(ch=="no"):
break
except mysql.connector.DatabaseError as db:
print("Problem in Database:",db)
except ValueError:
print("Don't enter strs, symbols and alpha-numerics for Empno,
Salary:")
#main program
emprecordinsert()
----------------------------------------------------------------------------------------------------------
Example:
----------------
#write a python program which will update emp sal by 30% and company name(based on keyboard
input) on the bases of emp number
#EmpUpdateEx.py
import mysql.connector
def emprecordupdate():
try:
con=mysql.connector.connect(host="localhost",

user="root",

passwd="root",

database="batch6pm" )
cur=con.cursor()
#accept employee values from KBD
print("-"*50)
eno=int(input("Enter Employee Number:"))
cname=input("Enter Employee Company Name for updattion:")
empsal=float(input("Enter employee salary for updation:"))
cur.execute("update employee set sal=%f,cname='%s' where eno=%d"
%(empsal,cname,eno))
con.commit()
print("-"*50)
if (cur.rowcount>0):
print("{} Emplyee Record Updated:".format(cur.rowcount))
else:
print("Employee Record Does not Exist:")
except mysql.connector.DatabaseError as db:
print("Problem in Database:",db)

#main program
emprecordupdate()
------------------------------------------------------------------------------------------------------------
Example:
----------------
#Program creating a table in batch6pm database on the name of employee
#TableCreate.py
import mysql.connector
try:
con=mysql.connector.connect(host="localhost",

user="root",

passwd="root",

database="batch6pm" )
cur=con.cursor()
#prepare query and execute
tq="create table student (sno int primary key, sname varchar(10) not null, marks float not
null, cname varchar(10) not null ) "
cur.execute(tq)
print("Table created in MySQL--Verify")
except mysql.connector.DatabaseError as db:
print("Problem in Database:",db)
-------------------------------------------------------------------------------------------------------
Example:
----------------
#Program obtaining connection from MySQL
#TestMySqlcon.py
import mysql.connector
con=mysql.connector.connect(host="localhost",user="root",passwd="root")
print("type of con=",type(con))
print("Python got connection from MySQL")

--------------------------------------------------------------------------------------------------
Example:
----------------
#Program creating an object of cursor
#TestMySqlCur.py
import mysql.connector
con=mysql.connector.connect(host="localhost",user="root",passwd="root")
cur=con.cursor()
print("type of cur=",type(cur))
print("Python Program created an object of cursor")

========================================
Regular Expressions
========================================
Index
-------------
=>Purpose of Regular Expression
=>Applications of Regular Expressions
=>Definition of Regular Expression
=>Module Name for Regular Expression Applications development ( re )
=>Functions in "re" modue
a) findall()
b) search()
c) finditer()
d) start()
e) end()
f) group().... more
=>Programming Examples
----------------------------------------------------------------------------------------
=>Programmer-Defined Character Classes
=>Programming Examples
=>Pre-Defined Character Classes
=>Programming Examples
=>Quatifiers in Regular Expression ( + * ? . )
=>Programming Examples
---------------------------------------------------------------------------------------------
=>Combinerd Programming Examples Programmer-Defined Character Classes, Pre-Defined
Character Classes and Quatifiers with "re" module.
==========================================
Pre-defined Functions in re module
==========================================
=>The 're' module contains the follwing essential Functions.
----------------------------------------------------------------------------------------------
1) finditer():
-------------------------------------------------------------------------------------------
Syntax:- varname=re.finditer("search-pattern","Given data")
=>here varname is an object of type <class,'Callable_Itetaror'>

=>This function is used for searching the "search pattern" in given data iteratively and it returns
table of entries which contains start index , end index and matched value based on the search pattern.
-----------------------------------------------------------------------------------------------
2) group():
----------------------------------------------------------------------------------------------
=>This function is used obtaining matched value by the findIter()
=>This function present in match class of re module
Syntax:- varname=matchtabobj.group()
----------------------------------------------------------------------------------------------
3) start():
----------------------------------------------------------------------------------------------
=>This function is used obtaining starting index of matched value
=>This function present in match class of re module
Syntax: varname=matchobj.start()
----------------------------------------------------------------------------------------------
4) end():
----------------------------------------------------------------------------------------------
=>This function is used obtaining end index+1 of matched value
=>This function present in match class of re module
Syntax: varname=matchobj.end()

----------------------------------------------------------------------------------------------
5) search():
----------------------------------------------------------------------------------------------
Syntax:- varname=re.search("search-pattern","Given data")
=>here varname is an object of <class,'re.match'> or <class,'NoneType'>

=>This function is used for searching the search pattern in given data for first occuence / match only
but not for other occurences / matches.
=>if the search pattern found in given data then it returns an object of match class which contains
matched value and start and end index values and it indicates search is successful.
=>if the search pattern not found in given data then it returns None which is type <class,
"NoneType"> and it indicates search is un-successful
---------------------------------------------------------------------------------------------
6) findall():
----------------------------------------------------------------------------------------------
Syntax:- varname=re.findall("search-pattern","Given data")
=>here varname is an object of <class,'list'>

=>This function is used for searching the search pattern in entire given data and find all occurences /
matches and it returns all the matched values in the form an object <class,'list'> but not returning
Start and End Index Values.
========================================
Regular Expressions
========================================
=>Regular Expressions is one of the Programming Languages Indepedent Concept.
=>The purpose of Regular Expressions in any programming language is that " To Perform Data
Validation (Validating End User Inputs) and build Robust Application."
--------------------------------------------------------------
Application of Regular Expressions
--------------------------------------------------------------
=>Development of Language Compilers and Interpreters.
=>Development of Operating Systems.
=>Development of pattern matching Applications
=>Development of Electronic Circuit Designing Applications
=>Development of Universal Protocols.
=>......etc
-----------------------------------------------------------------------------------------------------
Definition of Regular Expression:
-----------------------------------------------------------------------------------------------------
A Regular Expression is one of the String Pattern which is the combination of Alphabets,Digits and
Sppecial Symbols which is used to search or match or finding in Given Data and obtains desired
result.
----------------------------------------------------------------------
Example:
----------------
#RegExpr1.py---findall()
import re
sd="Python"
gd="Python is an oop Lang. Python is also Fun Prog Lang"
result=re.findall(sd,gd)
print(" '{}' found {} times:".format(sd,len(result)))

----------------------------------------------------------------------
Example:
----------------
#RegExpr2.py----search()
import re
sd="Python"
gd="Python is an oop Lang. Python is also Fun Prog Lang"
result=re.search(sd,gd)
if(result!=None):
print("Search is Successful:")
print(" '{}' Found at {} and ends {}".format(sd,result.start(),result.end()))
else:
print("Search is Un-Successful:")
print(" '{}' not Found ".format(sd))
print(" '{}' Found at {} and ends {}".format(sd,result.start(),result.end()))
-----------------------------------------------------------------------
Example:
----------------
#RegExpr3.py---finditer()
import re
sd="an"
gd="Python is an oop Lang. Python is also Fun Prog Lang"
matchtable=re.finditer(sd,gd)
noc=0
print("-"*50)
for mat in matchtable:
print("Start Index:{} End Index:{} Value:{}".format(mat.start(),mat.end(),mat.group()))
noc=noc+1
print("-"*50)
print("Number of '{}' occurences={}".format(sd,noc))
===========================================
Programmer-Defined Character Classes
===========================================
=>Programmer-Defined Character Classes are defined by Programmers for designing Search Pattern
and it can be used to search or match or find in given data and obtains desired result.

=>Syntax: "[ Search Pattern] "


=>The following are the Programmer-Defined Character Classes.

1. [abc] --------->Searches for Either 'a' or 'b' or 'c' only


2. [^abc]--------->Searches for all except a' or 'b' or 'c
3. [a-z]------------>Searches for all Lower case Alphabets only
4. [^a-z]------------>Searches for all except Lower case Alphabets
5. [A-Z]------------->Searches for all Upper case Alphabets only
6. [^A-Z]------------->Searches for all except Upper case Alphabets
7. [0-9]-------------->Searches for all Digits only
8. [^0-9]-------------->Searches for all except Digits .
9. [A-Za-z]----------->Searches for all Alphabets (Upper and Lower) only
10.[^A-Za-z]----------->Searches for all except Alphabets (Upper and Lower)
11. [A-Za-z0-9]------>Searches for Alpha-Numeric Values (Alphabets +Digits) only
12. [^A-Za-z0-9]------>Searches for Special Symbols Except Alpha-Numeric Values
(Alphabets+Digits) only
13. [A-Z0-9]-----Searhes for Upper Case Alpabets and Digits only
14. [^A-Z0-9]-----Searhes for all except Upper Case Akpabets and Digits
15. [a-z0-9]-----Searhes for Lower Case Alpabets and Digits only
16. [^a-z0-9]-----Searhes for all except lower Case Alpabets and Digits
==================================================================
Example:
----------------
#RegExpr4.py---------Searches for Either 'a' or 'b' or 'c' only
import re
matchtable=re.finditer("[abc]", "acHkL@83TaP#9&Qb$6")
print("-"*50)
for mat in matchtable:
print("Start Index:{} End Index:{} Value:{}".format(mat.start(),mat.end(),mat.group()))
print("-"*50)

-------------------------------------------------------------------
Example:
----------------
#RegExpr5.py---------Searches for all except 'a' or 'b' or 'c'
import re
matchtable=re.finditer("[^abc]", "acHkL@83TaP#9&Qb$6")
print("-"*50)
for mat in matchtable:
print("Start Index:{} End Index:{} Value:{}".format(mat.start(),mat.end(),mat.group()))
print("-"*50)
---------------------------------------------------------------------
Example:
----------------
#RegExpr6.py---------Searches for all lower case alphabets
import re
matchtable=re.finditer("[a-z]", "AcHkL@83TaP#9&qb$6")
print("-"*50)
for mat in matchtable:
print("Start Index:{} End Index:{} Value:{}".format(mat.start(),mat.end(),mat.group()))
print("-"*50)

----------------------------------------------------------------------
Example:
----------------
#RegExpr7.py---------Searches for all except lower case alphabets
import re
matchtable=re.finditer("[^a-z]", "AcHkL@83TaP#9&qb$6")
print("-"*50)
for mat in matchtable:
print("Start Index:{} End Index:{} Value:{}".format(mat.start(),mat.end(),mat.group()))
print("-"*50)

-----------------------------------------------------------------------
Example:
----------------
#RegExpr8.py---------Searches for all Upper case alphabets only
import re
matchtable=re.finditer("[A-Z]", "AcHkL@83TaP#9&qb$6Q")
print("-"*50)
for mat in matchtable:
print("Start Index:{} End Index:{} Value:{}".format(mat.start(),mat.end(),mat.group()))
print("-"*50)
----------------------------------------------------------------------
Example:
----------------
#RegExpr9.py---------Searches for all except Upper case alphabets
import re
matchtable=re.finditer("[^A-Z]", "AcHkL@83TaP#9&qb$6Q")
print("-"*50)
for mat in matchtable:
print("Start Index:{} End Index:{} Value:{}".format(mat.start(),mat.end(),mat.group()))
print("-"*50)
---------------------------------------------------------------------
Example:
----------------
#RegExpr10.py---------Searches for all digits
import re
matchtable=re.finditer("[0-9]", "AcHkL@83TaP#9&qb$6Q")
print("-"*50)
for mat in matchtable:
print("Start Index:{} End Index:{} Value:{}".format(mat.start(),mat.end(),mat.group()))
print("-"*50)
----------------------------------------------------------------------
Example:
----------------
#RegExpr11.py---------Searches for all except digits
import re
matchtable=re.finditer("[^0-9]", "AcHkL@83TaP#9&qb$6Q")
print("-"*50)
for mat in matchtable:
print("Start Index:{} End Index:{} Value:{}".format(mat.start(),mat.end(),mat.group()))
print("-"*50)
-----------------------------------------------------------------------
Example:
----------------
#RegExpr12.py---------Searches for all alphabets
import re
matchtable=re.finditer("[A-Za-z]", "AcHkL@83TaP#9&qb$6Q")
print("-"*50)
for mat in matchtable:
print("Start Index:{} End Index:{} Value:{}".format(mat.start(),mat.end(),mat.group()))
print("-"*50)
-----------------------------------------------------------------------
Example:
----------------
#RegExpr13.py---------Searches for all except alphabets
import re
matchtable=re.finditer("[^A-Za-z]", "AcHkL@83TaP#9&qb$6Q")
print("-"*50)
for mat in matchtable:
print("Start Index:{} End Index:{} Value:{}".format(mat.start(),mat.end(),mat.group()))
print("-"*50)

-----------------------------------------------------------------------
Example:
----------------
#RegExpr14.py---------Searches for all alpha-numerics (Alphabets +Digits)
import re
matchtable=re.finditer("[A-Za-z0-9]", "AcHkL@83TaP#9&qb$6Q")
print("-"*50)
for mat in matchtable:
print("Start Index:{} End Index:{} Value:{}".format(mat.start(),mat.end(),mat.group()))
print("-"*50)

-----------------------------------------------------------------------
Example:
----------------
#RegExpr15.py---------Searches for all Special Symbols except alpha-numerics (Alphabets +Digits)
import re
matchtable=re.finditer("[^A-Za-z0-9]", "Ac HkL@83TaP#9&qb$6Q")
print("-"*50)
for mat in matchtable:
print("Start Index:{} End Index:{} Value:{}".format(mat.start(),mat.end(),mat.group()))
print("-"*50)

-----------------------------------------------------------------------
Example:
----------------
#RegExpr16.py---------Searches for space character
import re
matchtable=re.finditer("\s", "Ac HkL@ 83TaP#9&qb$6Q")
print("-"*50)
for mat in matchtable:
print("Start Index:{} End Index:{} Value:{}".format(mat.start(),mat.end(),mat.group()))
print("-"*50)
--------------------------------------------------------------------
Example:
----------------
#RegExpr17.py---------Searches for all except space character
import re
matchtable=re.finditer("\S", "Ac HkL@ 83TaP#9&qb$6Q")
print("-"*50)
for mat in matchtable:
print("Start Index:{} End Index:{} Value:{}".format(mat.start(),mat.end(),mat.group()))
print("-"*50)
-----------------------------------------------------------------------
Example:
----------------
#RegExpr18.py---------Searches for digit
import re
matchtable=re.finditer("\d", "Ac HkL@ 83TaP#9&qb$6Q")
print("-"*50)
for mat in matchtable:
print("Start Index:{} End Index:{} Value:{}".format(mat.start(),mat.end(),mat.group()))
print("-"*50)
-----------------------------------------------------------------------
Example:
----------------
#RegExpr19.py---------Searches for all except digit
import re
matchtable=re.finditer("\D", "Ac HkL@ 83TaP#9&qb$6Q")
print("-"*50)
for mat in matchtable:
print("Start Index:{} End Index:{} Value:{}".format(mat.start(),mat.end(),mat.group()))
print("-"*50)
-----------------------------------------------------------------------
Example:
----------------
#RegExpr20.py---------Searches for word character(Alphabets and Digits)
import re
matchtable=re.finditer("\w", "Ac HkL@ 83TaP#9&qb$6Q")
print("-"*50)
for mat in matchtable:
print("Start Index:{} End Index:{} Value:{}".format(mat.start(),mat.end(),mat.group()))
print("-"*50)
----------------------------------------------------------------------
Example:
----------------
#RegExpr21.py---------Searches for all special Symbols except word character(Alphabets and Digits)
import re
matchtable=re.finditer("\W", "Ac HkL@ 83TaP#9&qb$6Q")
print("-"*50)
for mat in matchtable:
print("Start Index:{} End Index:{} Value:{}".format(mat.start(),mat.end(),mat.group()))
print("-"*50)
=========================================
Quantifiers in Regular Expressions
=========================================
=>Quantifiers in Regular Expressions are used for searching number of occurences of the specified
value (alphabets or digits or special symbols) used in search pattern to search in the given data and
obtains desired result.

1) "k"------->It search for only one 'k' at a time


2) "k+"------>It search for either one 'k' more 'k' s
3) "k*"------>It search for either zero 'k' or one 'k' and more 'k' s
4) "k?"----->>It search for either zero 'k' or one 'k'
5) ". " ---->It searches for all

---------
Note:
---------
\ddd or \d{3}----->searches for 3 digit Number
\dd.\dd----searhes for 2 integer values and 2 decimal values OR \d{2}.\d{2}
\d{2,4}----searches for min 2 digit number and max 4 digit number.
[A-Za-z]+ ---searches one alphabet or More alphabets.
\w+
[0-9]+ or \d+

-----------------------------------------------------------------------
Example:
----------------
#RegExpr22.py
import re
matchtable=re.finditer("K+", "KVKKVKKKVKV")
print("-"*50)
for mat in matchtable:
print("Start Index:{} End Index:{} Value:{}".format(mat.start(),mat.end(),mat.group()))
print("-"*50)
-----------------------------------------------------------------------
Example:
----------------
#RegExpr23.py
import re
matchtable=re.finditer("K*", "KVKKVKKKVKV")
print("-"*50)
for mat in matchtable:
print("Start Index:{} End Index:{} Value:{}".format(mat.start(),mat.end(),mat.group()))
print("-"*50)

-----------------------------------------------------------------------
Example:
----------------
#RegExpr24.py
import re
matchtable=re.finditer("K?", "KVKKVKKKVKV")
print("-"*50)
for mat in matchtable:
print("Start Index:{} End Index:{} Value:{}".format(mat.start(),mat.end(),mat.group()))
print("-"*50)
-----------------------------------------------------------------------
Example:
----------------
#RegExpr25.py
import re
matchtable=re.finditer(".", "KVKKVKKKVKV")
print("-"*50)
for mat in matchtable:
print("Start Index:{} End Index:{} Value:{}".format(mat.start(),mat.end(),mat.group()))
print("-"*50)
-----------------------------------------------------------------------
Programs Regular Expressions
---------------------------------------------------------------------
Example:
----------------
#write a python program which will read email id's of various students whose information present in
file
#EmailsListEx1.py
import re
try:
with open("student.data","r") as fp:
filedata=fp.read()
maillist=re.findall("\S+@\S+",filedata)
print("-"*50)
print("Mails of Students:")
print("-"*50)
for mail in maillist:
print("\t{}".format(mail))
print("-"*50)
except FileNotFoundError:
print("File does not exist:")
-----------------------------------------------------------------------
Example:
----------------
#wapp which will extract names and marks of students where the student information is available in
file
#FilesNamesMarksEx1.py
import re
try:
with open("student.data") as fp:
filedata=fp.read()
nameslist=re.findall("[A-Z][a-z]+",filedata)
markslist=re.findall("\d{2,3}",filedata)
print("-"*50)
print("\tStudent Names\tStudent Marks")
print("-"*50)
for name,marks in zip(nameslist,markslist):
print("\t{}\t\t{}".format(name,marks))
print("-"*50)
except FileNotFoundError:
print("File does not exist:")
-----------------------------------------------------------------------
Example:
----------------
#wapp which will extract names and marks and mails of students where the student information is
available in file
#FilesNamesMarksMailsEx1.py
import re
try:
with open("student.data") as fp:
filedata=fp.read()
nameslist=re.findall("[A-Z][a-z]+",filedata)
markslist=re.findall("\d{2,3}",filedata)
maillist=re.findall("\S+@\S+",filedata)
print("-"*50)
print("\tStudent Names\tStudent Marks\t\tMail-id")
print("-"*50)
for name,marks,mail in zip(nameslist,markslist,maillist):
print("\t{}\t\t{}\t\t{}".format(name,marks,mail))
print("-"*50)
except FileNotFoundError:
print("File does not exist:")
--------------------------------------------------------------------
Example:
----------------
#write a python program which will read student marks from the given data
#MarksListEx1.py
import re
gd="Rossum got 56 marks , Dennis got 100 marks , Travis got 22 marks , Gosling got 15 marks and
Mckinney got 66 marks"
markslist=re.findall("\d{2,3}",gd)
print("-"*50)
print("Marks of Students--findall()")
print("-"*50)
for marks in markslist:
print("\t{}".format(marks))
print("-"*50)
--------------------------------------------------------------------
Example:
----------------
#Program for Mobile Number validation
#MobileNumber.py
import re
while(True):
mno=input("Enter Ur Mobile Number:")
if(len(mno)==10):
result=re.search("\d{10}",mno)
if(result!=None):
print("\nUr Mobile Number is Valid:")
break
else:
print("\nMobile Number Must contain only Digits but not non-digits:")
else:
print("\nMobile Number Must Contain 10 Digits Length Only")
-----------------------------------------------------------------------
Example:
----------------
#write a python program which will read student names from the given data
#NamesListEx1.py
import re
gd="Rossum got 56 marks , Dennis got 66 marks , Travis got 22 marks , Gosling got 15 marks and
Mckinney got 66 marks"
nameslist=re.findall("[A-Z][a-z]+",gd)
print("-"*50)
print("Name of Students--findall()")
print("-"*50)
for name in nameslist:
print("\t{}".format(name))
print("-"*50)
print("Name of Students--finditer()")
print("-"*50)
names=re.finditer("[A-Z][a-z]+",gd)
for name in names:
print("Start Index:{} End Index:{}
Name:{}".format(name.start(),name.end(),name.group()))
print("-"*50)
-----------------------------------------------------------------------
Example:
----------------
#write a python program which will read student marks from the given data
#NamesMarksListEx1.py
import re
gd="Rossum got 56 marks , Dennis got 100 marks , Travis got 22 marks , Gosling got 15 marks and
Mckinney got 66 marks"
nameslist=re.findall("[A-Z][a-z]+",gd)
print("-"*50)
print("Name of Students--findall()")
print("-"*50)
for name in nameslist:
print("\t{}".format(name))
print("-"*50)
markslist=re.findall("\d{2,3}",gd)
print("-"*50)
print("Marks of Students--findall()")
print("-"*50)
for marks in markslist:
print("\t{}".format(marks))
print("-"*50)
----------------------------------------------------------------------
Example:
----------------
#write a python program which will read student marks from the given data
#NamesMarksListEx2.py
import re
gd="Rossum got 56 marks , Dennis got 100 marks , Travis got 22 marks , Gosling got 15 marks and
Mckinney got 66 marks"
nameslist=re.findall("[A-Z][a-z]+",gd)
markslist=re.findall("\d{2,3}",gd)
print("-"*50)
print("\tStudent Names\tStudent Marks")
print("-"*50)
for name,marks in zip(nameslist,markslist):
print("\t{}\t\t{}".format(name,marks))
print("-"*50)
==========================================
random module
==========================================
=>'random' is one of pre-defined module
=>The purpose of random module is that "To generate random values".
=>random module contains the following pre-defined Functions.
1) randrange()
2) randint()
-------------------------
2) random()
3) uniform()
-------------------------
4)choice()
5) shuffle()
6)sample()
--------------------------
------------------------------------------------------------------------------------------------------------------
1) randrange():
------------------------------------------------------------------------------------------------------------------
=>Syntax1: varname=randrange(Value)
(OR)
randrange(Value)
=>This Syntax generates random Integer Values from 0 to Value-1

=>Syntax2: varname=randrange(Start,Stop)
(OR)
randrange(Start,Stop)
=>This Syntax generates random Integer Values from Start to Stop-1
Examples:
-------------------
>>> import random as r
>>> print(r.randrange(10))-----------3
>>> print(r.randrange(10))-----------8
>>> print(r.randrange(10))----------3
>>> print(r.randrange(10))----------5
>>> print(r.randrange(10))-------7
>>> print(r.randrange(10))---------2
>>> print(r.randrange(10,20))--------19
>>> print(r.randrange(10,20))----------10
>>> print(r.randrange(10,20))--------12
>>> print(r.randrange(10,20))---------19
>>> print(r.randrange(10,20))--------16
>>> print(r.randrange(10,20))-------11
>>> print(r.randrange(1000,10000))-----7254
>>> print(r.randrange(1000,10000))-----6283
>>> print(r.randrange(1000,10000))------7713
>>> print(r.randrange(1000,10000))----3593
>>> print(r.randrange(1000,10000))----2564
Examples:
----------------
#Program form randrange()
#randrangeex.py
import random as r
for i in range(1,8):
print(r.randrange(1000,2000))
------------------------------------------------------------------------------------------------------------------
2) randint()
------------------------------------------------------------------------------------------------------------------
=>Syntax2: varname=randint(Start,Stop)
(OR)
randint(Start,Stop)
=>This Syntax generates random Integer Values from Start to Stop(Both are Inclusive)
----------------
Examples:
-----------------
>>> import random as r
>>> print(r.randint(10,15))--------13
>>> print(r.randint(10,15))---------10
>>> print(r.randint(10,15))--------14
>>> print(r.randint(10,15))--------15
>>> print(r.randint(10,15))--------11

Examples:
------------------
#Program form randint()
#randintex.py
import random as r
for i in range(1,6):
print(r.randint(100,150))

NOTE: here randrange() and randint() are used for generating random Integer values only
---------------------------------------------------------------------------------------------------------------------------
2) random()
---------------------------------------------------------------------------------------------------------------------------
Syntax: random.random()
=>This syntax generates random floating values between 0.0 to 1.0 (Exclusive)
Examples:
------------------
>>> import random as r
>>> print(r.random())----------------0.953414908971505
>>> print(r.random())---------------0.8602010668984944
>>> print(r.random())---------------0.6652750407642519
>>> print(r.random())------------0.8657790572994452
>>> print("%0.2f" %r.random())-----------0.62
>>> print("%0.2f" %r.random())----------0.52
>>> print("%0.2f" %r.random())----------0.48
>>> print("%0.2f" %r.random())-----------0.99

Examples:
--------------------------------
#Program for random()
#randomex.py
import random as r
for i in range(1,6):
print(r.random())
print("-------------------------------")
for i in range(1,6):
print("%0.3f" %r.random())
---------------------------------------------------------------------------------------------------------------------------
3) uniform()
---------------------------------------------------------------------------------------------------------------------------
=>Syntax: random.uniform(Start,Stop)
=>This Syntax generates ra ndom floating point values from Start to Stop-1.
=>Here start and stop values can be either Integer or floating point values
Examples:
-------------------
>>> import random as r
>>> print(r.uniform(2,3))-------2.125910222609465
>>> print(r.uniform(2,3))--------2.5724588835923488
>>> print(r.uniform(2,3))----2.315566668246915
>>> print(r.uniform(2,3))------2.361772917954831
>>> print(r.uniform(2,3))-----2.183749376668188
>>> print(r.uniform(100,300))------255.9741762891575
>>> print(r.uniform(100,300))-------186.53282469558758
>>> print(r.uniform(1.5,2.5))-------2.4826601405944295
>>> print(r.uniform(1.5,2.5))------1.6289136361161278
>>> print(r.uniform(1.5,2.5))-------1.679501275355531

Examples:
------------------
#Program for unitorm()
#uniformex.py
import random as r
for i in range(1,6):
print(r.uniform(2,3.5))
print("-------------------------------")
for i in range(1,6):
print("%0.2f" %r.uniform(100,200))
---------------------------------------------------------------------------------------------------------------------------
4)choice()
---------------------------------------------------------------------------------------------------------------------------
=>Syntax:- random.choice(Iterableobject)

Examples:
---------------
>>> import random as r
>>> s="PYTHON"
>>> r.choice(s)---------------------'T'
>>> r.choice(s)---------------------'O'
>>> r.choice(s)---------------------'O'
>>> r.choice(s)---------------------'N'
>>> r.choice(s)---------------------'N'
>>> r.choice(s)--------------------'N'
>>> print(r.choice(s),r.choice(s))-------N H
>>> print(r.choice(s),r.choice(s))-------Y H
>>> print(r.choice(s),r.choice(s))-------N H
>>> print(r.choice(s),r.choice(s))-------Y N
>>> print(r.choice(s),r.choice(s))
TP
>>> s="ABCD12345efghikl@#$%^&*"
>>> print(r.choice(s),r.choice(s),r.choice(s),r.choice(s))
4#AB
>>> print(r.choice(s),r.choice(s),r.choice(s),r.choice(s))
BBAe
>>> print(r.choice(s),r.choice(s),r.choice(s),r.choice(s))
h@3&
>>> print(r.choice(s),r.choice(s),r.choice(s),r.choice(s))
i3e3
>>> print(r.choice(s),r.choice(s),r.choice(s),r.choice(s))
4*A&
----------------------------------------------------------------------
Example:
---------------
#Program for choice()
#choiceex2.py
import random as r
nums="0123456789"
alpha1="ABCEDEFGHIJKLMNOPQRSTUVWXYZ"
alpha2="ABCEDEFGHIJKLMNOPQRSTUVWXYZ"
for i in range(1,11):
print("TS"+r.choice(nums)+r.choice(nums)+r.choice(alpha1)+r.choice(alpha2)+r.choice(nu
ms)+r.choice(nums)+r.choice(nums)+r.choice(nums))
print("\n---------------------------------------")
for i in range(1,11):
print("TS08"+r.choice(alpha1)+r.choice(alpha2)+r.choice(nums)+r.choice(nums)+r.choice(
nums)+r.choice(nums))
---------------------------------------------------------------------------------------------------------------------------
5) shuffle()
---------------------------------------------------------------------------------------------------------------------------
=>This function is use for re-organizing the elements of Mutable objects only (Immutable objects data
is not possible to shuffle)
=>Syntax: random.shuffle(object)
=>Here object can be mutable.

Examples:
------------------
>>> l1=[10,20,30,40,50]
>>> r.shuffle(l1)
>>> l1---------------[30, 20, 40, 50, 10]
>>> r.shuffle(l1)
>>> l1--------------[10, 30, 40, 50, 20]
>>> r.shuffle(l1)
>>> l1-------------[10, 20, 40, 50, 30]
-----------------------------
>>> l1=[10,20,30,40,50]
>>> l1
[10, 20, 30, 40, 50]
>>> r.shuffle(l1)
>>> l1
[20, 40, 30, 10, 50]
>>> print(r.shuffle(l1))----------None
>>> print(l1)
[40, 10, 20, 30, 50]
---------------------------------------------------------------------------------------------------------------------------
6)sample()
---------------------------------------------------------------------------------------------------------------------------
=>This Function is used for selecting k number of sample random elements from given Iterable
object.
=>Syntax:- varname= random.sample(object,k)
=>here Varname is an object of list.
=>Here k represents Number of Samples to be selected randomly from Iterable object.

Examples:
------------------
>>> l1=[10,"KVR",34.56,"Python",4.5,True]
>>> x=r.sample(l1,3)
>>> x
[34.56, 4.5, True]
>>> x=r.sample(l1,3)
>>> x
['Python', 4.5, True]
>>> r.sample(l1,3)
[True, 4.5, 'KVR']
>>> r.sample(l1,3)
[10, 'Python', 'KVR']
>>> r.sample(l1,3)
[10, 4.5, 'Python']
>>> r.sample(l1,3)
['Python', 4.5, True]
>>> r.sample(l1,3)
[4.5, 'KVR', True]
>>> s1="PYTHON"
>>> r.sample(s1,2)
['P', 'N']
>>> r.sample(s1,2)
['T', 'P']
>>> r.sample(s1,2)
['Y', 'O']
>>> r.sample(s1,2)
['O', 'H']
----------------------
Example
----------------------
#Program for sample()
#sampleex.py
import random as r
s="ABCDEFGHI123456@#$%^&*()abcd"
for i in range(1,6):
x=r.sample(s,6)
s1=""
for val in x:
s1=s1+val
print(s1)
-----------------------------------------------------------------------
Example:
----------------
#Program for unitorm()
#choiceex1.py
import random as r
s="ABCD12345efghikl@#$%^&*"
for i in range(1,6):
print(r.choice(s)+r.choice(s)+r.choice(s)+r.choice(s))
-------------------------------------------------------------------
Example:
----------------
#Program for choice()
#choiceex2.py
import random as r
nums="0123456789"
alpha1="ABCEDEFGHIJKLMNOPQRSTUVWXYZ"
alpha2="ABCEDEFGHIJKLMNOPQRSTUVWXYZ"
for i in range(1,11):
print("TS"+r.choice(nums)+r.choice(nums)+r.choice(alpha1)+r.choice(alpha2)+r.choice(nu
ms)+r.choice(nums)+r.choice(nums)+r.choice(nums))
print("\n---------------------------------------")
for i in range(1,11):
print("TS08"+r.choice(alpha1)+r.choice(alpha2)+r.choice(nums)+r.choice(nums)+r.choice(
nums)+r.choice(nums))
--------------------------------------------------------------------
Example:
----------------
#Program for randint()
#randintex.py
import random as r
for i in range(1,6):
print(r.randint(100,150))
--------------------------------------------------------------------
Example:
----------------
#Program for random()
#randomex.py
import random as r
for i in range(1,6):
print(r.random())
print("-------------------------------")
for i in range(1,6):
print("%0.3f" %r.random())
----------------------------------------------------------------------
Example:
----------------
Program for randrange()
#randrangeex.py
import random as r
for i in range(1,8):
print(r.randrange(1000,2000))
-----------------------------------------------------------------
Example:
----------------
#Program for sample()
#sampleex.py
import random as r
s="ABCDEFGHI123456@#$%^&*()abcd"
for i in range(1,6):
x=r.sample(s,k=6)
s1=""
for val in x:
s1=s1+val
print(s1)
----------------------------------------------------------------------
Example:
----------------
#Program for shuffle
#shuffleex.py
import random as r
l1=[10,"KVR","Python",45.67,True,2+3j]
for i in range(1,6):
r.shuffle(l1)
print(l1)
------------------------------------------------------------------
Example:
----------------
#Program for uniform()
#uniformex.py
import random as r
for i in range(1,6):
print(r.uniform(2,3.5))
print("-------------------------------")
for i in range(1,6):
print("%0.2f" %r.uniform(100,200))

OOPs Principles Classes Concept


=================================================
List of Object-Oriented Principles
=================================================
=>To say a language is Object Oriented , It has to satisfy the following Principles.

1. Classes
2. Objects
3. Data Encapsulation
4. Data Abstraction
5. Inheritance
6. Polymorphism
7. Message Passing (already discussed)
===================================================
➢ Object Oriented Principles or Features or Concepts
===================================================
=>In real time, to develop any project or application, we must choose a language and it can satisfy
two types of principles. They are
1. Functional(Procedure) Oriented Principles-----C,Pascal,
cobol,8086,oracle7.3,PYTHON
2. Object Oriented Priciples.--------PYTHON C++ JAVA, .NET.......
=>Even though, PYTHON programming Belongs both Functional and Object-Oriented Programming
language and internally every thing is treated as object.
-----------------------------------------------------------------------

"Every Thing is an object " --Benifits


(OR)
Adavtanges of Object Oriented Principles
---------------------------------------------------------------------
1. Objects allows us to store Large Volume of Data (Platform Indepenedent)
2. The Data is visiting between two machines in the form of Ciphet Text (encrypted Format).
So that we can achieve the Security
3. The Large Volume of Data can be transfered between multiple machines all at once in the
form of objects and obtains effective communication.
4. With Objects we can build high effective Re-Usable Applications.
5. The Data is always available arround Objects (Effective Memory Usage) and functions can operate
on the objects.

===================================
Classes
===================================
=>The Purpose of Classes Concept is that "To Develop Programmer-Defined Data Type+To
develop any real Time Application in OOPs"
=>The Purpose of Developing Programmer-Defined Data Type is that "To Store Customized
Data and To Perform Customized Operations".
=>To Develop Programmer-Defined Data Type by using Classes concept, we use "class"
keyword
=>In Python Programming, All Class Names are treated as Programmer-Defined Data Type.
=>Every Program in OOPs, Must starts with Classes concept.
--------------------------------------------------
Definition:
--------------------------------------------------
=>A Class is a collection Variables (Data Members) and Method .
--------------------------------------------------
=>When we define a class, Memory space is not created for Data Members and Methods But Whose
Memory Space is created when we create an object w.r.t Class Name.
===================================x===============================

You might also like