Python
Python
HISTORY :
Python was started in the December 1989 by Guido Van Rossum at CWI in
[Link] van Rossum was also reading the published scripts from
“Monty python’s flying circus”, a BBC comedy series from the 1970s.
PYTHON APPLICATION:
Keywords:
Keywords in Python are reserved words that can not be used as a variable
name, function name, or any other [Link] number of
keyword 35.
import keyword
print([Link])
Variables:
Variables are containers for storing data values.
A variable name must start with a letter or the underscore character
A variable name cannot start with a number
X=3 #x is int
X=”python” #x is str
Comments:
Comments stars with a #.
Multiline Comment: ”””python”””
Indentation
Indentation refers to the spaces at the beginning of a code line.
Where in other programming languages the indentation in code is for
readability only, the indentation in Python is very important.
Python uses indentation to indicate a block of code.
Ex: if 5 > 2:
print("Five is greater than two")
Many Values to Multiple Variables
Ex: x = y = z = "Orange"
print(x)
print(y)
print(z)
x = 20 int
x = 20.5 float
x = 1j complex
x = range(6) range
x = True bool
x = b"Hello" bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview
x = None NoneType
EX: x=5
y=”python”
print(type(x)) # <class 'int'>
print(type(y)) #<class ‘str’>
PYHTON NUMBERS:
int
float
complex
INT:
EX:
x=1
y = 35656222554887711
z = -3255522
print(type(x)) #<class ‘int’>
print(type(y)) #<class ‘int’>
print(type(z)) #<class ‘int’>
FLOAT:
EX:
x = 1.10
y = 1.0
z = -35.59
print(type(x)) #<class=’float’>
print(type(z)) #<class=’float’>
COMPLEX:
EX:
x = 3+5j
y = 5j
z = -5j
print(type(x)) #<class=’complex’>
TYPE CONVERSTION:
You can convert from one type to another with the int(), float(), and complex()
methods.
EX
#convert from int to float:
x = float(1)
#convert from float to int:
y = int(2.8)
#convert from int to complex:
z = complex(1)
print(x)
print(y)
print(z)
print(type(x))
print(type(y))
print(type(z))
NOTE: You cannot convert complex numbers into another number type.
PYTHON STRING:
Strings in python are surrounded by either single quotation marks, or double
quotation marks.
SLICING STRING:
b = "Hello, World!"
print(b[2:5]) #llo
print(b[2:]) #llo, World!
print(b[-5:-2]) #orl
Note: The first character has index 0.
MODIFY STRING:
Python has a set of built-in methods that you can use on strings.
EX:
a = "Hello, World!"
print([Link]()) #HELLO,WORLD!
print([Link]()) #hello, world!
a = "Hello, World!"
b = [Link](",")
print(b) #[‘Hello’ , ‘World’]
STRING CONCATENATION:
To concatenate, or combine, two strings you can use the + operator.
EXAMPLE:
a = "Hello"
b = "World"
c = a + b
print(c)
String Methods:
a="python language"
b=[Link]()
print(b)
a="PYTHON language"
b=[Link]()
print(b)
a="python language"
b=[Link]()
print(b)
a="python language"
b=[Link]()
print(b)
b=[Link](50)
print(b)
a="py is a py in py"
b=[Link]("py")
print(b)
a="python language"
b=[Link]('e')
print(b)
b=[Link]("lang")
print(b)
a=("python","language")
b="*".join(a)
print(b)
a="python language"
b=[Link]("python","java")
print(b)
a=("python language")
b=[Link]()
print(b)
a="python language"
b=[Link]()
print(b)
b=[Link]("p")
print(b)
Output:
Python language
python language
False
True
python language
3
True
7
python*language
java language
['python', 'language']
Python Language
True
age = 36
txt = "My name is John, and I am {}"
print([Link](age))
ANOTHER EXAMPLE:
quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print([Link](quantity, itemno, price))
Output:
EXAMPLE:
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
ARITHMETIC OPERATOR:
OPERATOR OPERATION
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo
** Exponentiation
// Floor Division
EXAMPLE:
ASSINGMENT OPERATOR:
EXAMPLE:
a=a+10 a+=10
a=a-10 a-=10
a=a*10 a*=10
a=a/10 a/=10
COMPARISION OPERATOR:
x=int(input(“Enter x value”))
y=int(input(“Enter y value”))
print(x==y)
print(x!=y)
print(x<y)
print(x<=y)
print(x>y)
print(x>=y)
LOGICAL OPERATOR:
Logical operators are used to check whether an expression is true or false.
EX:
x=int(input(“Enter x value”))
y=int(input(“Enter y value”))
print(x>=y and x>y)
print(x==y or x<y)
Identity operators are used to compare the objects, not if they are equal, but
if they are actually the same object, with the same memory location.
OPERATOR DESCREPTION
is Returns True if both variables are the
same object
is not Returns True if both variables are not
the same object
EX:
x = ["apple", "banana"]
y = ["apple", "banana"]
z=x
print(x is y) #false
print(x is z) #true
print(x==y) #true
print(x is not y) #true
x = ["apple", "banana"]
print("banana" in x) #true
BITWISE OPERATOR:
OPERATOR DESCRIPTION
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
~ Bitwise NOT
<< Shift left
>> Shift right
EX:
IF STATEMENT:
EX:
a = int(input(“Enter a value”))
b = int(input(“Enter b value”))
if b > a:
print("b is greater than a")
print(“Hello”)
IF….ELSE STATEMENT:
This statement is check with two conditions. If the condition is true the set of
statement is executed. Otherwise another set of statement is executed.
Syntax:
if(contidion):
statement
else:
statement
EX:
a =int(input(“Enter a value”))
b = int(input(“Enter b value”))
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
Exercise:
IF…ELIF…ELSE STATEMENT:
if condition:
statements
elif condition:
statements
elif condition:
statements
else:
statements
EX:
a = int(input(“Enter a value”))
b = int(input(“Enter b value”))
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
Exercise:
a=int(input("Enter a value"))
b=int(input("Enter b value"))
c=int(input("Enter c value"))
if a>b:
if a>c:
print("A is big")
else:
print("C is big")
else:
if c>b:
print("C is big")
else:
print("B is big")
EX:
a = int(input(“Enter a value”))
b = int(input(“Enter b value”))
c = int(input(“Enter c value”))
if a > b and c > a:
print("Both conditions are True")
else:
print(“Both conditions are false”)
The not keyword is a logical operator, and is used to reverse the result of the
conditional statement.
EX:
a = int(input(“Enter a value”))
b = int(input(“Enter b value”))
if not a > b:
print("a is NOT greater than b")
else:
print(“a is greater than b”)
PASS STATEMENT:
a = 33
b = 200
if b > a:
pass
PYTHON LOOP:
while loop
for loop
WHILE LOOP:
i=1
while i < 6:
print(i)
i += 1
Exercise
1. write a program using while loop in
12+22+32+................+n2
1+3+5+.............+n
1+5+10+……..+n
2. write a program using while loop in
Sum of digits
Reverse the digits
Armstrong no
Palindrome no
BREAK STATEMENT:
The break statement we can stop the loop even if the while condition is true.
EXAMPLE:
i=1
while i < 6:
print(i)
if i == 3:
break
i += 1
CONTINUE STATEMENT:
the continue statement we can skip the current iteration, and continue with
the next.
EXAMPLE:
i=0
while i < 6:
i += 1
if i == 3:
continue
print(i)
ELSE STATEMENT:
The else statement we can run a block of code once when the condition no
longer is true.
EX:
i=1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")
FOR LOOP:
A for loop is used for iterating over a sequence. the for loop we can execute
a set of statements, once for each item in a list, tuple, set etc.
EX:
for x in fruits:
print(x)
for x in "banana":
print(x)
RANGE FUNCTION:
EX:
i=1
n=int(input("Enter the number?”))
for i in range(0,10):
print(i,end = ' ')
Ex:
sum=0
for i in range(2,10,2):
sum=sum+i
print(sum)
NESTED FOR LOOP:
A nested loop is a loop inside a [Link] "inner loop" will be executed one
time for each iteration of the "outer loop"
EX:
n = int(input("Enter the number of rows you want to print?"))
i, j=0,0
for i in range(0,n):
print()
for j in range(0,i+1):
print("*",end="")
ELSE STATEMENT:
The else keyword in a for loop specifies a block of code to be executed when
the loop is finished.
EX:
for x in range(6):
print(x)
else:
print("Finally finished!")
BREAK STATEMENT:
The break statement we can stop the loop before it has looped through all the
items.
Ex:
str = "python"
for i in str:
if i == 'o':
break
print(i)
CONTINUE STATEMENT:
The continue statement we can stop the current iteration of the loop, and
continue with the next:
EX:
PASS STATEMENT:
For loops cannot be empty, but if you for some reason have a for loop with
no content, put in the pass statement to avoid getting an error.
EX:
n=[1,2,3,-4,-5,6,-7,-8,9]
for i in n:
if i>0:
pass
else:
print(i)
PYTHON LIST:
EXAMPLE:
print(L1) #[‘John’,102,’USA’]
print(L2) #[1,2,3,4,5,6]
print(L3) #[1,’Ryan’]
list=[10,20,30,40,50]
print(‘using while loop’)
i=0
while i<len(list):
print(list[i])
i+=1
print(‘using for loop’)
for i in list:
print(i)
USING range() FUNCTION:
The elements of the list can be accessed by using the slice operator [].
Ex:
[Link](9)
print(lst) #[1,2,3,4,9]
list[1]=8
print(lst) #[1,8,3,4,9]
list[1:3]=10,11
print(lst) #[1,10,11,4,9]
[Link](11)
print(lst) #[1,4,9]
Iteration The for loop is used to iterate over the for i in l1:
list elements. print(i)
Output 1 2 3 4
EX:
l =[]
n = int(input("Enter the number of elements in the list"))
for i in range(0,n):
[Link](input("E
nter the item?"))
print("printing the list items ")
for i in l:
print(i, end = " ")
Output:
Enter the number of elements in the list 5
Enter the item?1
Enter the item?2
Enter the item?3
Enter the item?4
Enter the item?5
printing the list items 12345
LIST COMPREHANSION:
List comprehension offers a shorter syntax when you want to create a new
list based on the values of an existing list.
EX:
SORT LIST:
List objects have a sort() method that will sort the list alphanumerically,
ascending, by default.
[Link]()
print(list)
list1=[2,3,4,1,5]
[Link]()
print(list1)
COPY LIST:
copy() method copies the list and returns the copied list
Ex:
a = [6,8,2,4]
b =[Link]()
print("Original list:",a)
print("Copy list:",b)
JOIN LIST:
Joining two list.
EX:
reverse() METHOD:
PYTHON TUPLE:
Accessing the elements from a tuple can be done using indexing or slicing.
EXAMPLE:
t=(20,30,50,40,60,70)
print(t[0]) #20
print(t[-1]) #70
print(t[-6]) #20
print(t[:]) #(20,30,50,40,60,70)
print(t[1:4]) #(30,50,40)
print(t[::2]) #(20,50,60)
print(t[::-2]) #(70,40,30)
print(t[-4:-1]) #(50,40,60)
UPDATE TUPLE:
Tuples are unchangeable, meaning that you cannot change, add, or remove
items once the tuple is created. So you can change the list than we will change the
items.
EXAMPLE:
UNPACKED TUPLE:
EX:
You can loop through the tuple items by using a for loop.
EX:
You can also loop through the tuple items by referring to their index
[Link] the range() and len() functions .
EXAMPLE:
EX:
Sets are used to store multiple items in a single [Link] items are
unordered,unchanged and do not allow duplicate values.
Set items are unordered.
EX:
EX:
ADD SETS:
To add items from another set into the current set, use the update() method.
EX:
EX:
JOIN SET:
EX:
# empty dictionary
my_dict = {}
# dictionary with integer keys
my_dict = {1: “apple”, 2: “ball”}
EX:
x={1:"C",2:"C++",3:"Java",4:"Python"}
print(x)
y=x[2]
print(y)
z=[Link]()
print(z)
a=[Link]()
print(a)
x[2]="R"
print(x)
x={1:”C”,2:”C++”,3:”Java”,4:Python”}
[Link]({3:"java"})
print(x)
ADD ITEMS:
Adding an item to the dictionary is done by using a new index key and assigning
a value to it.
EX:
[Link]({"favcolor": "red"})
print(dict)
REMOVING ITEMS:
EXAMPLE:
dict={“name”:”Jack,”age”:23,”city”:”Madurai”,”favcolor”:”green”}
[Link](“city”)
print(dict) #{‘name’:’Jack’,’age’:23,’favcolor’:’green’}
[Link]()
print(dict) #{‘name’:’Jack’,’age’:23}
LOOP DICTIONARY:
EX:
PYTHON FUCNTION:
EXAMPLE:
def my_function(x):
return 5 * x
print(my_function(3)) #15
print(my_function(5)) #25
print(my_function(9)) #45
LAMDA FUNCTION:
A lambda function can take any number of arguments, but can only have one
expression.
EX:
x = lambda a: a + 10
print(x(5)) #15
x = lambda a, b: a * b
print(x(5, 6)) #30
PYTHON EXCEPTION HANDLING:
The try block lets you test a block of code for errors.
The else block lets you execute code when there is no error.
The finally block lets you execute code, regardless of the result of
the try-and except blocks.
Common Exceptions
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c=a/b
print(c)
except Exception as e:
print(e)
else:
print("Hi I am else block")
try:
print(x)
except:
print("Something went wrong")
finally:
print("The 'try except' is finished")
Name Error:
try:
n="sathya"
print(age)
except NameError as e:
print(e)
Value Error:
try:
n=int(input("enter no:"))
except ValueError as e:
print(e)
except NameError as e:
print(e)
Index Error:
try:
l=[10,20,30,40]
print(l[6])
except IndexError as e:
print(e)
Key Error:
try:
d={'name':'python','lang":"high"}
print(d['city'])
except KeyError :
print("city not in dictionary")
RAISE AN EXCEPTION:
EX:
x = "hello"
if not type(x) is int:
raise TypeError("Only integers are allowed")
PYTHON FILE:
Advantages of file:
• Once the data is stored in a file, the same data can be shared by various
programs.
FILE HANDLING:
The key function for working with files in Python is the open() function.
The open() function takes two parameters; filename, and mode.
MODE MEANING
“r” – read Default value. Opens a file for reading,
error if the file does not exis
“w” – write Opens a file for writing, creates the file
if it does not exist
CREATING A FILE:
• The new file can be created by using one of the following access modes with
the function open().
• x: it creates a new file with the specified name. It causes an error a file
exists with the same name.
Ex:
fileptr = open("[Link]","x")
if fileptr:
print("File created successfully")
• a: It will append the existing file. The file pointer is at the end of the file. It
creates a new file if no file exists.
• w: It will overwrite the file if any file exists. The file pointer is at the
beginning of the file.
EX:
f=open('[Link]','w')
s=input('enter text:')
[Link](s)
[Link]()
Output: enter text : hai hello
EX:
f=open('[Link]',‘r')
s=[Link]()
print(s)
print(s1)
[Link]()
Output:
hai hello
hai
OOPS CONCEPT
CLASS:
Class is a blueprint for an object.
Class is a Logical Entity.
Syntax:
class class_name:
variables
methods
OBJECT:
Object is a physical entity, that works on class data.
Note:
Each object has a distinct role (or) responsibility.
Object creates space on memory as per class member.
Syntax:
object_name=class_name()
Ex:
class A:
a=10
def fun(self):
print("this is fun")
obj=A()
[Link]()
self:
self is keyword or [Link] class function access the [Link] used to pass the
values from another class [Link] function are automatic using self keyword.
class A:
def fun(self,a,b):
self.a=a
self.b=b
def fun1(self):
c=self.a+self.b
print(c)
obj=A()
[Link](10,2)
obj.fun1()
Package:
Python modules may contain several classes, functions, variables, etc. whereas
Python packages contain several modules. In simpler terms, Package in Python is a
folder that contains various modules as files.
Creating Package
class Factorial:
def
fact(self,num):
f=1
for i in
range(1,num+1):
f*=i
return f
import package:
from Factorial
import*
num=int(input("Enter the value:"))
obj=Factorial()
r=[Link](num)
print(r)
INHERITANCE:
When we define a class that inherits all the properties of other class
called Inheritance.
Syntax:
class Father:
properties
class Daughter(Father):
properties
Types:
Single Inheritance
Multiple Inheritance
Multi-level Inheritance
Hierachical Inheritance
Hybrid Inheritance
Single Inheritance:
Single Inheritance is nothing but which contain one parent class and
only one child class.
Syntax:
class A:
properties
class B(A):
properties
EX:
class A:
def fun(self):
print("This is function")
class B(A):
def fun1(self):
print("Hai")
obj=B()
[Link]()
obj.fun1()
Multiple Inheritance:
Class which contain more than one Base class and only one derived
class is called Multiple Inheritance.
Syntax:
class A:
properties
class B:
properties
class C(A,B):
properties
Ex:
class A:
def value(self):
a=int(input("Enter the value:"))
self.a=a
class B:
def value1(self,pi):
[Link]=pi
class area(A,B):
def value2(self):
area=[Link]*self.a*self.a
print("Radius of circle:",area)
a=area()
[Link]()
a.value1(3.14)
a.value2()
Multi-Level Inheritance:
In this inheritance we have one parent class and multiple child class.
Syntax:
class A:
properties
class B(A):
properties
class C(B):
properties
EX:
class myclass:
def get(self):
a=int(input("Enter a value:"))
b=int(input("Enter b value:"))
self.a=a
self.b=b
class process(myclass):
def swap(self):
self.t=self.a
self.a=self.b
self.b=self.t
class myswap(process):
def display(self):
print("After swapping")
print("a=",self.a)
print("b=",self.b)
s=myswap()
[Link]()
[Link]()
[Link]()
Hierachical Inheritance:
This inheritance which contain only one parent class and multiple
child class but each child classes can access parent class properties.
Syntax:
class A:
properties
class B(A):
properties
class C(A):
properties
Ex:
class A:
def getx(self):
x=int(input("Enter the number:"))
self.x=x
def showx(self):
print("X=",self.x)
class B(A):
def gety(self):
self.x
y=int(input("Enter the number:"))
self.y=y
def showy(self):
print("Y=",self.y)
class C(A):
def getz(self):
self.x
z=int(input("Enter the number:"))
self.z=z
def showz(self):
print("Z=",self.z)
p=B()
g=C()
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
Hybrid Inheritance:
ENCAPSULATION:
Using OOP in python ,we can restricted access to methods and
[Link] does not have any private keywords. Unlike java, This prevents data
from direct modification which is called Encapsulation.
EX:
class Car:
def __init__(self):
self.__maxprice=900000
def sell(self):
print("Selling price:",format(self.__maxprice))
def setmaxprice(self,price):
self.__maxprice=price
c=Car()
[Link]()
c.__maxprice =1000000
[Link]()
[Link](1000000)
[Link]()
ABSTRACTION:
Method Overloading:
Same function name different arguments
EX1:
class A:
def fun(self,a=None,b=None,c=None):
if a!=None and b!=None and c!=None:
return a+b+c
elif a!=None and b!=None :
return a+b
else:
return a
obj=A()
print("Result=",[Link](10,20,30))
print("Result=",[Link](10,20))
EX 2:
class Myclass:
def func(self,*args): #*args=more than a values(parameter passing a fun)
sum=0
for i in args:
sum+=i
print("Sum:",sum)
obj=Myclass()
[Link](10)
[Link](1,5)
[Link](1,2,3)
Method Overriding
Same functi
class A :
def fun(self):
print("Java")
class B:
def fun(self):
print("Python")
obj=B()
[Link]()