PFSD
PFSD
Dt : 24/12/2022
PYTHON:
History:
1. Open Source.
2. Easy to use and learn.
3. Interpreted Language.
4.Object Oriented Programming Language.
5. Supports wide range of libraries and frameworks.
6. Integrated.
1. AI
2. Data Science
3. ML
4. Data Mining.
5. Computer Vision.
6. Mobile Apllications.
7. Web Applications.
8. Interprise Applications.
9. Desktop Applications.
10. Software Development.
Limitations of Python:
1. Very slow in execution(c executes much faster than python). --> python is slow
due to its libraries.
2. Not good for gaming.
3. Used Libraries.
Note :
PEP 8 --> style guide for python code
Dt : 27/12/2022
Python Example:
Welcome to PFSD course
Python Comments:
Comments are helpful in defining the code and making others in understanding.
# --> Single line comment.
""" ______
_________""" --> Multi Line Comments.
Python Variables:
1. variable is an entity in a program which holds a single value and known by its
name.
2. Variable is also known as identifier.
3. variable should consist of Alphabets(A-Z,a-Z), Digits, and "_".
4. It is recommended to name variables in lowercase letters.
Identifiers:
--> to name a Variable, Array and Function.
Var --> a, b, c, sum, res, etc.
Array --> a[5].
Function --> sum(), palindrome(), etc.
Delete Variables:
a = 25
syntax delete<>
Ex:
--> delete a
Object Reference:
In Python Variables are the symbolic names that is referenced to an object.
Ex: a = 25
--> a is referneced to an object called 25.
: a = b = c = 25
--> a, b , c are references of an object 25.
: a= 10 b = 20
--> a is referenced to object 10 and b is referenced to object 20.
Python DataTypes:
1. Number
--> int, float, complex
2. Dictionary
3. Boolean
4. Set
5. Sequence Type
--> String, list, tuple
1. Number:
a. int:
--> a = 10
print(a)
print(type(a))
b. float:
--> a = 9.51
print(a)
print(type(a))
c. Complex:
--> a = 3 + 4j
print(a)
print(type(a))
5. Sequence Type:
a. String:
String isa collection of characters.
or
String is a sequence of characters.
--> strings can have Alphabets([A - Z],[a - z]), Digits(0 - 9), special
characters(~, !, @, #, $, %, etc).
Note :
--> when we need to print '/' we should print it as '//' as '/' is an escape
sequence.
--> while printing multiple strings in a same print() we should follow the
following syntax:
print("Reddy" , "venkat" , "kalyan")
output : Reddy venkat kalyan
--> '/n' is used to print in next line
--> print() in python for strings has two inbuilt arguments:
1. end
2. sep
1. end example :
print("My name is reddy",end = " ")
print("venkat kalyan")
Output : My name is reddy venkat kalyan.
2. sep example :
print("My name is reddy","venkat","kalyan",sep="-")
Output : My name is reddy-venkat-kalyan.
Ex :
print("My", "name", "is", sep="_", end="*")
print("Monty", "Python.", sep="*", end="*\n")
Output : My_name_is*Monty*Python.*
Ex :
ch = 'a'
print(ord(ch)) --> 97
2. chr()
--> The chr() returns the charcter corresponding to the ascii value.
Ex :
print(chr(97)) --> a
3. isalnum()
--> Returns true if string contains only alphabets and letters.
4. capitalize()
--> changes the first character of a string to capital.
5. find()
--> returns the index if the susbstring is found else returns '-1'.
6. index()
--> retruns the index of the character.
7. isalpha()
--> returns true if the string contains all aplhabets.
8. isdigit()
--> returns true if the string contains all digits.
9. join()
--> print(" ".join(["omicron", "pi", "rho"]))
==> omicron pi rho
1o. swapcase()
--> changes capital to lower and vice-versa.
11. title()
--> changes every word of the string to capital.
Ex :
print("I know that I know nothing. Part 1.".title()) --> I Know That I Know
Nothing. Part 1.
1. Some of the methods offered by strings are:
2. String content can be determined using the following methods (all of them return
Boolean values):
Ex1:
s1 = "pfsd"
print(s1)
print(type(s1))
Ex2:
s1 = "hello"
s2 = "welcome to pfsd course"
Strong Slicing :
Ex :
alpha = "abdefg"
print(alpha[1:3]) ---> bd
print(alpha[3:]) ---> efg
print(alpha[:3]) ---> abd
print(alpha[3:-2]) ---> e
print(alpha[-3:4]) ---> e
print(alpha[::2]) ---> adf
print(alpha[1::2]) --> beg
Dt : 31/12/2022
b. List:
--> list is a collection of heterogenous / different items.
--> list is similar to array, whereas list is a collection of
heterogenous / different items but array is a collection of homoogenous / similar
items.
--> It is denoted by [].
Example:
list1 = [7,"kalyan",9.51,45]
print(list1)
print(list1[2])
print(list1[1:2])
print(list1[2:])
print(list1 * 3)
print(list1 + list1)
b. Tuple:
--> Tuple is a collection of heterogenous / different dataype
items.
--> tuple is similar to list, values in the list can be changed
but whereas values in the tuple cannot be changed.
--> It is denoted by ().
Example :
tuple1 = ("kalyan", 959, 9.51, 2004)
print(tuple1)
print(type(tuple1))
print(tuple1[1:2])
print(tuple1[2:])
print(tuple1*3)
print(tuple1+tuple1)
2. Dictionary:
--> Dictionary is an unordered set of key value per item(key.value).
--> It is denoted by { }.
Example:
dic1 = {1:"Hello",2:2100030959,3:"Good Morning"}
print(dic1)
print(type(dic1))
print(dic1[1])
print(dic1.keys())
print(dic1.values())
print(dic1.pop(2))
print(dic1)
print(dic1.clear())
#del dic1
#print(dic1)
Ex :
#iterating over a dictionary and printing
dictionary = {"cat": "chat", "dog": "chien", "horse": "cheval"}
Note :
--> dictionary_name.items() ==> returns the key value pairs while iterating.
--> dictionary_name.keys() ==> returns the keys while iterating.
--> dictionary_name.values() ==> returns the values associated with the key while
iterating.
--> dictionary_name.get('key') ==> returns the values associated with the key.
3. Boolean:
--> Boolean is a datatype which represents a statement stating True or False.
--> T or 1 and F or 0.
Note :
-->The name comes from George Boole (1815-1864), the author of the fundamental
work, The Laws of Thought,
which contains the definition of Boolean algebra - a part of algebra which makes
use of only two distinct values:
True and False, denoted as 1 and 0.
--> The backslash (\) symbol is used. If you use it in Python code and end a line
with it,
it will tell Python to continue the line of code in the next line of code.
Ex : (\)
if height < 1.0 or height > 2.5 or \
weight < 20 or weight > 200:
return None
--> The backslash (\) symbol is also used as a escape character when dealing with
strings.
Ex : (\)
print('No, it can\'t be a triangle.')
Example :
a = (True == 1)
print(a) --> True
Example:
a = (True == 1)
b = a + 10
print(b) --> 11
4. Set:
--> Set is a unordered collection of items.
--> It is denoted by { }
Example:
set1 = set() --> representation of an empty set in python.
set2 = {"abc",789,"def",45,9.33}
print(set1) --> set()
print(set2)
print(set2.add(9.67))
print(set2.add("abc"))
print(set2.remove(7))
print(set2.clear())
print(set2) --> set()
Dt : 04/01/2023
Python Keywords :
Keywords are unique/reserved words which are having pre-defined meaning.
--> In C there were 32 keywords earlier but present they are 48.
--> In Python there are 35 keywords.
Python Literals :
--> Literals are classified into four categories :
1. String Literals :
--> whenever we assign a string data to a variable or to a constant then it is
called as a String literal.
Ex :
s1 = "kalyan"
--> Strings are of two types :
1. Single Line String --> s1 = "rvk"
2. Multi Line String --> s1 = "reddy\
venkat kalyan"
2. Numeric Literals :
--> whenever we assign a number data to a varaible or to a constant then it is
called as a Numeric literal.
a. int :
Ex : a = 10
b. float :
Ex : a = 9.51
c . Complex :
Ex : a = 3 + 4j
3. Boolean Literals :
--> whenever we assign a boolean data to a varaible or to a constant then it is
called as a Boolean literal.
Ex :
a = True
4. Special Literals :
--> whenever we assign a special data to a varaible or to a constant then it is
called as a Special literal.
Ex :
a = None
Python Operators :
Operators are the symbols which performs the special task with respect to the
operands.
Ex : (a + b) * c
---> a, b, c are operands and +, * are operators.
--> In general operators are classified into three categories :
1. Unary Operators :
Any operation having one single operand is called as unary operator.
Ex : a++
2. Binary Opearotors :
Any operation having two operands is called as binary operator.
Ex : a + b
3. Terenary Operators :
Any operation with three or more operands is called as a terenary operator.
Ex : (a + b) * c
2. Relational Operators :
Ex : >, <, >=, <=, ==, !=
3. Logical Operators :
Ex : &&, ||
4. Bitwise Operators :
Ex : &, ^, <<, >>, ~
5. Assignment Operators :
Ex : =
6. Membership Opeartors :
--> in : returns true if the first operand is found in second object.
--> not in : returns true if the first operand is not found in second object
7. Identity Operators :
--> is : It returns true if both the first operand and second operand have the same
value.
--> is not : It returns true if the first operand and second operand does not
have the same value.
Priority Operator
1 +, -
2 **
3 *, /, //, %
4 +, -
5 <, <=, >, >=
6 ==, !=
b. elif
c. nested if
d. if else
Dt : 07/01/2023
b. if else :
Syntax : if condition:
Statement
else :
Statement
Ex: p20.py
a = 10
if a % 2 == 0:
print("Even Number")
else:
print("not a even number")
c. nested if :
Syntax : if condition :
if condition :
if condition :
statements
Ex : p21 .py
a = 8
if a < 10 :
if a % 2 == 0 :
print("a is less than 8 and is even")
else :
print("inner if condition fails)
else :
print("outer if condition fails")
d. elif :
Syntax :
if condition:
statements
elif condition:
statements
else:
statements
Ex : p22.py
a = 10
if a < 10 :
print("if condition get executed")
elif a % 2 == 0 :
print("1st elif block get executed")
else :
print("all the conditions failed")
Python Loops :
a. for loop :
Syntax :
for var in sequence :
statements
Note : sequence --> set, tuple, dictionary, string
Ex : p23.py
names = ("kalyan", "venkat", "reddy")
for x in names :
print(x)
Ex : p24.py
for x in "kalyan" :
print(x)
Ex : p25.py
for x in "kalyan" :
print(x)
else :
print("for loop executed successfully")
Ex : p26.py
for x in range(6):
print(x) --> 0 to 5
Ex : p27.py
for x in range(6, 25):
print(x) --> 6 to 24
Ex : p28.py
for x in range(6, 25, 2):
print(x) --> 6, 8, 10 ........................ 24
Ex : p29.py :
Vehicles = ["bike","car","plane"]
date = [2003, 2004, 2005]
for x in Vehicles:
for y in date:
print(x,y)
b. While loop
Syntax :
initialization
while condition:
statements
updation
Ex : p30.py
i = 1
while i <= 10:
print(i)
i = i + 1
c. do while(wrong)
Renamed as :
--> while with exit() condition
--> while with break statement
Ex : p32.py
i = 1
while i <= 10 :
print(i)
i += 1
if i == 5:
break
Note :
break :
--> to terminate from the current loop.
syntax --> break
Ex : p33.py
names = ("kalyan", "venkat", "reddy")
for x in names :
print(x)
if x == "venkat" :
break
Continue :
--> to skip all the statements after continue but execution remains in
the same loop.
Syntax : continue
Ex : p34.py
names = ("kalyan", "venkat", "reddy")
for x in names :
if x == "venkat" :
continue
print(x)
pass :
--> to do nothing
Syntax :
pass
Ex :
names = ("kalyan", "venkat", "reddy")
for x in names :
pass
Ex : p36.py
#program to check whether the number is palindrome or not
num = 121
x = 0
r = 0
z = num
while num > 0:
r = int(num % 10)
x = int(x * 10 + r)
num = int(num / 10)
#print(int(x))
if z == x :
print("palindrome")
else:
print("not a palindrome")
Ex : p37.py
# progrom to print palindrome numbers between 1 to 100
for i in range(1,100):
k = i
x = 0
while k > 0:
r = int(k %10)
x = int((x * 10) + r)
k = int(k / 10)
if i == x:
print(i)
Ex : p38.py
#program to check whether the given number is prime or not
n = 5
x = 0
for i in range(1, n + 1):
if n % i == 0:
x += 1
if x == 2:
print("prime")
else:
print("not prime")
Ex : p39.py
#program to dispaly all the prime numbers between 1 to 100
for i in range(1, 100):
x = 0;
k = i;
for j in range(1, k + 1):
if k % j == 0:
x += 1
if x == 2:
print(j)
Ex : p40.py
#program to demonstrate swapping of two numbers
a = 10
b = 20
c = a
a = b
b = c
print(a,b)
Dt : 10/01/2023
Python Functions :
Function is defined as a set of statements or group of statements or block of code
which perform a specific task.
Ex: p41.py
def add(x,y):
return x+y
a = add(1,2)
print(a)
Classification of Functions :
Ex :
x = input("enter any number")
35
print(x) --> 35
Ex :
x = input()
34
print(x) --> 34
Ex :
x = int(input()) --> only accepts a integer value.
34
print(x) --> 34
Types of Functions :
1. Functions with no arguments and no return type.
2. Functions with no arguments and return type.
3. Functions with arguments and no return type.
4. Functions with arguments and return type.
Types of Arguments :
1. Default Arguments :
Ex : p44.py
def add(a ,b = 10):
return a + b
print(add(10,5)) --> 15
print(add(10)) --> 20
Ex : p45.py
def add(a = 5,b = 10):
return a + b
print(add(10,5)) --> 15
print(add(10)) --> 20
print(add()) --> 15
2. Keyword Arguments :
Ex :
def stu(name, id,cgpa):
print(id,name,cgpa)
stu("kalyan",2100030959,9.45)
stu("kalyan",2100030959,cgpa = 9.5)
stu(name = "venkat",id = 2100030959,cgpa = 9.5)
Note :
Keyword arguments are also known as named arguments.
3. Required Arguments :
--> Number of arguments in function call = number of arguments in function
definition.
Ex :
def stu(name, id,cgpa):
print(id,name,cgpa)
stu("kalyan",2100030959,9.45)
Ex :
# program to demonstrate types of arguments
def add(a, b = 5):
return a + b
print(add(1,10)) --> 11(required)
print(add(10, b = 20)) --> 30(keyword)
print(10) --> 15(default)
Dt : 21/1/23
4. Arbitrary Arguments :
--> It can also be called as Variable length arguments.
Ex : p49.py
Recursive Fn's:
---------------
The fn which calls by itself is called recursive fn.
function()
Ex-p49.py
def factorial(x):
if x==1:
return x
else:
return (x*factorial(x-1))
print(factorial(3))
Lambda fn:
---------------
Lambda fn is a fn which allows multiple args but only one expr.
Ex-p50.py
x=lambda a:a*10
print(x(2))
y=lambda a,b:a+b
print(y(2,3))
z=lambda a,b,c:a+b+c
print(z(3,5,5))
Python Arrays:
---------------
->Array is a spl var, which can hold more than one value.
->it can hold many value under a single name, and can access the
values by reffring to its index value.
Syn:
array_name=[items separated by comma]
Ex:
vehicles=["bike","cycle",900]
Ex-p52.py
x=vehicles[2]
print(x)
Ex-p53.py:
y=len(vehicles)
print(y)
Looping Array Ele.:
Ex-p54.py
vehicles=["bike","cycle",900]
for x in vehicles:
print(x)
Ex: vehicles=["bike","cycle",221]
vehicles.append("Car")
vehicles.append(2342)
-remove
-pop
Ex:
vehicles=["bike","cycle",221]
vehicles.remove("cycle")
vehicles.pop(2)
Ex:
vehicles.clear()
-sort()
Ex:
vehicles.sort()
-reverse()
Ex:
vehicles.reverse( )
Dt : 24/01/23
Python OOP :
1.
--> Class is a collection of objects.
--> Class consists of data members and member functions(methods).
Syntax :
class Classname:
data members
data functions
Ex :
class Student:
id = 30959
def display(self):
print("Hello")
2. Object:
Syntax :
Objectname = Classname()
Ex :
ob1 = Student()
Ex : p53.py
#program to demonstrate object and class.
class Student:
id = 2100030959
name = "Kalyan"
def printStudentDetails(self):
print(self.id,self.name)
s1 = Student()
s1.printStudentDetails()
3. Methods :
--> A member function in a class is known as methods.
Ex:
def display(self):
print("Example of method")
Note :
=> Special method = Constructor
--> Constructors are defined to instantiate the instance members of a class.
--> method_ _init_ _() is used to represent constructor.
--> constructors are invoked automatically at the time of object creation.
--> Classification of constructors :
--> parameterized constructors.
--> Non-parameterized constructors.
1. parameterized constructors:
Ex :
#program to display parameterized constructors:
class Student:
def __init__(self,id, name):
self.id=id
self.name=name
def display(self):
print(self.id,self.name)
s1 = Student(30959,"kalyan")
s1.display()
2. Non-parameterized constructors:
Ex :
#program to demonstrate the number of objects created.
class Student:
count = 0
def __init__(self):
Student.count+=1
s1=Student()
s2=Student()
s3=Student()
s4=Student()
print(Student.count) --> 4
Ex :
#program to demonstrate multiple constructors:
class Student:
def __init__(self):
print("First Constructor")
def __init__(self):
print("Second Constructor")
obj = Student()
4. Inheritance :
--> Acquiring the properties from one class to another class is known as
inheritance.
--> The class from which we acquire properties is called as base class.
--> The class to which we acquire properties is called as derived class.
Note :
--> Acquiring the properties from base class to derived class is known as
inheritance.
Types of Inheritances :
1. Single Inheritance.
2. Multiple Inheritance.
3. Multilevel Inheritance.
4. Hierarchial Inheritance.
5. Hybrid Inheritance.
1. Single Inheritance :
--> Acquiring the properties from one base class to one derived class is known as
single Inheritance.
Syntax :
class Base:
class block
class Derived(Base):
class block
Ex :p57.py
#program to demonstrate single inheritance:
class Base:
def fn1(self):
print("Base Class")
class Derived(Base):
def fn2(self):
print("Derived class")
obj = Derived()
obj.fn1()
obj.fn2()
2. Multiple Inheritance :
--> Acquiring the properties from multiple base classes to one derived class is
known as Multiple Inheritance.
Syntax :
class Base1:
class block
class Base2:
class block
class Base3:
class block
class derived(Base1,Base2,Base3):
class block
Ex :p58.py
#program to demonstrate multiple inheritance
class Base1:
def fn1(self):
print("Base1 class")
class Base2:
def fn2(self):
print("Base2 class")
class Derived(Base1, Base2):
def fn3(self):
print("Derived class")
dr = Derived()
dr.fn1()
dr.fn2()
dr.fn3()
3. Multilevel Inheritance :
--> Acquiring the properties from one class to another class, and then from that
class to another class in multiple levels is known as Multilevel Inheritance.
Syntax :
class Base1:
class block
class Base2(Base1):
class block
class Base3(Base2):
class block
class derived(Base3):
class block
Ex :p59.py
#program to demonstrate multilevel inheritance
class Base1:
def bfn1(self):
print("Base1 class")
class Base2(Base1):
def bfn2(self):
print("Base2 class")
class Base3(Base2):
def bfn3(self):
print("Base3 class")
class Derived(Base3):
def dfn1(self):
print("Derived class")
obj = Derived()
obj.bfn1()
obj.bfn2()
obj.bfn3()
obj.dfn1()
4. Hierarchial Inheritance :
--> Acquiring the properties from one base class to multiple derived classes is
known as Hierarchial Inheritance.
Syntax :
class Base:
class block
class Derived1(Base):
class bock
class Derived2(Base):
class block
Ex:p60.py:
#program to demonstrate hierarchial inheritance
class Base1:
def bfn1(self):
print("Base1 class")
class Derived1(Base1):
def dfn1(self):
print("Derived1 class")
class Derived2(Base1):
def dfn2(self):
print("Derived2 class")
obj1 = Derived2()
obj1.bfn1()
obj2 = Derived1()
obj2.dfn1()
obj1.dfn2()
5. Hybrid Inheritance :
--> Combination of Hierarchial and Multiple inheritances is known as Hybrid
Inheritance.
Syntax :
class Base:
class block
class Derived1(Base):
class bock
class Derived2(Base):
class block
class NewDerived(Derived1,Derived2):
class block
Ex : p61.py
#program to demonstrate hybrid inheritance:
class Base():
def bfn1(self):
print("Base class")
class Derived1(Base):
def dfn1(self):
print("Derived1 class")
class Derived2(Base):
def dfn2(self):
print("Derived2 class")
class NewDerived(Derived1,Derived2):
def ndfn3(self):
print("New Derived Class")
ob = NewDerived()
ob.bfn1()
ob.dfn1()
ob.dfn2()
ob.ndfn3()
Dt : 28/01/23
5. PolyMorphism :
--> PolyMorphism is a greek word where poly means many and morphism means forms. So
polymorphism is refered to many forms.
Types of PolyMorphism :
1. Compile Time PolyMorphism
2. Run Time PolyMorphism
1. Compile-Time PolyMorphism :
--> Method Overloading is an example of Compile-Time PolyMorphism.
Ex : p62.py
#program to demonstrate method overloading
class Addition:
def add(self,a=0,b=0,c=0):
return a+b+c
obj = Addition()
print(obj.add())
print(obj.add(10))
print(obj.add(10,20))
2. Run-Time PolyMorphism:
--> Method Overriding is an example of Run-Time PolyMorphism.
Ex : p63.py
#program to demonstrate method overrding
class Base:
def display(self):
print("Base class")
class Derived(Base):
def display(self):
print("Derived class")
od = Derived()
od.display()
6. Encapsulation :
--> Wrapping up of code and data together into a single unit is referred to
encapsulation.
7. Data Abstraction :
--> It refers to providing only essential information to the outside world by
hiding all its background details.
Ex :
class Stu:
id = 30959
name = "kalyan"
__cgpa = 9.35 --> data hiding
1. getattr(object,name):
--> It is used to access the attribute of an object.
2. setattr(object,name,value):
--> It is used to set the value of attribute of an object.
3. delattr(object,name):
--> It is used to delete the attribute of an object.
4. hasattr(object,name):
--> It is used to check whether an attribute of object is found or not.
--> It returns true if the attribute is found.
--> It returns false if the attribute is not found.
Ex : p64.py
#program to demonstrate built-in methods
class Student:
def __init__(self,id,name,cgpa):
self.id = id
self.name = name
self.cgpa = cgpa
st = Student(30959,"kalyan",9.35)
print(getattr(st,'cgpa'))
setattr(st,'cgpa',9.51)
print(getattr(st,'cgpa'))
delattr(st,'id')
print(hasattr(st,'cgpa'))
print(hasattr(st,'id'))
2. _ _dic_ _ ():
--> It is a dictionary which contains the details about class name spaces.
3. _ _name __ ():
--> It contains the name of the class.
4. _ _ base _ _() :
5. _ _module _ _ :
--> It is used to access the module in which the class is defined.
Pycharm Installation :
--> https://www.jetbrains.com/pycharm/download
Python Modules :
--> Module is a file which consists of definitions and statements.
--> Module can define functions, classes and variables.
Ex :
def mul(a,b):
return a * b
def div(a,b):
return a /b
Ex : p65.py
import calc
print(calc.add(10,20)) --> 30
Syntax :
from module_name import specific
Ex : p66.py
from math import sqrt
print(math.sqrt(25)) --> 5
print(sqrt(25)) --> 5
Ex : p67.py
import calender
year = 2023
month = 2
print(calender.month(year,month))
1. datetime :
--> It is a module which consists of classes related to date and time.
Ex : p68.py
import datetime
a = datetime.datetime.now()
print(a)
print(a.year)
Ex : p69.py
import datetime
a = datetime.MINYEAR
print(a)
Ex : p70.py
#program to replace date using datetime module
import datetime
today = datetime.date.today()
a = today.replace(year=2003)
print(a)
2. math :
--> It is a module which consists of different mathematical operations.
Ex : p71.py
import math
a = max(10,20,30) --> 30
b = min(1,2,3,4) --> 1
print(a,b)
Ex : p72.py
import math
a = pow(2,2)
print(a)
Ex : p73.py
import math
a = -2
print(abs(a))
Ex :
from math import factorial
print(factorial(4)) --> 24
3. re :
--> It is amodule consisting of set of constraints used to find a string getting
matched or not.
Ex : p74.py
import re
a = "reddy venkat kalyan reddy"
b = re.findall("reddy",a)
print(b)
Ex : p75.py
import re
a = "reddy venkat kalyan reddy"
c = re.search("reddy",a)
print(c)
Ex : p76.py
import re
a = "reddy venkat kalyan"
b = re.split("\s",a)
print(b)
Ex : p77.py
import re
a = "reddy venkat kalyan reddy"
c = re.sub("\s","9",a)
print(c)
4. os :
--> It is a module which consists of all os commands.
--> The pre-defined methods of os module are :
Ex : p78.py:
import os
x = os.getcwd()
print(x)
Ex : p79.py :
import os
y = os.getcwd()
print(y)
x = os.chdir(r"C:\Users\DELL\Desktop\PFSD")
print(x)
Ex : p80.py :
import os
y = os.listdir()
print(y)
Ex : p81.py
import os
print(help(print()))
5. csv :
--> csv stands for comma separated values.
--> This module is used to deal with data which is in tabular form.
--> Some of the important operations on csv files are :
1. read() --> It is used to read the data from a csv file or used for
accessing the data .
2. write() --> It is used to write data into csv file or to store the data.
3. update() --> It is used to update the data in csv file.
4. delete() --> It is used to delete a data from a csv file.
Ex : p82.py
# program to demonstrate read() in csv
import csv
with open('ABC-ID.csv',newline='')as f:
reader = csv.reader(f)
for row in reader:
print(row)
Ex : p83.py
# program to demonstrate write() in csv
import csv
Ex : p84.py
# program to demonstrate update() in csv
import csv
Ex : p85.py
# program to demonstrate delete() in csv
import csv
7. random
--> It is a module used to generate random numbers.
Ex :
from random import random
for i in range(5):
print(random())
OUTPUT :
0.9535768927411208
0.5312710096244534
0.8737691983477731
0.5896799172452125
0.02116716297022092
8. platform:
--> The platform module lets you access the underlying platform's data,
i.e., hardware, operating system, and interpreter version information.
Ex :
from platform import machine
print(machine())
OUTPUT:
x86_64 --> machine() returns the processor type in a string format
Ex :
from platform import processor
print(processor())
OUTPUT:
x86 --> processor() returns the processor version.
Dt : 04/02/2023
Exception Handling in Python :
--> Exception is a python object which represents an error.
or
--> It is an event which occurs during the execution of the program which generally
disturbs the flow of execution of a program.
Types of errors :
1. Run Time Error
2. Compile Time Error
program phases :
--> compilation => HLL to MLL
--> execution => o/p
Ex :
def add(a,b)
print(a+b) --> compile time error or syntax error
1. try
2. except
3. else
4. finally
1. try :
--> block of code which contains an exception.
2. except
--> This block of code will executes when their is an exception.
3. else
--> This block of code will executes when their is no exception.
4. finally
--> This block of code always executes irrespective of whether their is an
exception or not.
Syntax :
try:
block of code to represent try block.
except Exception1:
block of code to represent except block.
except Exception2:
block of code to represent except block.
else :
block of code to represent else block.
finally :
block of code to represent finally block.
Ex : p89.py
#program to demonstrate exception handling
try:
a = int(input())
b = int(input())
c = a/b
except:
print("An Error Occured -- Zerodivision error")
else:
print("No error occured")
finally:
print("Successfully executed an example to demonstrate exception handling")
Ex : p90.py
#program to demonstrate exception handling
try:
j = 5.0
for i in range(1,1000):
j = j**i
print(j)
except:
print("An Error Occured -- overflow error")
else:
print("No error occured")
finally:
print("Successfully executed an example to demonstrate exception handling")
Note :
Types of Exceptions :
1. Exception
2. Arithmetic Error
3. EOF Error(End of the file)
4. Import Error
5. ZeroDivision Error
Dt : 11/02/23
pytest :
- >It is a testing framework, which is based on Python.
- >It is mainly used to write and executes testcases.
- >It helps you to write simple and scalable tetstcases for databases, API's and
UI.
- >Pytest is mainly used for API's.
- >It Works based on Unit Testing.
Advantages :
i. Open Source.
ii. Pytest can run multiple test in parallel, which can reduce the execution time.
iii. It is very easy to use, because of its simple syntax.
Installantion :
- >To work with, we need to install a module called pytest.
step-1 pip install pytest
Ex: test_91.py
def fn(x):
return x+1
def test_sample():
assert fn(4)==5
Ex:test_92.py
def fn(x):
return x+1
def test_sample():
assert fn(4)==5
def test_sasmple():
assert fn(5)==5
Ex: test_p93.py
def fn(x):
return x+1
def test_sample():
assert fn(4)==5}
assert fn(5)==5}
Note:
1. To run all the files in a folder ->pytest
2. To run a specific file ->pytest filename.py
3. To run a spec. file with details testcases->pytest filename.py -v
4. To run a spec from a file -> pytest filename::methodname
Marker:
-------
-Markers are used to set various features or attributes to the test fn's.
Syntax: @pytest.mark.markername
Ex: @pytest.mark.marker1
def test_sample():
assert fn(3)==6
Fixtures:
---------
-Fixtures are used to provide an input to testcase.
Syntax:- @pytest.fixtures
Ex: @pytest.fixtures
def test_sample():
assert fn(3)==6
Parameterized Test:
-------------------
-Calling a test fn for multiple no. of times by changing
parameter i/p.
Syn: @pytest.mark.parameterize
Dt : 14/02/23
Full Stack :
--> Front End Development :
** Flask
** Django
Flask :
--> Flask is a web application framework written in python.
--> Flask is considered as a microframework.
--> some of the popular web application are :
flask, django, pyramid, cherrypy
--> Flask was developed by Armin.
--> Flask is designed based on WSGI(Web Server Gateway Interface) toolkit and
jinga2 template engine.
--> Default port number = 5000
--> Url to access a flask application :
--> http.//127.0.0.1:5000
WSGI Toolkit :
--> WSGI is a Toolkit which is used to built python web application.
--> It acts as an interface between web server and web applcation.
Ginga2 :
--> It is a web template engine.
--> It combines a template with a certain data code to render a dynamic web pages.
Web Pages :
--> Static Web page
--> Dynamic Web page
#Create a Route
@app.route("/")
def sample():
return "Welcome To Flask"
if __name__ == "__main__":
app.run()
#dynamic routing
#template routing
#html
HTML
--> HTML stands for hyper text markup language.
--> HTML is used to create static webpages.
--> HTML was invented by a person called Tim Berners Lee & he is the one who
invented internet in 1991.
--> CSE started in 1981.
--> Hyper Text refers to linking of webpages together.
--> Markup Language refers to a document which tells you how to display a
structure.
Specifications Of HTML :
--> HTML 1.o
--> HTML 2.o
--> HTML 3.2
--> HTML 4.o
--> HTML 5(Latest version of HTML)
Adavantages Of HTML :
--> Open source.
--> Easy to understand.
--> User friendly.
--> TroubleShooting is easy.
--> Flexibility.
HTML Structure :
<html>
<head>
<title>Title</title>
</head>
<body>
--------
--------
</body>
</html>
HTML Tags :
--> Any word which is enclosed within a angular brackets is called as a HTML tag.
Ex : <head>
HTML Element :
--> HTML Elements and tags are often same but strictly speaking html element must
have start tag , content followed by closed tag.
Ex : <h1> Welcome</h1>
b. Paragraph :
--> <p>
Ex : <p>Ram is good Boy.
Kalyan is also good boy </p>
d. Break Tag :
--> <br>
Ex : <p>Ram is good Boy.<br>
Kalyan is also good boy </p>
f. Italic Tag :
--> <i>
Ex : <i>Ram is good Boy.<br>
Kalyan is also good boy </i>
g. UnderLine Tag :
--> <u>
Ex : <u>Ram is good Boy.<br>
Kalyan is also good boy </u>
h. Big Tag :
--> <big>
Ex : <big>Ram is good Boy.<br>
Kalyan is also good boy </big>
i. Small Tag :
--> <small>
Ex : <small>Ram is good Boy.<br>
Kalyan is also good boy </small>
j. Strike Tag:
--> <strike>
Ex : <strike>Ram is good Boy.<br>
Kalyan is also good boy </strike>
k. Delete Tag :
--> <del>
Ex : <del>Ram is good Boy.<br>
Kalyan is also good boy </del>
l. Mark Tag :
--> <mark>
Ex : <mark>Ram is good Boy.<br>
Kalyan is also good boy </mark>
m. Superscript Tag :
--> <sup>
Ex : <h1>Ram is good Boy.<sup>
Kalyan is also good boy </h1>
n. Subscript Tag :
--> <sub>
Ex : <h1>Ram is good Boy.<sub>
Kalyan is also good boy </h1>
o. Horizontal Ruler :
--> <hr>
Ex : <h1>Ram is good Boy.<sub>
Kalyan is also good boy </h1>
<hr>
p. Marquee Tag :
--> <marquee>
Ex : <marquee>Ram is good Boy.<sub>
Kalyan is also good boy </marquee>
NOTE :
Attribute :
--> Attributes are used to display the property of a tag.
--> Attribute will have name and value.
Syntax :
<tag attributename = attributevalue> content </tag>
Ex : <marquee behaviour = "alternate">Ram is good Boy.<sub>
Kalyan is also good boy </marquee>
2. Anchor Tags :
--> <a> </a>
Ex : <a href = "www.google.com">Google</a>
3. Image Tag :
--> <img>
Ex : <img src = "C:\Users\DELL\Downloads\profile.jpg">
4. Audio Tag :
--> <audio>
Ex : <audio controls>
<source src = "audio path.mp3">
</audio>
5. Video Tag :
--> <video>
Ex : <video controls>
<source src = "video path.mp4">
</video>
6. List Tag :
--> List is a c0llection of items.
1. Unorder List :
Ex :
<ul type = "square">
<li> CSE</li>
<li> ECSE</li>
<li> AIDS</li>
</ul>
2. Ordered List :
Ex :
<ol type = "A" start = "24">
<li> CSE</li>
<li> ECSE</li>
<li> AIDS</li>
</ol>
3. Descriptive List or Definition List :
Ex :
<dl>
<dt>CSE</dt>
<dd> Faculty</dd>
<dd>Students</dd>
</dl>
7. Table Tag :
--><table>
Ex :
<table border = 2>
<caption><b>Student Data</b></caption>
<tr bgcolor = "red"align = center>
<th> ID Num</th>
<th> Name</th>
<th> CGPA</th>
</tr>
<tr align = "center">
<td>001</td>
<td> kalyan</td>
<td> 9.35</td>
</tr>
<tr align = "center">
<td>002</td>
<td> sai</td>
<td> 9.1</td>
</tr>
</table>
8. HTML Forms :
--> Forms are used to collect the data.
--> Data can be coolected using form elements.
--> The different form elements are :
a. input
i. text
ii. radio
iii. button
iv. check box
b. selection
c. text area
--> Denoted by <form>
a. input :
i. Text :
Ex :
<form>
First Name :<input type = "text" name = "fn"><br>
Second Name :<input type = "text" name = "sn"><br>
Mobile Number :<input type = "number" name = "no"><br>
Password :<input type = "password" name = "pwd"><br>
Date Of Birth :<input type = "date" name = "dob"><br>
</form>
ii. Radio :
Ex :
<form>
First Name :<input type = "text" name = "fn"><br>
Second Name :<input type = "text" name = "sn"><br>
Mobile Number :<input type = "number" name = "no"><br>
Password :<input type = "password" name = "pwd"><br>
Date Of Birth :<input type = "date" name = "dob"><br>
Gender :<input type = "radio" name = "r">Male
<input type = "radio" name = "r">Female
</form>
iii. Button :
Ex :
<form>
First Name :<input type = "text" name = "fn"><br>
Second Name :<input type = "text" name = "sn"><br>
Mobile Number :<input type = "number" name = "no"><br>
Password :<input type = "password" name = "pwd"><br>
Date Of Birth :<input type = "date" name = "dob"><br>
Gender :
<input type = "radio" name = "r">Male
<input type = "radio" name = "r">Female
<input type = "button" value = "Register">
<input type = "reset" value = "clear">
<input type = "submit" value = "click here">
</form>
b. selection :
Ex :
<form>
First Name :<input type = "text" name = "fn"><br>
Second Name :<input type = "text" name = "sn"><br>
Mobile Number :<input type = "number" name = "no"><br>
Password :<input type = "password" name = "pwd"><br>
Date Of Birth :<input type = "date" name = "dob"><br>
Gender :
<input type = "radio" name = "r">Male
<input type = "radio" name = "r">Female
Branch :
<select>
<option> None </option>
<option> CSE</option>
<option> EEE</option><br>
Fav Course :
<input type = "chack box" name = "da" value = "daa">DAA
<input type = "chack box" name = "se" value = "Se">SE
<input type = "button" value = "Register">
<input type = "reset" value = "clear">
<input type = "submit" value = "click here">
</form>
c. Text Area :
Ex :
<form>
First Name :<input type = "text" name = "fn"><br>
Second Name :<input type = "text" name = "sn"><br>
Mobile Number :<input type = "number" name = "no"><br>
Password :<input type = "password" name = "pwd"><br>
Date Of Birth :<input type = "date" name = "dob"><br>
Gender :
<input type = "radio" name = "r">Male
<input type = "radio" name = "r">Female
Branch :
<select>
<option> None </option>
<option> CSE</option>
<option> EEE</option><br>
Fav Course :
<input type = "chack box" name = "da" value = "daa">DAA
<input type = "chack box" name = "se" value = "Se">SE
Address : <br>
<textarea>
</textarea><br>
<br>
<input type = "button" value = "Register">
<input type = "reset" value = "clear">
<input type = "submit" value = "click here">
</form>
NOTE :
Form Attributes:
--> Attributes associated to a form is called is form attribute.
--> The form attributes are :
1. action
2. method
1. action :
--> Ex :
<form action = "index.html">
First Name :<input type = "text" name = "fn"><br>
Second Name :<input type = "text" name = "sn"><br>
<input type = "button" value = "Register">
</form>
2. method :
--> Ex :
<form action = "index.html" method = GET>
First Name :<input type = "text" name = "fn"><br>
Second Name :<input type = "text" name = "sn"><br>
<input type = "button" value = "Register">
</form>
Assignment :
CSS --> implemented in three ways
1. Inline
2. Internal
3. External
Dt : 25/02/23
Dt : 28/02/23
Redirect :
# redirect
@app.route("/route/template2/<role>")
def sample4(role):
if role == "guest":
return redirect(url_for("sample2"))
else:
return redirect(url_for("sample3",name = role))
Template Rendering:
@app.route("/temp/inherit")
def sample6():
lst = ["kalyan", 9.35, "IInd Year"]
return render_template('home.html', lst=lst)
#index4.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{% block content %}
{% endblock content %}
</body>
</html>
#home.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{% extends 'index4.html' %}
{%block content %}
{% for i in lst %}
<li>{{i}}</li>
{%endfor %}
{%endblock content %}
</body>
</html>
#iflag.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{% if value %}
{{value}}
{% endif %}
</body>
</html>
Form Example :
MongoDB :
Introduction to NOSQL :
--> NOSQL stands for 'not only structured query language'.
--> NOSQL databases are non-relational databases whereas sql databses are
relational databases.
--> Note :
Relational Database :
--> It is a kind of database that stores and provide data related to each
other.
--> The system which maintains relational database is referred to as RDBMS.
--> SQL -> relational -> tables
--> NOSQL -> non relational -> no tables
--> NOSQL is specially designed for large set of data(Big Data).
Big Data:
--> It can be defined using three characteristics.
--> velocity(speed at which data arrives to a database).
--> volume(size of data).
--> varieties of data(comments,imgs,videos,etc).
--> All these three together defines bigdata.
NOSQL :
--> Data is not stored in tables.
--> NOSQL is unstructured data.
--> NOSQL is used for larger data.
--> Scalability is not limited.
Introduction to MongoDB :
--> MONGODB is a Document based database.
--> MONGODB is a open source with high performance.
--> MONGODB is highly scalable.
--> MONGODB stores data in the form of JSON format.
--> It was developed by a company called 10gen.
Note :
--> Document based database will consists of collections, documents, fields,etc.
Features of MONGODB :
--> It doesn't require any relational data model.
--> It doesn't require any schema.
--> It doesn't require any table.
--> It doesn't require any query language.
--> It doesn't require any Normalization.
--> It completely works based on aggregation.
ORACLE
--> stores data in the form of tables.
--> unit of data will be stored in record.
--> schema is fixed.
--> CRUD operations are performed on table.
--> Primary key uniquely identifies a record.
--> It is sql database.
Dt : 11/03/23
MongoDB Topics :
--> Introduction to Nosql.
--> Introduction to MongoDB.
--> MongoDB environment setup.
--> Basics of MongoDB.
--> Create Collections and Documents.
--> CRUD Operatins.
--> Find and pretty functions.
--> Summary.
Basics of MongoDB :
--> MongoDB is a document based database.
--> MongoDB is a leading nosql database.
--> MongoDB is written in c++.
Advantages of MongoDB :
--> Schema less.
--> Fast performance(100 times faster than sql).
--> Easy to scale.
Applications of MongoDB :
--> Dealing with Big Data.
--> Data hub.
--> social and mobile networking sites.
--> Data management.
--> content management.
MongoDB Datatypes:
1. String
2. Boolean.
3. Integer
4. Double
5. Arrays
6. Min
7. Max
8. Null
9. Object
10. Symbol
Database Creation :
--> Syntax :
use db_name
Ex :
use klu-v
Note :
--> If the database name does not exist it creates a database and switches to that
database.
--> If the name is existing it will simply switch to that database.
Drop Database :
--> Syn :
db.dropDatabase()
ex :
use klu-v
db.dropDatabase()
Create Collection :
Syntax :
db.createCollection("name")
Ex :
db.createCollection("CSe")
Drop Collection :
Syntax :
db.COLLECTION_NAME.drop()
Ex :
db.CSe.drop()
Documents :
--> Documents are used to store the data in mongodb database.
Syntax :
db.collection_name.insert()
Ex1 :
db.CSe.insert({"course":"PFSD"})
Ex2 :
db.CSe.insert({"course":"MSWD","credits":5})
Ex3:
db.CSe.insertMany([{"course":"ATFL","credits":3},
{"course":"AIDS","Credits":5},{"course":"se","credits":3,"Details":
{"Faculty":"madhu sir","mode":"self"}}])
CRUD Operations :
--> The different CRUD operations performed on a document are
1. create
2. retrive
3. update
4. delete
1. create :
--> Insert a single and multiple documents.
2. retrive :
--> Used to retrive data.
Ex : db.CSe.find()
Ex : db.CSe.find({"course":"ATFL"})
3. update:
--> Syntax :
db.collection_name.update({selection_critera},{update_criteria})
Ex :
db.CSe.update({"course":"ATFL"},{"credits",4})
4. delete :
a. to remove all collections:
Syn : db.collection_name.remove({})
Ex : db.CSe.remove({})
Ex : db.CSe.remove({"course":"PFSD"},1)
find:
a. to retrive all documents:
--> This is used to retrive a document.
Ex :
db.CSe.find()
pretty:
--> This is used to display the documents in more structurized format.
Syn :
db.collection_name.find().pretty()
Ex:
db.CSe.find().pretty()
MongoDb compass :
Django Framework :
Web Applictaion :
--> FE, BE, Connectivity
Local Applaication:
--> Runs on a client/usrer machine.
Global Application:
--> Runs on a web server.
Ex : AWS
History :
--> It was developed by Lawerence Journal orl in 2003.
Features of Django :
--> Rapid Development
--> Open source
--> very secured
--> Fully loaded
--> scalable
-pages
_ _init_ _.py
admin.py
apps.py
tests.py
views.py
models.py
urls.py(create)
Changes Recommended
-----------------------------------
1. settings.py :
=> ALLOWED_HOSTS = ['*']
2.settings.py :
=> INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'pages',
]
--> add app name 'pages' to installed_apps
3.project1/urls.py :
=> urlpatterns = [
path('admin/', admin.site.urls),
path(' ',include('pages.urls'))
]
Normal Routing
------------------------
Views and HttpResponse :
views.py :
from django.shortcuts import render,HttpRespnse
def sample1(request):
return HttpResponse("Welcome to django")
urls.py :
from django.urls import path,include
from .views import sample1
urlpatterns=[
path(' ',sample1,name= 'NR')
]
Dynamic routing
-------------------------
def sample2(request,name):
return HttpResponse(name)
def sample3(request,name):
return render(request,'index1.html',{'name':name})
def sample6(request,name):
lst = {'anb','ksk','ssaj'}
return render(request,'index2.html',{'lst':lst})
Redirect :
views.py
----------
def sample7(request):
return redirect('TR')
urls.py
-----------
path('redirect/',sample7,name='RD'),
Template Inheritance :
views.py
----------
def sample8(request):
return render(request,"inheritance.html")
urls.py
--------
path('template4',sample8,name='TI'),
inheritance.html
--------------------
{% extends 'base.html' %}
<body>
{% block main %}
<h1> this is gettirn inherited </h1>
{% endblock %}
</body>
base.html
-------------
<body>
{% block main %}
{% end block %}
<h2> This is an example of template inheritance </h2>
</body>
Static content :
project1 --> new directory --> static --> new directory ---> images
views.py
----------
def sample9(request):
return render(request,"index4.html")
index4.html
---------------
<!DOC...... >
{% load static %}
<body>
<img src = "{static '/images/abc.png' }" alternate = "Image not found">
</body>
urls.py
-------
path('static/',sample9,name = "SC")
Settings.py
-------------
change settings :
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static")
]
CRUD Operations(DB) :
The different operations which can be performed on a database are :
1. Create and insert
2. Retrive
3. Update
4. Delete
Checking Authentication :
from django contrib.auth import authenticate
Admin panel :
--> open terminal --> python manage.py makemigrations
--> python manage.py migrate
--> pyhton manage.py createsupersuser
UserName : ________________
Email : ___________________
Password : _________________
Re enter Password : ______________
SuperUser created Successfully
urls.py
------
path('register/',registration,name="reg")
Writing Models
--------------------
--> Models.py is nothing but defining a schema for your database.
--> A model is a single, definitive source of information about your data.
--> Each model is python class which contains subclasses to.
--> Each attribute of a model represents a database field.
models.py :
from django.db import models
class Student(models.Model):
fn = models.CharField(max_length = 40)
ln = models.CharField(max_length = 40)
class Vehicle(models.Model):
regno = models.CharField(max_length = 40)
model = models.DateField()
NOTE
--------
The fn and ln of Student model are called fields.
Each field is specified as class attribute and each attribute maps to a database
column.
https://docs.djangooproject.com/en/4.1/topics/db/models
-----------------------------------------------------------------------------------
-----------------------------------------------------------------
Django Database Connectivity :
-> Before creating a superuser make user to implement the above commands in
terminal.
1. create a superuser :
--> python manage.py createsuperuser
def __str__(self):
return self.prod_name --> to print the product name in db while
viewing
-----------------------------------------------------------------------------------
-----------------------------------------------------------------
Changes required :
1. project--> settings.py :
--> change the old app name to new app name in 'INSTALLED_APPS' as new class name
in app--> apps.py
--> app_name.apps.class_name(syntax to new app)
2. project--> settings.py :
urlpatterns = [
.................................................
.................................................
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
-----------------------------------------------------------------------------------
-----------------------------------------------------------------
To deal with the database using shell in terminal :