Python
Python
---
high level prog language
1991
#include<stdio.h>
void main
{
int a,b;
printf("hello world");
}
python 3.8
a=10
_ it is a private
__ strongly private
keywords
30+ keywords are avaialble
Data types
-------------
Int
float
boolean
str
bytes
complex
range
bytearray
list
tuple
set
dict
None
frozenset
substring
---------
4 methods
backward-- rfind(),rindex()
------------------------------
@author: Poorni
"""
#
#print("hello world")
#a=10
#b=30
#print("the sum",(a+b))
#print(type(a))
#a=3+5j
#print(type(a))
#a=True
#print(type(a))
#
#import keyword
#print(keyword.kwlist)
#a="""learning
#python
#is
#very
#simple"""
#
#print(type(a))
#a=[10,20,30,40]
#b=bytes(a)
#print(type(a))
#print(type(b))
#print(b[2])
#r=range(10)
#for i in r:
# print(i)
#r=range(10,20)
#for i in r:
# print(i)
#r=range(10,20,2)
#for i in r:
# print(i)
#a=100
#b=20
#print("a>b", a>b)
#a=10
#b=30
#print(a is b)
#s="helloworld"
#print(s[-4])
#[0] left to right
#[-1] right to left
#print(int(123.456))
#print(float(10))
#a=10
#b=20
#c=a<b
#print(c)
#print(type(a))
#s='poorna'
#s1="""learning
#python
#is
#very simple"""
#print(s1)
#x=[10,20,30,40]
#b=bytes(x)
#print(type(b))
#print(b)
#identity operator
#a=10
#b=10
#a==b content comaprison
#print(a is not b)
#b=20
#print("the sum is",(a+b))
#s="poornamathi"
#s='poornamathi'
#s="poorna mathi"
#for x in s:
# print(x)
#
#for x in range(11):
# if(x%2!=0):
# print(x)
#for x in range(10,0,-1):
# print(x)
#x=1
#while x<=10:
# print(x)
# x=x+1
#name=input("enter name")
#if name=="poorna":
# print("hello poorna")
#else:
# print("hello guest")
#String
#slicing technique []
#s='a'
#s="poornamathi"
#print(s[4])
#print(s[-4])
#print(s[20])
#print(s.find("python",0,10))
#print(s.index("poorna"))
#print(s.title())
#print(s.upper())
#print(s.lower())
#print(s.capitalize())
#print(s.isupper())
#print(s.islower())
#l=s.split()
#for x in l:
# print(x)
#print("poorna"+"mathi")-concatination operator
#len()
#s="poornamathi"
#print(len(s))
#membership operator "in/not in", to check string is the member of another string
#s="poornamathi"
#print('d' in s)
#print('a' in s)
#comparison .<,>,<=,>=,==,!=
#count
#s="abcabcbabcbacbac"
#print(s.count('a'))
#print(s.count('a',3,7))
#replace,s.replace(oldstring,newstring)
#isalnum(),islower(),isupper(),isspace(),isdigit()
#ch='a'
#print(type(ch))
#
#x=input("enter the value")
#if x=="poorna":
# print("HEllo poorna")
#elif x=="mathi":
# print("hello mathi")
#else:
# print("hello guest")
#s="poorna mathi"
#for x in s:
# print(x)
#
#s=input("enter string")
#i=0
#for x in s:
# print("the character present at",i,"index is",x)
# i=i+1
#
#for x in range(11):
# print(x)
#for x in range(21):
# if(x%2!=0):
# print(x)
#for x in range(10,0,-1):
# print(x)
#x=1
#while x<=10:
# print(x)
# x=x+1
#s="poorna"
#s='poorna'
#ch='a'
#type(ch)
# s="abcabcabcabcadda"
# print(s.count('a'))
# print(s.count('ab'))
# print(s.count('a',3,7))
#
#s="ababababababab"
#s1=s.replace("a","b")
#print(s1)
List
----------
represent a group of elements as a single entity
insertion order is preserved // 1 4 6 7
duplicate elements are allowed, differentiated by using index
hetegrogenous elements are allowed
list is dynamic, increase/decrese the size of the list
[]
mutable
@author: Poorni
"""
#empty list
#a=[]
#print(a)
#print(type(a))
#list=[1,2,3,4,5,'poorna',6.7,'mathi']
#print(list)
#l=list(range(0,10,2))
#print(l)
#
#n=[1,2,3,4,5,6,7,8,9]
#print(n[4::2])
#print(n[8:2:-2])
#print(n[4:100])
#
#n=[10,20,30,40]
#print(n)
#n[1]=70
#print(n)
#
#n=[0,1,2,3,4,5,6,7,8,9,10]
#i=0
#while i<len(n):
# print(n[i])
# i=i+1
#for n1 in n:
# print(n1)
#n=[0,1,2,3,4,5,6,7,8,9,10]
#print(len(n))
##
#count returns the no of occurences of items in the list
#n=[1,2,2,2,2,3,3,4]
#print(n.count(2))
#index returns the first occurence of the specif item
#
#n=[1,2,2,2,2,3,3,4]
#print(n.index(2))
#n=[1,2,3,4,5]
#n.insert(1,88)
#print(n)
#n=[1,2,3,4,5]
#print(n)
#n.insert(-5,6)
#n.insert(10,6)
#l1.extend(l2)
#
#l1=["a","b","c"]
#l2=["d","e","f"]
#l1.extend(l2)
#print(l1)
#print(l2)
#n=[10,20,30,10]
#n.remove(10)
#print(n)
#n=[10,20,30,10]
#n.remove(30)
#print(n)
#n=[10,20,30,40]
#print(n.pop())
#print(n.pop())
#print(n)
#n=[]
#print(n.pop())
#n=[10,20,30,40]
##print(n.pop(1))
#print(n.pop(10))
#
#append(),insert(),extend()- for increse the size of the list
#remove(),pop()- to decrese the size of the list
#n=[10,20,30,40]
#n.reverse()
#print(n)
#
#n=[70,40,50,40]
#n.sort()
#print(n)
#copy()
#x=[10,20,30,40]
#y=x.copy()
#y[1]=70
#print(x)
#print(y)
#n=[10,20,30,40]
#y=n*3
#print(y)
#n=[10,20,30,40,[50,60]]
#print(n)
#print(n[0])
#print(n[3])
#print(n[4][0])
#print(n[4][1])
#list comprehension
tuple
-------
immutable
tuple is read only version of list
insertion order is preserved
duplicate elements are allowed, differentiated by using index
hetegrogenous elements are allowed
()
@author: Poorni
"""
#Tuple datastructure
#t=10,20,30,40
#print(t)
#print(type(t))
#t=(10)
#print(type(t))
#t=(10,20,30,40)
#t[1]=90
#a=[startvalue:endvalue:skipvalue]
#t=10,20,30,40,50,60
#print(t[2:5])
#print(t[2:100])
#print(t[-1])
#list=[10,20,30,40]
#t=tuple(list)
#print(t)
#print(type(t))
#t1=(10,20,30)
#t2=(40,50,60)
#t3=t1+t2
##t3=t1*3
#print(t3)
#len()
#t1=(10,20,30,40)
#print(len(t1))
##
#t=(10,20,30,10,20)
#print(t.count(10))
#sorted(),max(),min(),index(),count
#tuple packing
#a=10
#b=20
#c=30
#d=40
#t=a,b,c,d
#print(t)
#print(type(t))
#tuple unpacking
#t=(10,20,30,40)
#a,b,c,d=t
#print("a=",a,"b=",b,"c=",c,"d=",d)
#Tuple comprehension
#
#t=(x**5 for x in range(1,6))
#print(type(t))
#for x in t:
# print(x)
set
----
unique elements
insertion order is not preserved but we can perform sorting
6 1 2 5 3 4
no indexing and slicing
heterogeneous elements
mutable
{ }
#s=set(any sequence)//list,tuple
#l=[10,20,30,40,50]
#s=set(l)
#print(s)
#print(type(s))
#s=set(range(5))
#print(s)
#t=(10,)
#print(type(t))
#s={}
#print(type(s))
#s=set()
#print(type(s))
#s={10,20,30,40}
#s.add(50)
#print(s)
#s={10,20,30}
#l=[11,21,31,41,51]
#s.update(l,range(5))
#print(s)
#s.add(8,9,10)
#s.update(70)
#s1=s.copy()
#print(s1)
#
#s={10,20,30,40}
#print(s.pop())
##print(s.pop)
#print(s)
#s.remove(30)
#s.discard(10)
#
#s.clear()
@author: Poorni
"""
#d={100:"poorna",200:"mathi",300:"maanav"}
##print(d[100])
#print(d[400])
#d={100:"poorna",200:"mathi",300:"maanav"}
#if 200 in d:
# print(d[200])
#update dict
#d[key]=value
#d={100:"poorna",200:"mathi",300:"maanav"}
#print(d)
#d[400]="prabu"
#d[100]="poo"
#print(d)
#
#d={100:"poorna",200:"mathi",300:"maanav"}
#del d[100]
#print(d)
#d.clear()
#pop(),keys(),values(),len()
#d={100:"poorna",200:"mathi",300:"maanav"}
#print(d.popitem())
#print(d)
#d={100:"poorna",200:"mathi",300:"maanav"}
#print(d.keys())
#for i in d.keys():
# print(i)
#d={100:"poorna",200:"mathi",300:"maanav"}
#print(d.values())
#for i in d.values():
# print(i)
functions
----------
4 types of argument
positional arg
keyword arg
default arg
variable length arg
@author: Poorni
"""
#def fun_name(parameters):
# """doc string"""
#...
#...
#return value
#def manadatory,return,paramters(optional)
#functions
#----------------
#def f1():
# print("Hello")
#f1()
#print(f1())
#if we are not wirting return statement
#then default value is none
#############################
#def add(x,y):
# return x+y
#result=add(10,20)
#print("The sum is",result)
#print("The sum is",add(100,200))
###############
##############
#positional arg,keyword arg,default arg,variable length
#arg
#keyword arguments
##we can pass argument values by keyword ie parameter name
#here the order of argments is not important,but no of arg
#should match
#def wish(name,msg):
# print("Hello",name,msg)
#wish(name="Poorna",msg="Good Morning")
#wish(msg="Good Morning",name="poorna")
########
#Default Arguments
#
#def wish(name="Guest"):
# print("Hello",name,"Good Morning")
#
#wish("poorna")
#wish()
#positional arg
#def sub(a,b):
# print(a-b)
# sub(100,200)
# sub(200,100)
####################
##############3
#We can mix variable length arguments with positional arguments
#
#def f1(n1,*s):
# print(n1)
# for s1 in s:
# print(s1)
#
#f1(10)
#f1(10,20,30,40)
#f1(10,"A",30,"B")
############################
#keyword arguments
#
#def display(**kwargs):
# for k,v in kwargs.items():
# print(k,"=",v)
#display(n1=10,n2=20,n3=30)
#display(rno=100,name="Poorna",marks=70,subject="Java")
##########################
#Global Variables
###############
#Local Variables
#Local variables are available only for the function in which we declared it.i.e
from outside
#of function we cannot access.
#def f1():
# a=10
# print(a) # valid
#
#def f2():
# print(a) #invalid
#
#f1()
#f2()
####################
#global keyword
#to declare global variable inside function
#to make global variable avaialbale to the function
#so that we can perform required modification
#
#a=10
#def f1():
# global a
# a=777
# # print(a)
#def f2():
# print(a)
#f1()
#f2()
#a=10
#def f1():
#
# a=777
# print(a)
# print(globals()['a'])
#
#print(a)
#f1()
#####################
#Recursive Functions
#
#def factorial(n):
# if n==0:
# result=1
# else:
# result=n*factorial(n-1)
# return result
#print("Factorial of 4 is :",factorial(4))
#print("Factorial of 5 is :",factorial(5))
#############################
######################
#s=lambda a,b:a+b
#print("The Sum of 10,20 is:",s(10,20))
#print("The Sum of 100,200 is:",s(100,200))
######################
#without lamda
#def isEven(x):
# if x%2==0:
# return True
# else:
# return False
#
#l=[0,5,10,15,20,25,30]
#l1=list(filter(isEven,l))
#print(l1) #[0,10,20,30]
###########################
#with lamda
###
#l=[0,5,10,15,20,25,30]
#l1=list(filter(lambda x:x%2==0,l))
#print(l1) #[0,10,20,30]
#l2=list(filter(lambda x:x%2!=0,l))
#print(l2)#[5,15,25]
#######################
#map unction is used to generate new element with the
#required modification
#wihtout lamda
#l=[1,2,3,4,5]
#def doubleIt(x):
# return 2*x
#l1=list(map(doubleIt,l))
#print(l) #[2, 4, 6, 8, 10]
#
##with lamda
#
#l=[1,2,3,4,5]
#l1=list(map(lambda x:2*x,l))
#print(l) #[2, 4, 6, 8, 10]
File operations
----------
text file- to store character data
binary fie- audio,videos...
f= open(filename,mode)
@author: Poorni
"""
"""r -open an existing file with read mode,file pointer is positoned at the
begining of the file
f.close()
properties
------------
name
mode
closed-boolean value file closed or not
readable()- boolan value file is readable or not
writable()
"""
##
#f=open("abc.txt",'w')
#print("File Name: ",f.name)
#print("File Mode: ",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)
#f=open("abcd.txt",'r')
#data=f.read(10)
#print(data)
#f.close()
#f=open("abcd.txt",'r')
#line1=f.readline()
#print(line1,end='')
#line2=f.readline()
#print(line2,end='')
#line3=f.readline()
#print(line3,end='')
#f.close()
#f=open("abcd.txt",'r')
#lines=f.readlines()
#for line in lines:
# print(line,end='')
#f.close()
#
#f=open("abcd.txt","r")
#print(f.read(3))
#print(f.readline())
#print(f.read(4))
#print("Remaining data")
#print(f.read())
#With statement
##
#with open("abcd.txt","w") as f:
# f.write("Welcome\n")
# f.write("to\n")
# f.write("Cognizant Digital Business\n")
#print("Is File Closed: ",f.closed)
#import os,sys
#fname=input("Enter File Name: ")
#if os.path.isfile(fname):
# print("File exists:",fname)
# f=open(fname,"r")
#else:
# print("File does not exist:",fname)
# sys.exit(0)
#print("The content of file is:")
#data=f.read()
#print(data)
#
#import os,sys
#fname=input("Enter File Name: ")
#if os.path.isfile(fname):
# print("File exists:",fname)
# f=open(fname,"r")
#else:
# print("File does not exist:",fname)
# sys.exit(0)
#lcount=wcount=ccount=0
#for line in f:
# lcount=lcount+1
# ccount=ccount+len(line)
# words=line.split()
# wcount=wcount+len(words)
#print("The number of Lines:",lcount)
#print("The number of Words:",wcount)
#print("The number of Characters:",ccount)
#import csv
#f=open("emp.csv",'r')
#r=csv.reader(f) #returns csv reader object
#data=list(r)
##print(data)
#for line in data:
# for word in line:
# print(word,"\t",end='')
# print()
# file zip
#
#from zipfile import *
#f=ZipFile("files.zip",'w',ZIP_DEFLATED)
#f.write("abcd.txt")
#f.write("abc.txt")
#f.close()
#print("files.zip file created successfully")
#Unzipping
#
#from zipfile import *
#f=ZipFile("files.zip",'r',ZIP_STORED)
#names=f.namelist()
#for name in names:
# print( "File Name: ",name)
# print("The Content of this file is:")
# f1=open(name,'r')
# print(f1.read())
# print()
#import os
#cwd=os.getcwd()
#print(cwd)
#import os
#os.mkdir("subdir")
#import os
#os.rename("subdir")
-----------------------------
exception
----------------
syntax
runtime
78
...100
without try-except
-----------
print("hello")
print(10/0)//zerodivsion error
print("statement")
o/p
---
hello
o/p
---
hello
5
statement
try:
code
except:
handller code
finally:
cleanup code
class classname:
instance var
local var
static var
__init__//constructor
class
@author: Poorni
"""
#
#class Student:
# def__init__(self,name,age,mark):
# self.name=name
# self.age=age
# self.mark=mark
#
# def method(self):
# print("hello",self.name)
# print("age is",self.age)
# print("my mark is",self.mark)
#
#referencevariable=clsssname()
#
#s=Student();
#s.method();
#class Student:
#
# def __init__(self,name,rollno,marks):
# self.name=name
# self.rollno=rollno
# self.marks=marks
#
# def talk(self):
# print("Hello My Name is:",self.name)
# print("My Rollno is:",self.rollno)
# print("My Marks are:",self.marks)
#s1=Student("Poorna",101,80)
#s1.talk()