Adv Python
Adv Python
PYTHON
MOHAN REDDY
MOHAN S.REDDY
TABLE OF CONTENTS
Object Oriented Programming (OOP’s) : ...................................................................... 3
Features of object-oriented programming: ................................................................... 4
Encapsulation:............................................................................................................. 4
Abstraction: ................................................................................................................. 4
Polymorphism: ............................................................................................................ 5
Inheritance: ................................................................................................................. 5
Types of Inheritance:...................................................................................................... 6
How to create a class: ..................................................................................................... 6
How to create object to the class:................................................................................ 6
Constructor: ................................................................................................................ 8
Method: ....................................................................................................................... 8
Types of variables: ........................................................................................................ 10
Instance variables: .................................................................................................... 10
Static variables: ......................................................................................................... 13
Local variables: .......................................................................................................... 14
Types of methods: ........................................................................................................ 15
Instance methods: ..................................................................................................... 15
Class methods: .......................................................................................................... 15
Static methods: .......................................................................................................... 16
GC (Garbage Collector): ............................................................................................... 19
Destructors: ..................................................................................................................20
Encapsulation: .............................................................................................................. 21
Inheritance: .................................................................................................................. 24
Polymorphism: ............................................................................................................. 29
Operator overloading: ...............................................................................................30
Method overloading: ................................................................................................. 32
Constructor overloading: .......................................................................................... 32
Abstract method and Abstract class: ........................................................................... 34
Abstract method: ....................................................................................................... 34
Abstract class:............................................................................................................ 35
Exception Handling: .................................................................................................... 37
Page 1 of 117
MOHAN S.REDDY
ADVANCE PYTHON
Page 3 of 117
MOHAN S.REDDY
1. Encapsulation
2. Abstraction
3. Polymorphism
4. Inheritance
ENCAPS UL ATION:
ABSTRACTION:
Page 4 of 117
MOHAN S.REDDY
POL YMORPHISM:
INHERITANCE:
Page 5 of 117
MOHAN S.REDDY
TYPES OF INHERITANCE:
1. Single :
It is the process of creating new class from single base
class
2. Multi-level :
It is the process of creating new class from already
derived class
3. Hierarchical :
It is the process of creating multiple child classes from
single base class
4. Multiple :
It is the process of creating new class from two or more
base classes
5. Hybrid :
It is the combination of multilevel, multiple, hierarchical
inheritance.
Ex: s = Student( )
Page 6 of 117
MOHAN S.REDDY
class Student:
'''This is student class for display
student details'''
#help(Student)
s=Student()
print(s.__doc__)
class Student:
def __init__(self):
self.sid=123
self.sname="sai"
self.saddress="hyderabad"
def display(self):
print("Student id is:",self.sid)
print("Student name is:",self.sname)
print("Student address is:",self.saddress)
s1=Student()
s2=Student()
s1.display()
s2.display()
Page 7 of 117
MOHAN S.REDDY
CON STRUCTOR:
METHOD:
def display(self):
print("Student id is:",self.sid)
print("Student name is:",self.sname)
print("Student address
is:",self.saddress)
s1=Student(101,"sai","hyderabad")
s2=Student(102,"mohan","sr nagar")
s1.display()
s2.display()
Page 8 of 117
MOHAN S.REDDY
class Student:
def getdata(self):
self.sid=int(input("Enter sid:"))
self.sname=input("Enter sname:")
self.saddress=input("Enter saddress:")
def display(self):
print("Student id is:",self.sid)
print("Student name is:",self.sname)
print("Student address is:",self.saddress)
s1=Student()
s1.getdata()
s1.display()
s1=Student(101,"sai","hyderabad")
s2=Student(102,"mohan","sr nagar")
print(s1.__dict__)
print(s2.__dict__)
Page 9 of 117
MOHAN S.REDDY
TYPES OF VARIABLES:
INSTANCE VARIABLES:
def m1(self):
self.b=20
t=Test()
t.m1()
t.c=30
print(t.__dict__)
Page 10 of 117
MOHAN S.REDDY
class Test:
def __init__(self):
self.a=10
self.b=20
def m1(self):
print("within the class")
print(self.a)
print(self.b)
t=Test()
t.m1()
print("outside of the class")
print(t.a)
print(t.b)
Note: We can create any no of object to the class , for every object a
separate copy of instance variables will be create ,if we change or delete
one copy of instance variables then other copy of instance variables will not
effect.
Page 11 of 117
MOHAN S.REDDY
class Test:
def __init__(self):
self.a=10
self.b=20
self.c=30
def m1(self):
del self.a
t1=Test()
t2=Test()
print(t1.__dict__)
print(t2.__dict__)
t1.m1()
del t2.b
t1.c=44
print(t1.__dict__)
print(t2.__dict__)
Page 12 of 117
MOHAN S.REDDY
STATIC VARIABLES:
class Test:
a=10 #static variable
def __init__(self):
self.b=20 #instance variable
t1=Test()
t2=Test()
print("t1:",t1.a,t1.b)
print("t2:",t2.a,t2.b)
Test.a=99
t1.b=45
print("t1:",t1.a,t1.b)
print("t2:",t2.a,t2.b)
Page 13 of 117
MOHAN S.REDDY
LOCAL VARIABLES:
o The variables which are declare inside the particular method and
that variables are available for only that method is called local
variables.
o Local variables cannot access outside of the methods.
o Local variables can only be access within the same method where
we declare it.
o Local variables are also called as temporary variables.
o Once method execution starts these variables will be create
o Once method execution completes these will be destroyed
o Local variables can be declared inside the method without using
self.
class Test:
def m1(self):
a=10
print(a)
#print(b)#NameError: name 'b' is not
defined
def m2(self):
b=20
print(b)
#print(a)#NameError: name 'a' is not
defined
t=Test()
t.m1()
t.m2()
Page 14 of 117
MOHAN S.REDDY
TYPES OF METHODS:
INSTANCE METHODS:
CLASS METHODS:
Page 15 of 117
MOHAN S.REDDY
STATIC METHODS:
Ex:
class Student:
inst="durgasoft" #static variable
def __init__(self,m1,m2,m3):
self.m1=m1
self.m2=m2
self.m3=m3
#self.avg()
@classmethod
def m1(cls):
print(cls.inst)
@staticmethod
def add(a,b):
print("sum is:",a+b)
@staticmethod
def f1():
print("Hello")
s1=Student(78,87,69)
s2=Student(90,86,94)
#print(s1.avg())
#print(s2.avg())
s1.avg()
s2.avg()
Student.m1()
s1.add(10,20)
s1.f1()
Page 16 of 117
MOHAN S.REDDY
Ex:
class Test:
a=10 #static variable
def __init__(self):
print("Inside the constructor")
print(self.a)
print(Test.a)
def m1(self):
print("Inside the instance method")
print(self.a)
print(Test.a)
@classmethod
def m2(cls):
print("Inside the class method")
print(cls.a)
print(Test.a)
@staticmethod
def m3():
print("Inside the static method")
print(Test.a)
t=Test()
t.m1()
t.m2()
t.m3()
print("Outside of the class")
print(Test.a)
print(t.a)
Page 17 of 117
MOHAN S.REDDY
Inner class:
o Sometimes we can declare a class inside another class is called inner
class.
o A class which is having one more class within it is called inner class.
o Without existing one type of object if there is no chance of existing
another type of object then we use inner class mechanism.
def f1(self):
print("outer class method")
class Inner:
def __init__(self):
print("Inner class constructor")
def m1(self):
print("Inner class method")
'''o=Outer()
i=o.Inner()
i.m1()'''
'''i=Outer().Inner()
i.m1()'''
#Outer().Inner().m1()
o=Outer()
o.f1()
i=o.Inner()
i.m1()
Page 18 of 117
MOHAN S.REDDY
GC (GARBAGE COLLECTOR):
Ex:
import gc
print(gc.isenabled())
gc.disable()
print(gc.isenabled())
gc.enable()
print(gc.isenabled())
Page 19 of 117
MOHAN S.REDDY
DESTRUCTORS:
Ex:
import time
class Test:
def __init__(self):
print("Constructor execution")
def __del__(self):
print("Destructor execution")
t=Test()
time.sleep(5)
print("End of the program")
Page 20 of 117
MOHAN S.REDDY
Ex:
import sys
class Test:
pass
t1 = Test()
t2 = t1
t3 = t1
t4 = t1
print(sys.getrefcount(t1))
ENCAPSULATION:
Page 21 of 117
MOHAN S.REDDY
Ex:
class Test:
x=10 #public
_y=20 #protected
__z=30 #private
def __init__(self):
print("within the class")
print(self.x)
print(self._y)
print(self.__z)
t=Test()
print("outside of the class")
print(t.x)
print(t._y)
print(t.__z) #AttributeError: 'Test' object
has no attribute '__z'
Ex:
class Parent:
x=10 #public
_y=20#protected
__z=30 #private
class Child(Parent):
print(Parent.x)
print(Parent._y)
#print(Parent.__z) #AttributeError: type
object 'Parent' has no attribute '_Child__z'
c=Child()
Page 22 of 117
MOHAN S.REDDY
Ex:
class Car:
def __init__(self):
self.__updatesoftware()
c=Car()
#c.__updatesoftware() #AttributeError: 'Car'
object has no attribute '__updatesoftware'
Ex:
class Car:
__name=""
__maxspeed=0
def __init__(self):
self.__name="verna"
self.__maxspeed=100
print(self.__name)
print(self.__maxspeed)
def drive(self):
self.__maxspeed=200
print("Driving")
print(self.__name)
print(self.__maxspeed)
c=Car()
#c.__maxspeed=200 #maxspeed will not change
c.drive()
Page 23 of 117
MOHAN S.REDDY
INHERITANCE:
Syntax :
class Baseclass:
body of the base class
class Derivedclass (Baseclass):
body of the derived class
class Branch:
def getbranchdata(self):
self.bcode=int(input("Enter branch code:"))
self.bname=input("Enter branch name:")
self.baddress=input("Enter branch address:")
def displaybranchdata(self):
print("Branch code is:",self.bcode)
print("Branch name is:",self.bname)
print("Branch address is:",self.baddress)
Page 24 of 117
MOHAN S.REDDY
class Employee(Branch):
def getempdata(self):
self.eid=int(input("Ente eid:"))
self.ename=input("Enter ename:")
self.eaddress=input("Enter eaddress:")
def displayempdata(self):
print("Empid is:",self.eid)
print("Ename is:",self.ename)
print("Eaddress is:",self.eaddress)
class Salary(Employee):
def getsal(self):
self.basic=int(input("Enter basic salary:"))
def calculate(self):
self.DA=self.basic*0.06
self.HRA=self.basic*0.4
self.Gross=self.basic+self.DA+self.HRA
def displaysal(self):
print("Basic is:",self.basic)
print("DA is:",self.DA)
print("HRA is:",self.HRA)
print("Gross is:",self.Gross)
s=Salary()
s.getbranchdata()
s.getempdata()
s.getsal()
s.calculate()
s.displaybranchdata()
s.displayempdata()
s.displaysal()
Page 25 of 117
MOHAN S.REDDY
class Child1(Parent):
def f2(self):
print("Child1 class method")
class Child2(Parent):
def f3(self):
print("Child2 class method")
c1=Child1()
c2=Child2()
c1.f1()
c1.f2()
c2.f1()
c2.f3()
isinstance():
It is used to check whether the object is an instance of
particular class or not
issubclass():
It is used to check whether the class is a subclass of particular
class or not
Ex:
class Parent:
def f1(self):
print("Parent class method")
class Child1(Parent):
def f2(self):
print("Child1 clas method")
Page 26 of 117
MOHAN S.REDDY
class Child2(Parent):
def f3(self):
print("child2 class method")
c1=Child1()
c2=Child2()
print(isinstance(c1,Child1)) #true
print(isinstance(c2,Child2)) #true
print(isinstance(c1,Child2)) #false
print(isinstance(c2,Child1)) #false
print(isinstance(c1,Parent))# true
print(isinstance(c2,Parent))# true
print(issubclass(Child1,Parent)) #true
print(issubclass(Child2,Parent)) #true
print(issubclass(Child1,Child2)) #false
print(issubclass(Child2,Child1)) #false
class A:
def f1(self):
print("F1 function of class A")
class B:
def f2(self):
print("F2 function of class B")
class C(A,B):
def f3(self):
print("F3 function of class C")
Page 27 of 117
MOHAN S.REDDY
c=C()
c.f1()
c.f2()
c.f3()
Ex :
class A:
def f1(self):
print("F1 function of class A")
class B:
def f1(self):
print("F1 function of class B")
class C(A,B):
def f3(self):
B.f1(self)
print("F3 function of class C")
c=C()
c.f1()
c.f3()
class B:
def f1(self):
print("F1 function of class B")
class C(A,B):
def f3(self):
B.f1(self)
print("F3 function of class C")
Page 28 of 117
MOHAN S.REDDY
class D(C):
def f4(self):
print("F4 function of class D")
class E(C):
def f5(self):
print("F5 function of class E")
e=E()
e.f1()
e.f3()
e.f5()
d=D()
d.f1()
d.f3()
d.f4()
POLYMORPHISM:
Page 29 of 117
MOHAN S.REDDY
OPERATOR OVERLOADING:
b1=Book(10)
b2=Book(20)
print(b1+b2) #TypeError: unsupported operand
type(s) for +: 'Book' and 'Book'
Page 30 of 117
MOHAN S.REDDY
Ex :
class Book:
def __init__(self,pages):
self.pages=pages
b1=Book(10)
b2=Book(20)
print(b1+b2)
print(b1*b2)
Ex :
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
class TimeSheet:
def __init__(self, name, days):
self.name = name
self.days = days
e = Employee('Durga', 500)
t = TimeSheet('Durga', 25)
print('This Month Salary:', e * t)
Page 31 of 117
MOHAN S.REDDY
METHOD OVERLOADIN G:
Ex:
class Test:
def m1(self):
print("no arg method")
def m1(self,a):
print("one arg method")
def m1(self,a,b):
print("two arg method")
t=Test()
#t.m1()
#t.m1(10)
t.m1(10,20)
Page 32 of 117
MOHAN S.REDDY
Ex:
class Test:
def __init__(self):
print("no arg constructor")
def __init__(self,a):
print("one arg constructor")
def __init__(self,a,b):
print("two arg constructor")
#t =Test()
#t =Test(10)
t=Test(10,20)
class Parent:
def property(self):
print("Cash+Gold+Lands")
def car(self):
print("Alto car")
class Child(Parent):
def car(self):
super().car()
print("Benz car")
c=Child()
c.property()
c.car()
Page 33 of 117
MOHAN S.REDDY
Ex :
class Parent:
def __init__(self):
print("Parent class constructor")
class Child(Parent):
def __init__(self):
super().__init__()
print("Child class constructor")
c=Child()
ABSTRACT METHOD:
Page 34 of 117
MOHAN S.REDDY
ABSTRACT CLASS:
Ex :
from abc import ABC,abstractmethod
class Test(ABC):
@abstractmethod
def m1(self):
pass
Ex :
from abc import ABC,abstractmethod
class Vehicle(ABC):
@abstractmethod
def wheels(self):
pass
def engine(self):
print("Bs6 engine")
@abstractmethod
def color(self):
pass
Page 35 of 117
MOHAN S.REDDY
class Car(Vehicle):
def wheels(self):
print("Car:4 wheels")
def color(self):
print("Car:color is red")
class Bike(Vehicle):
def wheels(self):
print("Bike:2 wheels")
def color(self):
print("Bike:color is black")
c=Car()
c.wheels()
c.engine()
c.color()
b=Bike()
b.wheels()
b.engine()
b.color()
Page 36 of 117
MOHAN S.REDDY
EXCEPTION HANDLING:
RUNTIME ERRORS:
1. Logical implementation
2. Try except implementation
Page 37 of 117
MOHAN S.REDDY
1. Name error
2. Value error
3. Type error
4. Zero division error
5. File not found error
6. File exist error etc.
Page 38 of 117
MOHAN S.REDDY
Note: In the above example when user give second number as zero then
we will get ZeroDivisionError, we can handle this by using logical
statements as follows.
Ex:
a=int(input("Enter Num1:"))
b=int(input("Enter Num2:"))
if b==0:
print("second num cant be zero")
else:
print("result is:",a/b)
Note: All the exceptions may not possible to handle using logical
statements in that case we use try except implementation.
Page 39 of 117
MOHAN S.REDDY
Syntax:
try:
Statements
except:
Statements
In general inside the try block we include risky statements and inside
except block we include handling statements.
If no exception occurs inside the try block then try block statements
will execute and except block will ignore.
If any exception occurs inside the try block then try block will ignore
and except block will execute.
Ex:
try:
a = int(input("Enter Num1:"))
b = int(input("Enter Num2:"))
print("result is:", a / b)
except :
print("something went wrong")
In the above example, any type of exception raised then we will get
same message that is something went wrong.
To display the proper exception information then we use specific
except block.
Page 40 of 117
MOHAN S.REDDY
Ex:
try:
a = int(input("Enter Num1:"))
b = int(input("Enter Num2:"))
print("result is:", a / b)
except ZeroDivisionError as msg:
print(msg)
Ex:
try:
a = int(input("Enter Num1:"))
b = int(input("Enter Num2:"))
print("result is:", a / b)
except ZeroDivisionError as msg:
print(msg)
except ValueError as msg:
print(msg)
Ex:
try:
a = int(input("Enter Num1:"))
b = int(input("Enter Num2:"))
print("result is:", a / b)
except(ZeroDivisionError,ValueError)as msg:
print(msg)
Page 41 of 117
MOHAN S.REDDY
Ex:
try:
a = int(input("Enter Num1:"))
b = int(input("Enter Num2:"))
print("result is:", a / b)
except Exception as msg:
print(msg)
Note: While working with specific except block and default except
block make sure that default except block should be last otherwise
we will get syntax error.
Ex:
try:
a = int(input("Enter Num1:"))
b = int(input("Enter Num2:"))
print("result is:", a / b)
except:
print("something went wrong")
except ZeroDivisionError as msg:
print(msg)
#SyntaxError: default 'except:' must be last
Ex:
try:
a = int(input("Enter Num1:"))
b = int(input("Enter Num2:"))
print("result is:", a / b)
except ZeroDivisionError as msg:
print(msg)
except:
print("something went wrong")
Page 42 of 117
MOHAN S.REDDY
Ex:
try:
print("statement-1")
#print("statement-2")
print(10/0)
print("statement-3")
except :
print(10/0)
#print("statement-4")
print("statement-5")
Page 43 of 117
MOHAN S.REDDY
Ex:
try:
#print(10/0)
print("try block")
except:
print("except block")
finally:
print("finally block")
There is only one situation where finally block won't be executed i.e.
whenever we are using os._exit (0) function.
Whenever we are using os._exit(0) function then Python Virtual
Machine itself will be shutdown. In this particular case finally won't
be executed.
Here 0 represents status code and it indicates normal termination
Page 44 of 117
MOHAN S.REDDY
Ex:
import os
try:
#print(10/0)
print("try block")
#os._exit(0)
except:
print("Except block")
os._exit(0)
finally:
print("finally block")
Nested try-except-finally blocks:
Ex:
try:
#print(10/0)
print("Outer try")
try:
print(10/0)
print("Inner try")
except ValueError:
print("Inner except")
finally:
print("Inner finally")
except:
print("Outer except")
finally:
print("Outer finally")
If the control entered into try block then compulsory finally block
will be executed. If the control not entered into try block then finally
block won't be executed.
Whenever we are writing try block, compulsory we should write
except or finally block.i.e without except or finally block we cannot
write try block.
Whenever we are writing except block, compulsory we should write
try block. i.e. except without try is always invalid.
Whenever we are writing finally block, compulsory we should write
try block. i.e. finally without try is always invalid.
We can write multiple except blocks for the same try, but we cannot
write multiple finally blocks for the same try
TYPES OF EXCEPTIONS:
1. Predefined exceptions
2. User defined exceptions
Page 46 of 117
MOHAN S.REDDY
Syntax:
class classname(predefined exception class name):
def __init__(self,arg):
self.msg=arg
Ex:
class Too_oldException(Exception):
def __init__(self,arg):
self.msg=arg
class Too_youngException(Exception):
def __init__(self,arg):
self.msg=arg
Ex:
class Too_oldException(Exception):
def __init__(self,arg):
self.msg=arg
class Too_youngException(Exception):
def __init__(self,arg):
self.msg=arg
try:
age = int(input("Enter your age:"))
if age > 60:
raise Too_oldException("Age should not
exceed 60")
Page 47 of 117
MOHAN S.REDDY
FILE HANDLING:
TYPES OF FILES:
Page 48 of 117
MOHAN S.REDDY
FILE MODES:
r ------- Open an existing file for read operation. The file pointer is
positioned at the beginning of the file. If the specified file does not
exist then we will get FileNotFoundError.This is default mode.
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 that file.
r+ ------- To read and write data into the file. The previous data in the
file will not be deleted. The file pointer is placed at the beginning of
the file.
a+ ------- To append and read data from the file. It won’t override
existing data.
Note: All the above modes are applicable for text files. If the above
modes suffixed with 'b' then these represents for binary files.
Ex: rb, wb, ab, r+b, w+b, a+b, xb
CLOSING A FILE:
Page 49 of 117
MOHAN S.REDDY
Once we open a file and we got file object, we can get various details
related to that file by using its properties.
name --- Name of opened file
mode ---Mode in which the file is opened
closed ---Returns boolean value indicates that file is closed or not
readable()--- Returns boolean value indicates that whether file is
readable or not
writable()--- Returns boolean value indicates that whether file is
writable or not.
Ex:
f=open("sample.txt","w")
print("file name is:",f.name)
print("file mode is:",f.mode)
print("is file readable?",f.readable())
print("is file writable?",f.writable())
print("is file closed?",f.closed)
f.close()
print("is file closed?",f.closed)
We can write character data to the text files by using the following 2
methods.
write(str)
writelines(list of lines)
Ex:
f=open("abc.txt",'w')
f.write("Hello\n")
f.write("Durgasoft\n")
f.write("Hyderabad\n")
print("Data written to the file")
f.close()
Page 50 of 117
MOHAN S.REDDY
Ex:
f=open("sample.txt",'w')
l=["sai\n","ram\n","mohan\n","durga\n"]
f.writelines(l)
print("List data written to the file")
f.close()
Ex:
f=open("xyz.txt",'a')
f.write("Hello durgasoft\n")
print("data written to the file")
f.close()
We can read character data from text file by using the following read
methods.
Page 51 of 117
MOHAN S.REDDY
Ex:
try:
f = open("sample.txt", 'r')
#data = f.read()
#data=f.read(5)
#data=f.readline()
data=f.readlines()
print(data)
f.close()
except FileNotFoundError as msg:
print(msg)
Ex:
with open("abcd.txt","w") as f:
f.write("Hello\n")
f.write("Hyderabad\n")
print("is file closed?",f.closed)
print("is file closed?",f.closed)
Page 52 of 117
MOHAN S.REDDY
Ex:
f=open("abc.txt",'r')
print(f.tell())
print(f.read(3))
print(f.tell())
f.seek(11)
print(f.tell())
data="hello hyderabad"
f=open("rrr.txt",'w')
f.write(data)
with open("rrr.txt","r+") as f:
print("current cursor position:",f.tell())
text=f.read()
print(text)
print("current cursor position:",
f.tell())
f.seek(6)
print("current cursor position:",
f.tell())
f.write("Durgasoft")
print("current cusor position:",f.tell())
f.seek(0)
text=f.read()
print("Data after modification")
print(text)
Page 53 of 117
MOHAN S.REDDY
if os.path.isfile(fname):
print("file is exist:",fname)
f=open(fname,'r')
else:
print("file does not exist:",fname)
os._exit(0)
text=f.read()
print("content of the file")
print(text)
import os
fname=input("Enter file name to cehck:")
if os.path.isfile(fname):
print("file is exist:",fname)
f=open(fname,'r')
else:
print("file does not exist:",fname)
os._exit(0)
lcount=ccount=wcount=0
for line in f:
lcount=lcount+1
ccount=ccount+len(line)
words=line.split(" ")
wcount=wcount+len(words)
print("No of lines:",lcount)
print("No of characters:",ccount)
print("No of words:",wcount)
Page 54 of 117
MOHAN S.REDDY
We have to create ZipFile class object with name of the zip file, mode
and constant ZIP_DEFLATED. This constant represents we are
creating zip file.
Ex : f = ZipFile("files.zip","w","ZIP_DEFLATED")
f=ZipFile("files.zip","w",ZIP_DEFLATED)
f.write("xyz.txt")
f.write("abc.txt")
f.write("rrr.txt")
print("Zip file created")
f.close()
Page 55 of 117
MOHAN S.REDDY
Ex:
f=ZipFile("files.zip",'r',ZIP_STORED)
names=f.namelist()
print(names)
print(type(names))
Page 56 of 117
MOHAN S.REDDY
import csv
with open("emp.csv","w",newline='')as f:
w=csv.writer(f)
w.writerow(["Eno","Ename","Esal","Eaddr"])
n=int(input("Enter no of employees:"))
for i in range(n):
eno=input("Enter emp no:")
ename=input("Enter emp name:")
esal=input("Enter emp sal:")
eaddr=input("Enter emp address:")
w.writerow([eno,ename,esal,eaddr])
print("Employee data written to csv file")
import csv
f=open("emp.csv","r")
r=csv.reader(f)
data=list(r)
Page 57 of 117
MOHAN S.REDDY
import pickle
class Employee:
def __init__(self,eid,ename,eaddress):
self.eid=eid
self.ename=ename
self.eaddress=eaddress
def display(self):
print(self.eid,self.ename,self.eaddress)
with open("emp.dat","wb") as f:
e=Employee(101,"sai","hyderabad")
pickle.dump(e,f)
print("pickling of employee object
completed")
with open("emp.dat","rb") as f:
obj=pickle.load(f)
print("Display emp information after
unpickling")
obj.display()
A DAT file is a data file that contains specific information about the
program used to create it.
This file always has the . dat file extension, which is a generic format
that can contain any information – video, audio, PDF, and virtually
any other type of file.
Page 58 of 117
MOHAN S.REDDY
REGULAR EXPRESSIONS:
Function of re module:
1. compile()
2. finditer()
3. match()
4. fullmatch()
5. search()
6. findall()
7. sub()
8. subn()
9. split()
Page 59 of 117
MOHAN S.REDDY
Ex:
import re
count=0
pattern=re.compile("ab")
match=pattern.finditer("abaababa")
for m in match:
count+=1
print(m.start(),"...",m.end(),"...",m.group())
print("The number of occurrences: ",count)
CHARACTER CLASSES:
[abc]===>Either a or b or c
[^abc] ===>Except a and b and c
[a-z]==>Any Lower case alphabet symbol
[A-Z]===>Any upper case alphabet symbol
[a-zA-Z]==>Any alphabet symbol
[0-9]==> Any digit from 0 to 9
[a-zA-Z0-9]==>Any alphanumeric character
[^a-zA-Z0-9]==>Except alphanumeric characters(Special
Characters)
Ex:
import re
match=re.finditer("[abc]","a7Sb@k9#Az")
#match=re.finditer("[^abc]","a7Sb@k9#Az")
#match=re.finditer("[a-z]","a7Sb@k9#Az")
#match=re.finditer("[A-Z]","a7Sb@k9#Az")
#match=re.finditer("[0-9]","a7Sb@k9#Az")
#match=re.finditer("[a-zA-Z]","a7Sb@k9#Az")
#match=re.finditer("[a-zA-Z0-9]","a7Sb@k9#Az")
#match=re.finditer("[^a-zA-Z0-
9]","a7Sb@k9#Az")
for m in match:
print(m.start(),"......",m.group())
Page 60 of 117
MOHAN S.REDDY
\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)
. Any character including special characters
Ex:
import re
match=re.finditer("\s","a7Sb @k 9#Az")
#match=re.finditer("\S","a7Sb @k 9#Az")
#match=re.finditer("\d","a7Sb @k 9#Az")
#match=re.finditer("\D","a7Sb @k 9#Az")
#match=re.finditer("\w","a7Sb @k 9#Az")
#match=re.finditer("\W","a7Sb @k 9#Az")
#match=re.finditer(".","a7Sb @k 9#Az")
for m in match:
print(m.start(),"......",m.group())
QUANTIFIERS:
Page 61 of 117
MOHAN S.REDDY
Ex:
import re
match=re.finditer("a","abaabaaab")
#match=re.finditer("a+","abaabaaab")
#match=re.finditer("a*","abaabaaab")
#match=re.finditer("a?","abaabaaab")
#match=re.finditer("a{2}","abaabaaab")
#match=re.finditer("a{2,3}","abaabaaab")
for m in match:
print(m.start(),"......",m.group())
match ():
Ex:
import re
p=input("Enter pattern to check:")
m=re.match(p,"hyderabad")
if m!= None:
print("Match is available at the beginning
of the String")
print("Start Index:",m.start(), "and End
Index:",m.end())
else:
print("Match is not available at the
beginning of the String")
print(m)
Page 62 of 117
MOHAN S.REDDY
fullmatch ():
Ex:
import re
p=input("Enter pattern to check: ")
m=re.fullmatch(p,"hyderabad")
if m!= None:
print("Full String Matched")
else:
print("Full String not Matched")
print(m)
search ():
Ex:
import re
p=input("Enter pattern to check: ")
m=re.search(p,"hyderabad")
if m!= None:
print("Match is available")
print("First Occurrence of match with
start index:",m.start(),"and end
index:",m.end())
else:
print("Match is not available")
print(m)
Page 63 of 117
MOHAN S.REDDY
findall ():
Ex:
import re
l=re.findall("[0-9]","a7b9c5kz")
print(l)
sub ():
sub means substitution or replacement
re.sub(regex,replacement,targetstring)
In the target string every matched pattern will be replaced with
provided replacement.
Ex:
import re
s=re.sub("[a-z]","#","a7b9c5k8z")
print(s)
subn ():
It is exactly same as sub except it can also returns the number of
replacements.
This function returns a tuple where first element is result string and
second element is number of replacements.
Ex:
import re
t=re.subn("[a-z]","#","a7b9c5k8z")
print(t)
print("The Result String:",t[0])
print("The number of replacements:",t[1])
Page 64 of 117
MOHAN S.REDDY
split ():
If we want to split the given target string according to a particular
pattern then we should go for split() function.
This function returns list of all tokens.
Ex:
import re
l = re.split(",",
"shashi,nandan,shanvi,mohan,sruthi")
print(l)
for t in l:
print(t)
Ex:
import re
l = re.split("\.", "www.durgasoft.com")
print(l)
for t in l:
print(t)
^ Symbol:
We can use ^ symbol to check whether the given target string starts
with our provided pattern or not.
Ex:
import re
s="Learning Python is Very Easy"
m=re.search("^Learn",s)
if m != None:
print("Target String starts with Learn")
else:
print("Target String Not starts with
Learn")
Page 65 of 117
MOHAN S.REDDY
$ Symbol:
We can use $ symbol to check whether the given target string ends
with our provided pattern or not.
Ex:
import re
s="Learning Python is Very Easy"
m=re.search("Easy$",s)
if m != None:
print("Target String Ends with Easy")
else:
print("Target String Not Ends with Easy")
Rules:
1. Every number should contains exactly 10 digits
2. The first digit should be 7 or 8 or 9
[7-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]
Or
[7-9][0-9]{9}
Or
[7-9]\d{9}
Or
\d{10}--- to represent 10-digit mobile numbers
Page 66 of 117
MOHAN S.REDDY
Ex:
import re
n=input("Enter mobile number:")
m=re.fullmatch("[7-9]\d{9}",n)
if m!= None:
print("Valid Mobile Number")
else:
print("Invalid Mobile Number")
Ex:
import re
mailid=input("Enter Mail id:")
m=re.fullmatch("\w[a-zA-Z0-
9_.]*@gmail[.]com",mailid)
if m!=None:
print("Valid Mail Id");
else:
print("Invalid Mail id")
\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*
Ex:
import re
mailid=input("Enter Mail id:")
m=re.fullmatch("\w+([-+.']\w+)*@\w+([-
.]\w+)*\.\w+([-.]\w+)*",mailid)
if m!=None:
print("Valid Mail Id");
else:
print("Invalid Mail id")
Page 67 of 117
MOHAN S.REDDY
These are the Memory Areas where Data will be stored temporarily.
Ex: Python objects like List, Tuple, and Dictionary.
Once Python program completes its execution then these objects will
be destroyed automatically and data will be lost.
Databases:
Page 68 of 117
MOHAN S.REDDY
def read(con):
print("Reading data from Database")
cursor=con.cursor()
cursor.execute("select*From emp")
for row in cursor:
print(row)
print()
def create(con):
print("Inserting data into Database")
cursor=con.cursor()
cursor.execute("insert into
emp(id,name,address,salary)
values(?,?,?,?);",(3,"mohan","hyd",5000))
con.commit()
read(con)
def update(con):
print("Updating data into Database")
cursor=con.cursor()
cursor.execute("update emp set
name=?,address=?,salary=? where
id=?;",("manoj","hyd",23000,1))
con.commit()
read(con)
Page 69 of 117
MOHAN S.REDDY
def delete(con):
print("Deleting data from Database")
cursor=con.cursor()
cursor.execute("delete from emp where id=2")
con.commit()
read(con)
con=pyodbc.connect("Driver={SQL
Server};server=.;database=python@8am")
read(con)
create(con)
update(con)
delete(con)
con.close()
import mysql.connector
try:
con=mysql.connector.connect(
user='root',
password='Shanvi@123',
#host='localhost',
#port=3306
)
if con.is_connected():
print("Connected successfully")
except:
print("unable to connect")
Page 70 of 117
MOHAN S.REDDY
import mysql.connector
try:
con=mysql.connector.connect(
user='root',
password='Shanvi@123',
host='localhost',
port=3306
)
if con.is_connected():
print("Connected successfully")
except:
print("unable to connect")
cur=con.cursor()
cur.execute(sql)
cur.close()
con.close()
Page 71 of 117
MOHAN S.REDDY
import mysql.connector
try:
con=mysql.connector.connect(
user='root',
password='Shanvi@123',
host='localhost',
database='mydb',
port=3306
)
if con.is_connected():
print("Connected successfully")
except:
print("unable to connect")
cur=con.cursor()
cur.execute(sql)
cur.close()
con.close()
Page 72 of 117
MOHAN S.REDDY
import mysql.connector
try:
con=mysql.connector.connect(
user='root',
password='Shanvi@123',
host='localhost',
database='mydb',
port=3306
)
if con.is_connected():
print("Connected successfully")
except:
print("unable to connect")
cur=con.cursor()
cur.execute(sql)
con.commit()
cur.close()
con.close()
Page 73 of 117
MOHAN S.REDDY
import mysql.connector
try:
con=mysql.connector.connect(
user='root',
password='Shanvi@123',
host='localhost',
database='mydb',
port=3306
)
if con.is_connected():
print("Connected successfully")
except:
print("unable to connect")
cur=con.cursor()
cur.execute(sql)
con.commit()
cur.close()
con.close()
Page 74 of 117
MOHAN S.REDDY
import mysql.connector
try:
con=mysql.connector.connect(
user='root',
password='Shanvi@123',
host='localhost',
database='mydb',
port=3306
)
if con.is_connected():
print("Connected successfully")
except:
print("unable to connect")
cur=con.cursor()
cur.execute(sql)
con.commit()
cur.close()
con.close()
Page 75 of 117
MOHAN S.REDDY
import mysql.connector
try:
con=mysql.connector.connect(
user='root',
password='Shanvi@123',
host='localhost',
database='mydb',
port=3306
)
if con.is_connected():
print("Connected successfully")
except:
print("unable to connect")
cur=con.cursor()
cur.execute(sql)
con.commit()
cur.close()
con.close()
Page 76 of 117
MOHAN S.REDDY
import mysql.connector
try:
con=mysql.connector.connect(
user='root',
password='Shanvi@123',
host='localhost',
database='mydb',
port=3306
)
if con.is_connected():
print("Connected successfully")
except:
print("unable to connect")
sql='select*from emp'
cur=con.cursor()
cur.execute(sql)
emp_details=cur.fetchall()
#print(emp_details)
for e in emp_details:
#print(e)
print("Id:",e[0])
print("Name:",e[1])
print("Address:",e[2])
cur.close()
con.close()
Page 77 of 117
MOHAN S.REDDY
import mysql.connector
cursor=''
con=''
try:
con=mysql.connector.connect(host='localhost',data
base='python_11am',user='root',password='Shanvi@1
23')
cursor=con.cursor()
cursor.execute("create table student(sid
int(5) primary key,sname varchar(10),saddress
varchar(10))")
print("Table is created")
sql="insert into student(sid,sname,saddress)
values(%s,%s,%s)"
records=[(101,"sai","hyd"),(102,"manoj","hyd")]
cursor.executemany(sql,records)
con.commit()
print("records inserted successfully")
cursor.execute("select*from student")
data=cursor.fetchall()
for row in data:
print("Student id:",row[0])
print("Student name:", row[1])
print("Student address:", row[2])
print()
except Exception as e:
if con==True:
con.rollback()
print("There is a problem with sql:",e)
else:
print("connection failed",e)
finally:
if cursor:
print("finally block")
cursor.close()
if con:
con.close()
Page 78 of 117
MOHAN S.REDDY
DECORATOR FUNCTIONS:
Ex:
def wish(name):
print("hello",name,"good morning")
wish("mohan")
wish("durga")
The above function can display always same output for any name
But we want to modify this function to provide different message if
name is "raj"
We can do this without touching wish () function by using decorator.
Page 79 of 117
MOHAN S.REDDY
Ex:
def decor(wish):
def inner(name):
if name=="raj":
print("hello raj good evening")
else:
wish(name)
return inner
@decor
def wish(name):
print("hello",name,"good morning")
wish("mohan")
wish("durga")
wish("raj")
Ex:
def mydiv(div):
def inner(a,b):
if a<b:
a,b=b,a
return div(a,b)
return inner
@mydiv
def div(a,b):
print(a/b)
div(2,4)
Note: we can call same function with decorator and without decorator.
Page 80 of 117
MOHAN S.REDDY
Ex:
def decor(wish):
def inner(name):
if name=="raj":
print("hello raj good evening")
else:
wish(name)
return inner
def wish(name):
print("hello",name,"good morning")
d = decor(wish)
GENERATOR FUNCTIONS:
Page 81 of 117
MOHAN S.REDDY
Normal collection:
Ex:
l = [x for x in
range(100000000000000000000000)]
for i in l:
print(i)
Note: we will get memory error in this case, because all these values
are required to store in the memory.
Generators:
Ex:
g = (x for x in
range(100000000000000000000000))
for i in g:
print(i)
Note: we will not get memory error in this case, because all these
values are not stored at the beginning.
Note: generators are best suitable for reading data from large files.
Page 82 of 117
MOHAN S.REDDY
Ex:
def f1():
yield 123
yield "sai"
yield "hyd"
yield 30000
g = f1()
print(type(g))
print(next(g))
print(next(g))
print(next(g))
print(next(g))
Ex:
def f1():
yield 123
yield "sai"
yield "hyd"
yield 30000
for i in f1():
print(i)
YIELD KEYWORD:
Page 83 of 117
MOHAN S.REDDY
ASSERTIONS:
The assert keyword lets you test if a condition in your code returns
True, if not, the program will raise an Assertion Error. You can write
a message to be written if the code returns False.
But the problem with the print function is after fixing the bug,
compulsory we have to delete extra added print statements
,otherwise these statements will be execute at runtime performance
problems and disturb the console output window.
The main advantage of assert statement over the print is after fixing
the bug we are not required to delete assert statements.
By seeing assertion error, programmer can analyse the code and fix
the problem.
Page 84 of 117
MOHAN S.REDDY
Ex:
def square(x):
return x*x
print(square(3))
print(square(4))
print(square(5))
Ex:
def square(x):
return x*x
print(square(3))
print(square(4))
print(square(5))
Page 85 of 117
MOHAN S.REDDY
LOGGING IN PYTHON:
Logs provide developers with an extra set of eyes that are constantly
looking at the flow that an application is going through. They can
store information.
The main advantages of logging are we can use log files while
performing debugging.
LOGGING LEVELS:
Page 86 of 117
MOHAN S.REDDY
Ex:
import logging
logging.basicConfig(filename='log.txt',
level=logging.WARNING)
print("Logging Module Demo")
logging.debug("This is debug message")
logging.info("This is info message")
logging.warning("This is warning message")
logging.error("This is error message")
logging.critical("This is critical message")
Note: In the above program only WARNING and higher level messages will
be written to log file.
If we set level as DEBUG then all messages will be written to log file.
Page 87 of 117
MOHAN S.REDDY
Ex:
import logging
logging.basicConfig(filename='log.txt',
level=logging.DEBUG)
print("Logging Module Demo")
logging.debug("This is debug message")
logging.info("This is info message")
logging.warning("This is warning message")
logging.error("This is error message")
logging.critical("This is critical message")
import logging
logging.basicConfig(filename='mylog.txt',level
=logging.INFO)
Page 88 of 117
MOHAN S.REDDY
PACKAGES IN PYTHON:
For example, we keep all our games in a Games folder and we can
even subcategorize according to the genre of the game or something
like this. The same analogy is followed by the Python package.
Syntax:
Import sys
Page 89 of 117
MOHAN S.REDDY
module1.py:
def display():
print("display function from module1")
module2.py:
def show():
print("show function from module2")
Page 90 of 117
MOHAN S.REDDY
mainprogram.py:
import sys
sys.path.append("F:/pythonProject@8am/package1
")
#option1
import module1
import module2
module1.display()
module2.show()
#option2
from module1 import *
from module2 import *
display()
show()
Page 91 of 117
MOHAN S.REDDY
module1.py:
def display():
print("display function from module1-
package1")
module2.py:
def show():
print("show function from module2-
subpackage-package1")
Page 92 of 117
MOHAN S.REDDY
mainprogram.py:
import sys
sys.path.append("F:/pythonProject@8am/package1")
display()
sys.path.append("F:/pythonProject@8am/package1/
subpackage")
from module2 import *
show()
Now run the manprogram and check.
Page 93 of 117
MOHAN S.REDDY
module1.py:
class Employee:
def __init__(self,eid,ename,eaddress):
self.eid=eid
self.ename=ename
self.eaddress=eaddress
def displayemp(self):
print(self.eid,self.ename,self.eaddress)
module2.py:
class Student:
def __init__(self,sid,sname,saddress):
self.sid=sid
self.sname=sname
self.saddress=saddress
def displaystu(self):
print(self.sid,self.sname,self.saddress)
mainprogram.py:
import sys
sys.path.append("F:\pythonProject@8am\package1")
sys.path.append("F:\pythonProject@8am\package2")
Page 94 of 117
MOHAN S.REDDY
MULTI-THREADING IN PYTHON:
Multi-tasking:
Page 95 of 117
MOHAN S.REDDY
Ex:
import threading
print("Current Executing
Thread:",threading.current_thread().getName())
threading.current_thread().setName("MohanThrea
d")
print("Current Executing
Thread:",threading.current_thread().getName())
Ex:
import warnings
warnings.filterwarnings("ignore",
category=DeprecationWarning)
from threading import *
print("Current Executing
Thread:",current_thread().getName())
current_thread().setName("MohanThread")
print("Current Executing
Thread:",current_thread().getName())
Page 96 of 117
MOHAN S.REDDY
import time
def square(numbers):
for n in numbers:
time.sleep(1)
print("square is:",n*n)
def cube(numbers):
for n in numbers:
time.sleep(1)
print("cube is:",n*n*n)
numbers=[2,3,4,5,6]
t=time.time()
square(numbers)
cube(numbers)
print("Done in:",time.time()-t)
#Done in: 10.334125518798828
Page 97 of 117
MOHAN S.REDDY
import time
import threading
def square(numbers):
for n in numbers:
time.sleep(1)
print("square is:",n*n)
def cube(numbers):
for n in numbers:
time.sleep(1)
print("cube is:",n*n*n)
numbers=[2,3,4,5,6]
t=time.time()
t1=threading.Thread(target=square,args=(number
s,))
t2=threading.Thread(target=cube,args=(numbers,
))
t1.start()
t2.start()
t1.join()
t2.join()
print("Done in:",time.time()-t)
#Done in: 5.050450086593628
Page 98 of 117
MOHAN S.REDDY
Ex :
def display():
for i in range(10):
print("Child Thread")
t=Thread(target=display)
t.start()
Page 99 of 117
MOHAN S.REDDY
We have to create child class for Thread class, in that child class
we have to override run() method with our required job
class Test(Thread):
def run(self):
for i in range(10):
print("Child Thread")
t=Test()
t.start()
Ex :
class Test:
def display(self):
for i in range(10):
print("Child Thread")
t=Test()
t1=Thread(target=t.display)
t1.start()
Ex :
def f1():
print("Child Thread")
t=Thread(target=f1)
t.start()
print("Main Thread Identification
number:",current_thread().ident)
print("Child Thread Identification
number:",t.ident)
active_count ():
Ex :
def f1():
print(current_thread().getName(),"...started")
time.sleep(3)
print(current_thread().getName(),"...ended")
print("The no of active threads:",active_count())
t1=Thread(target=f1,name="childthread1")
t2=Thread(target=f1,name="childthread2")
t3=Thread(target=f1,name="childthread3")
t1.start()
t2.start()
t3.start()
is_alive ():
Ex :
def f1():
print(current_thread().getName(),"..started")
time.sleep(3)
print(current_thread().getName(),"...ended")
t1=Thread(target=f1,name="childthread1")
t2=Thread(target=f1,name="childthread2")
t1.start()
t2.start()
print(t1.name,"is Alive:",t1.is_alive())
print(t2.name,"is Alive:",t2.is_alive())
time.sleep(5)
print(t1.name,"is Alive:",t1.is_alive())
print(t2.name,"is Alive:",t2.is_alive())
Join ():
Ex :
def f1():
for i in range(10):
print("childthread")
time.sleep(1)
t=Thread(target=f1)
t.start()
THREAD SYNCHRONIZATION:
Ex :
def f1(name):
for i in range(10):
print("Good morning:",end="")
time.sleep(2)
print(name)
t1=Thread(target=f1,args=("mohan",))
t2=Thread(target=f1,args=("sai",))
t1.start()
t2.start()
l=Lock()
def f1(name):
l.acquire()
for i in range(10):
print("Good morning:",end="")
time.sleep(2)
print(name)
l.release()
t1=Thread(target=f1,args=("mohan",))
t2=Thread(target=f1,args=("sai",))
t1.start()
t2.start()
Page 106 of 117
MOHAN S.REDDY
Ex:
def res(n):
print("The factorial
of",n,"is:",factorial(n))
t1=Thread(target=res,args=(4,))
t2=Thread(target=res,args=(5,))
t1.start()
t2.start()
Ex:
s=Semaphore(2)
def f1(name):
s.acquire()
for i in range(10):
print("Good morning:",end="")
time.sleep(2)
print(name)
s.release()
t1=Thread(target=f1,args=("sai",))
t2=Thread(target=f1,args=("mohan",))
t3=Thread(target=f1,args=("kiran",))
t4=Thread(target=f1,args=("raj",))
t1.start()
t2.start()
t3.start()
t4.start()
Page 108 of 117
MOHAN S.REDDY
Bounded semaphore:
Ex:
Ex:
Series:
Data Frame:
Data Frame is defined as a standard way to store data and has two
different indexes, i.e., row index and column index.
Ex:
import pandas
s=pandas.Series()
print(s)
Page 110 of 117
MOHAN S.REDDY
Ex:
import pandas as pd
import numpy as np
data = np.array(['a','b','c','d'])
s = pd.Series(data,index=[100,101,102,103])
print(s)
Ex:
import pandas as pd
data = {'a' : 0., 'b' : 1., 'c' : 2.}
s = pd.Series(data,index=['b','c','d','a'])
print(s)
Ex:
import pandas as pd
s = pd.Series(5, index=[0, 1, 2, 3])
print(s)
Ex:
import pandas as pd
s = pd.Series([1,2,3,4,5],index =
['a','b','c','d','e'])
print(s)
print(s['a'])
print (s[:3])
Ex:
import pandas as pd
df = pd.DataFrame()
print(df)
Ex:
import pandas as pd
data = [1,2,3,4,5]
df = pd.DataFrame(data)
print(df)
Ex:
import pandas as pd
data = [['Alex',10],['Bob',12],['Clarke',13]]
df =
pd.DataFrame(data,columns=['Name','Age'],dtype
=float)
print(df)
Ex:
import pandas as pd
data = {'Name':['Tom', 'Jack', 'Steve',
'Ricky'],'Age':[28,34,29,42]}
df = pd.DataFrame(data)
print(df)
#df.tail(2)
df.head(1)
Ex:
import pandas as pd
data = {'Name':['Tom', 'Jack', 'Steve',
'Ricky'],'Age':[28,34,29,42]}
df = pd.DataFrame(data,
index=['rank1','rank2','rank3','rank4'])
print(df)
Ex:
import pandas as pd
df1 = pd.DataFrame([[1, 2], [3, 4]], columns =
['a','b'])
df2 = pd.DataFrame([[5, 6], [7, 8]], columns =
['a','b'])
df1 = df1.append(df2)
print(df1)
Ex:
import pandas as pd
df1 = pd.DataFrame({'name': ['John',
'Smith','Paul'],
'Age': ['25', '30',
'50']},
index=[0, 1, 2])
df2 = pd.DataFrame({'name': ['Adam', 'Smith'
],
'Age': ['26', '11']},
index=[3, 4])
df_concat = pd.concat([df1,df2])
print(df_concat)
Ex:
Ex:
# x-axis values
x = [5, 2, 1, 4, 7]
# Y-axis values
y = [10, 5, 8, 4, 2]
# Function to plot
plt.plot(x,y,marker='o')
# function to show the plot
plt.show()
Ex:
Ex:
x=[5,8,10]
y=[12,16,6]
x2=[6,9,11]
y2=[6,15,7]
plt.plot(x,y,'g',label="line one",linewidth=3)
plt.plot(x2,y2,'r',label="line
two",linewidth=5)
plt.title("Simple Graph")
plt.ylabel("Y axis")
plt.xlabel("X axis")
plt.legend()
plt.grid(True,color='b')
plt.show()
Ex:
plt.bar([1,3,5,7,9],[5,2,7,8,2],label="Bar
one",color='y')
plt.bar([2,4,6,8,10],[8,6,2,5,6],label="Bar
two",color='g')
plt.legend()
plt.xlabel('bar number')
plt.ylabel('bar height')
plt.title("Bar Graph")
plt.show()
Ex:
Ex:
days=[1,2,3,4,5]
sleeping=[7,8,6,11,7]
eating=[2,3,4,3,2]
working=[7,8,7,2,2]
playing=[8,5,7,8,13]
plt.plot([],[],color='m',label='sleeping',line
width=5)
plt.plot([],[],color='c',label='eating',linewi
dth=5)
plt.plot([],[],color='r',label='working',linew
idth=5)
plt.plot([],[],color='g',label='playing',linew
idth=5)
plt.stackplot(days,sleeping,eating,working,pla
ying,colors=['m','c','r','k'])
plt.xlabel('X')
plt.ylabel('Y')
plt.title("Stack plot")
plt.legend()
plt.show()
Ex: