Python Notes
Python Notes
<class 'float'>
<class 'complex'>
<class 'str'>
'A'
'e'
=======================================================================================================
Reverse Indexing:
>>> name = 'amey'
'y'
'e'
name [-6]
>>>
Python does negative indexing. It counts from right side and 1st char is -1 from RHS
=======================================================================================================
Slicing a data
>>> name = 'amey'
'y'
'me'
>>> name [: : 2]
'ae'
'oout'
'portun'
'rtunity' Here it takes data from 5th character and shows till end as our end index is invalid. We don’t have 11 characters in
string.
'opportunity'
'trop' Here using negative indexing it starts counting from RHS and shows characters from RHS.
'tnt'
'ytinutroppo' Here start index and end index are not there but since -1 is given as step value it starts from RHS.
Ex:- If we just want name of website and want to skip www & com from URL then use following code:
this asks for url. Give [Link]. Then it prints only google.
=======================================================================================================
Operations on Data
Operator
Binary :-
Only unary, ternary, and combinational assignments are operated/associated from right to left. All others go from Left to Right.
>>> a =10
>>> --a
10
>>> a++
>>> a--
>>> ++a
10
>>>
>>> b=++a
10
>>> -a
-10
>>> --a
10
>>> a +=1
11
And
>>> a-=1
=======================================================================================================
Classification of operators
Arithmetic Operators:
>>> 5 / 2.0
2.5
>>> 5//2.0
2.0
Relational operators:
Logical Operators:
&& , || , !
Identity Operators:
Ex:-
>>> a = [1,2,3]
>>> b=[1,2,3]
>>> c=a
>>> a is b
False
>>> a == b
True
>>> a is c
True
>>> c == b
True
>>> a is not b
True
Membership Operators:
True
False
False
Garbage value:
If a = 100 ; it has a reference.
Later if we change a =10 ; then earlier ref value is not used i.e. garbage.
Bitwise operators:
>>> bin (10)
'0b1010'
Bitwise & :- used to turn off bit or bits …. & turns off the bit
Ex:- a=100 i.e. in binary a = 001100100 and we need to turn off 3rd last bit then & this no with 001100000
Ex:- a =100 then if we want to turn on last bit then or it with no 001100101 so last bit becomes 0 or 1 = 1
Ex:- a =10 i.e. a = 00001010 in binary. If we << 1 then a 0 is added from right into no a and it becomes 00010100 i.e. 20 i.e 10 x
raised to 1
If we << 2 then 2 zeros will be added from right and no becomes 00101000 i.e. 40 i.e. 10 x 2 raised to 2
Multiplication by 2s power
If we <<3 then 3 zeros added and no becomes 01010000 i.e. 80 i.e. 10 x 2 raised to 3
In case of negative no. As for -ve no MSB ie. Left most bit is 1 showing it is a -ve no.
So when 0 comes in from left side then it is logical right shift and when 1 comes in then it is arithmetic right shift.
So only 1 is added from left side i.e. right shift by 1 is done. 0 is never added from left.
When bits are same result is 0 . and when bits are different then ans is 1.
0110110100
0000011100
0110101000
Compliment ~
Ex:- >>> ~5
-6
>>> ~ -5
Imagine it is done it in binary and try. You will find it is actual bit inversion.
Control Flow statements :
Sequence statements.
20 - 10 is 10
Selection statements.
If -else statement : -
result = 10
result = 30
Ex:-
Ex:-
Nested if :
HW: Write a prog to accept 3 nos and display a maximum out of them
Display min of 3
Prog to accept dd,mm,yy from user and check if it is valid or not. Print accordingly.
A = eval (input (“enter the no”)) Here eval converts input to respective data type (int,float,string etc)
Where in 2.x series we don’t need eval. But in that for string we need to give it in “ “
1. Enumeration controlled loop: we know for how many time we want to run a loop. Ex:- for loop . add 1 st 10 no
2. Logically controlled loop: we don’t know for how many time we have to run the loop. Ex:- While loop .Add till user
stops.
While loop:-
<initialization>
While <condition>:
Range function:
for x in range (5):
print (x)
o/p is:
0
1
2
3
4
Ex:-
for ch in "india":
print (ch)
o/p is:
i
n
d
i
a
This range function takes 3 arguments:- (start value, end value, step value)
If we give 1 argument it considers It as end value.
Ex:-
pass
Jump statements:
Ex:-
sum of non 5 no is 40
Hw:
to accept lower and upper bound from user and find out sum of even and odd no in given range separately.
Prog:
sum of multiples of 6 is 36
n = -1
sum = 0
while n != 0:
n = eval (input ("plz enter no: "))
sum = sum + n # i. e. sum+=n
print ("you entered 0, sum till now is %d" %(sum))
o/p:
There is provision for else statement for for loop and while loop also.
This else gets executed when upper for loop ends completely/successfully.
But it does not executes when control comes out of loop because of jump statements like break, return etc.
Ex:-
loop complete
This facility is used when we want to check upper loop getting executed successfully or not.
Function:
def <fun_name> (<argument to fun>):
<statement to be executed>
Ex:-
o/p: result is 30
result is 110
Here value of a and b is given. Later values will be taken from function definition as default values.
Multiway assignments:
def fun():
return a,b,c,d,e
l,m,n,o,p = foo()
o/p: result is 40
result is 60
result is 50
result is 301
Here if we give add (1,b=20,60) is not allowed as we have started with b=20 in between next should be also defined like
c=something. If we have started with a=something then next 2 must be same way.
HW:-Write Add fun which takes 5 arguments and try out with min 5 different combinations of function call with positional and
keyword argument.
def VariableArgsAdd(*args):
print (type (args))
for x in args:
print (x)
result = VariableArgsAdd (1,2,3)
result = VariableArgsAdd (1,2,3,4,5)
<class 'tuple'>
5
Prog to add all even and odd no is given range using functions:
enter ub29
Python script can be run independently or some other module imports it.
if __name__=='__main__': should be 1st line of any program so that it can be called by any other program if it
imports our current program.
Ex:-
C:\Users\[Link]\PycharmProjects\Test>python
Python 3.0.1 (r301:69561, Feb 13 2009, 17:50:10) [MSC v.1500 64 bit (AMD64)] on win32
>>>
>>>
>>>
>>> import fun_sumofevenodd #here we are importing our file which has function we need to use later
(30, 24)
Prog to accept 2 no from users and find GCD of them. Greatest common divisor.
#!/usr/bin/python
def gcd(a,b):
while a != b:
if a > b:
a = a-b
else:
b = b-a
return a
def main():
a = eval(input("give 1st no: "))
b = eval(input("give 2nd no: "))
res = gcd(a,b)
print ("gcd is: %d "%res)
if __name__=='__main__':
main()
o/p is:
gcd is: 25
#/usr/bin/python
def reverse(number):
rev = 0
while number != 0:
rem = number % 10
rev = rev * 10 + rem
number = int(number // 10)
return rev
def main():
number = eval (input ("give a number to reverse:"))
result = reverse(number)
print ("reverse of given number is %d"%result)
if __name__=='__main__':
main()
o/p :
HW:prog to accept a no from user and display the count and digit which occurs maximum no of times
#!usr/bin/bash
n = eval(input("give no for start: "))
for i in range (1,n+1):
for j in range (1,i+1):
print ('*\t', end="") #if \t not given then *s ll’b without space like ****
print ("\n")
* *
* * *
* * * *
#!/usr/bin/bash
n = eval(input("give no for start: "))
for i in range (1,n+1):
for j in range (1,n-i+1):
print ('\t',end="")
for k in range (1,i+1):
print ("*\t",end="")
print("")
* *
* * *
* * * *
#!/usr/bin/python
n = eval(input("give no for start: "))
for i in range (0,n):
for j in range (0,n-i-1):
print ("\t",end="")
for i in range (0,2*i+1):
print("*\t", end="")
print("\n")
for i in range (0,n):
for j in range (0,i-1):
print ("\t",end="")
for i in range (0,2*(n-i)+1):
print ("*\t",end="")
print ("\n")
o/p is :
* * *
* * * * *
* * * * * * *
* * * * * * * * *
* * * * * * *
* * * * *
* * *
HW: Prog to accept no of rows from user and print pattern like following:
B A B
C B A B C
LIST :
Ex: l1=[]
>>> l2 = [1,2,3]
<class 'list'>
[1, 2, 3, 4]
[1, 2, 3, 4, 5, 6, 7]
print (x)
>>>
l2 = [1,2,3,4]
i = 0
while i < len(l2):
print (l2[i])
i+=1
Prog to accept a list from user and element whose occurrence in a list is to be counted.
>>> [Link](2,4)
[1, 2, 4, 3, 4, 5, 6, 7]
>>> [Link](5)
[1, 2, 4, 3, 4, 5, 6]
>>>
>>>
[1, 2, 4, 4, 5, 6]
>>> [Link](1)
>>>
>>> print (l2)
[2, 4, 4, 5, 6]
>>> [Link]()
[6, 5, 4, 4, 2]
============================================================================================
['p', 'y', 't', 'h', 'o', 'n', 'c', 'l', 'a', 's', 's']
[1, 2, 3, 4, 5, 6]
>>> [Link](2)
Push,pop,stackfull,stackempty.
Prog to take list from user and find highest and lowest no from it.
#/usr/bin/python
def maxmin(l):
max = min = l[0]
i = 1
while i < len (l):
if (l[i] > max):
max = l[i]
if l[i] < min:
min = l[i]
i+=1
return max,min
def main():
l = [eval(input("enter elemnts in a list: "))]
maxmin(l)
maximum = max(l)
minimum = min (l)
print ("max is %d" %maximum)
print ("min is %d" %minimum)
if __name__=='__main__':
main()
max is 12345
min is 12345
#/usr/bin/python
def listCompare(l1,l2):
if type (l1) != list or type (l2) != list: #we check if input is of type list/not
def main():
l1 = eval(input("give list1: "))
l2 = eval(input("give list2: "))
retVal = listCompare (l1,l2)
if(retVal == 1):
print("Input Lists are Same")
else:
print("Input Lists are not Same")
if __name__ == '__main__':
main()
o/p :
Another o/p:
Prog to accept 2 lists from user and return intersection of them i.e. common elements in both lists.
Prog to accept 2 lists and return union in both i.e. common elements once and rest also once
Prog to accept 2 lists and return inverse intersection i.e. non common elements only
Prog to accept nested list of any no but o/p should be single level list
========================================================================================================
Union function:
def union(l1,l2):
l3 = l1
i = 0
while i < len(l2):
if l2(i) not in l3:
[Link](l2[i])
i+=1
return l3
Intersection:
def intersection(l1,l2):
l3 = []
i = 0
while i < len(l2):
if l2[i] in l1:
[Link](l2[i])
i+=1
return l3
inverse intersection:
Tuple :
Tuple is immutable. i.e. it is fixed or constant list. Individual contents can not be changed. Full tuple can be changed directly.
In list individual elements can be changed. We can just add something in last and considered as different tuple but original tuple
is intact.
>>> l1 = (1,2,3)
<class 'tuple'>
Ex:
>>> l1 + l1
(1, 2, 3, 1, 2, 3)
(1, 2, 3)
>>> help (str) and you can see different operations that can be performed on string.
>>> x = "amey"
>>> [Link]()
'Amey'
>>> [Link](10,'$')
'$$$amey$$$'
Prog to accept 2 strings accept and search from user and count occurrence of search string in input string without using count
method
Prog to accept a statement from user and replace occurrence of ‘not xx bad’ with ‘good’
Prog to accept ip string and replace character and replace all occurrences of 1 st character of input string with replace character
-============-=-==-=-====================-======================-==================-==================-
Prog to accept 2 strings from user and check if 2nd string is rotation of 1st or not.
#Prog to accept 2 strings from user and check if 2nd string is rotation of 1st or not.
def IsRotation (input_string,rotation_string):
print("Checking for Rotation.")
if len(input_string) != len(rotation_string): #amey is given and we need to
search yame then this check is must
return False
return rotation_string in input_string+input_string
def main ():
input_string = eval(input("enter input string: "))
rotation_string = eval(input("give string to be checked if it is rotation of i/p
string: "))
print(input_string)
print(rotation_string)
if IsRotation(input_string,rotation_string):
print ("{0} is rotation of {1} ".format(rotation_string,input_string))
else:
print("{0} is not rotation of {1} ".format(rotation_string, input_string))
if __name__ == '__main__':
main()
jeetendra
jeetendra
Checking for Rotation.
Prog to accept an alphanumeric string and display sum of all digits of string
def SumofDigits(input_str):
sum = 0
i = 0
while i < len(input_str):
if input_str[i].isdigit():
sum += int(input_str[i])
i+=1
return su
To accept a string from user which has consecutive repetitive characters, o/p should be string with how many times repeated
char is there along with the character
SET:
Set performs hashing on data i.e. it performs operation which guarantees you to get a unique answer.
Its an index based comparison. Makes containers and compares block by lock to check the character is present in block.
Checks end index decides if element is in block or it is greater than block’s limit.
>>> help (set) shows all operations that can be performed on set.
>>> x
>>> [Link]("e")
>>> x
>>> id (x)
1663118181544
>>>
>>> y=x
>>> id (y)
1663118181544
>>>
>>>
>>> id (y)
1663118181544
>>>
>>> id (x) since python follows reference model, x and y have same id. i.e. shallow copy
1663118181544
>>> y
>>> x
>>> z = [Link]
>>> id (z)
1663118192784
>>> x = [1,2,3,[4,5,6]]
>>> id (x)
1663118648840
>>> y=x
>>> id (y)
1663118648840
>>> z = [Link] (y) Here it is shallow copy operation. It copies top level references. only ref of inside [] is copied
copied
>>> id (z)
1663118532424
>>> id (y)
1663118648840
>>> id (x[3])
1663118648392
>>> id(z[3])
1663118648392
>>> x[3].append(0)
>>> x
>>> z
>>> [Link](9)
>>> x
>>> z
>>> w = [Link](x)
>>> w
>>> x
>>> y
>>> z
>>> id x[3]
>>> id (x[3])
1663118648392
>>> id (z[3])
1663118648392
=========================================================================================
HW: read copy module methods deep copy and shallow copy and write it in notes.
Difference operation
>>>
>>> x
{1, 2, 3, 4, 5}
>>> y
{4, 5, 6, 7, 8}
{1, 2, 3}
{8, 6, 7}
>>> x.difference_update(y)
>>> x
{1, 2, 3}
>>> [Link](2)
>>> y
{4, 5, 6, 7, 8}
>>> [Link](2)
[Link](2)
KeyError: 2
>>> y
{4, 5, 6, 7, 8}
>>> y
{4, 5, 7, 8}
>>> [Link](9)
[Link](9)
KeyError: 9
>>> [Link](7)
>>> y
{4, 5, 8}
>>> [Link](y)
True
>>> [Link](y)
False
>>> [Link]()
>>>
>>> x
{2, 3}
>>> [Link]()
pop(...)
>>> z = ([1,2,3,4,5,6,7,8,9])
>>>
>>> [Link]()
>>> [Link]()
Dictionary:
>>>
>>> student
'amey'
'30'
>>>
>>>
>>> student
>>> [Link]()
>>> [Link]()
>>>
print (key,student[key])
name amey
age 30
marks 100
fromkeys method which takes 1st argument from dictionary,2nd can be none or 1 value. If list comes in then 1st key to1st index
value, 2nd to 2nd index value.
result = {}
if type(ValuesList) == list or type(ValuesList) == tuple:
length = len ([Link]())
for key in [Link]():
i = 0
if i+1 == length and i+1 < len(ValuesList):
result[key] = ValuesList[i:] # slicing value list so that all next
elements are assigned to last key
else : if i < len(ValuesList):\
result[key] = ValuesList[i]
i += 1
else:
result[key] = None
return result
>>> x = {}
>>>
>>> x [2] =2
>>>
>>> x
{1: 100, 2: 2}
>>>
>>> [Link](x)
>>> [Link](x,[1,2])
i/p should have same no of keys and values. Write with {} and : separated dictionaries.
def compare(dict1,dict2):
retval = True
if type (dict1) != dict or type (dict2) != dict :
retval = False
if len(dict1) != len(dict2):
retval = False
else:
for key in dict1:
if key in dict1 and dict1[key] == dict2[key]:
continue
retval = False
break
return retval
explore bite array and DEQue doubly ended queue. Explore default dict.
FILE HANDLING:
Go to directory of python files from cmd.
fd = open (“[Link]”)
lines = [Link]()
lines
name = “amey”
surname = “godse”
city = “pune”
state = “maharashtra”
and now write a prog where this file is accepted and write it in a dictionary where LHS of = sign is taken as key and RHS is taken
as value.
>>> import io
>>> fd = [Link](r"C:\Python30\[Link]")
>>> [Link]()
>>> fd = [Link](r"C:\Python30\[Link]")
>>> [Link]()
So when we open 1st file no of files shows 3 because by default stdin and stdout and stderr are open so counting starts from 3
automatically when we open a file.
Prog to accept filename from user and display alternate 10 characters and once you reach end of file print the once which are
skipped. [Link]. not complete
Write a prog which returns longest and shortest line in a given file.
i/p file =
States MH PN KN
Jan 70 75 78
feb 81 84 86
mar etc
Suppose there is an empty or blank line in a file then still that file contains \n in it so that ine is not a blank line or end of file.
Actual blank line is end of file which can be interpreted as: if line = “”:
>>> help ([Link]) Shows the file handling operation. Some of them are as follows:
>>>
>>> [Link]("test")
'C:\\Users\\[Link]\\AppData\\Local\\Programs\\Python\\Python36\\test'
Even if there is no such file as test in your current path it shows that file in that path but it doesn’t create that file actually.
This is like pwd command. Shows current path where we are currently in where prompt is running.
True
Here there is no file named as Python in my pwd so it returns False. If its there it shows True.
'a\\b\\C'
If we give / as 2nd character in input then in output 1st charater is not shown.
'/a\\b\\C'
isfile(path)
>>> [Link]("[Link]")
True
>>> [Link]("[Link]")
('python', '.exe')
This is to parse or walk through a directory and we will check the contents in it.
Is there any particular file or what. We can decide depending on the arguments we pass to walk method.
Write a prog to compare 2 files using shutil modules. Import shutil and help(shutil)
Prog to accept a direct from user and list of extensions of file which are to be counted.
#copy source file to destination file by passing name of files as command line args
#usr/bin/pthon
import sys
def main(args):
print args
s_index=[Link]("-s")
src_file=args[s_index+1]
d_index=[Link]("-d")
dest_file=args[d_index+1]
if __name__ == '__main__':
main([Link][1:])
Incomplete program
>>> parser.add_argument("-s", type=str, help="sourse file name") …how we want to define argument of source file
>>> parser.add_argument("-d", type=str, help="dest file name") …how we want to define argument of destination file
import argparse
parser = [Link]()
parser.add_argument("-s", type=str, help="sourse file name")
parser.add_argument("-d", type=str, help="dest file name")
args = parser.parse_args()
print (args.s , args.d)
C:\Users\[Link]>C:\Users\[Link]\AppData\Local\Programs\Python\Python36\[Link] C:\Users\[Link]\
PycharmProjects\Test\[Link] -s source -d dest
#/usr/bin/python
import argparse
import shutil
parser = [Link]()
parser.add_argument("-s", type=str, help="sourse file name")
parser.add_argument("-d", type=str, help="dest file name")
args = parser.parse_args()
print(args.s, args.d)
[Link](args.s,args.d)
C:\Users\[Link]>C:\Users\[Link]>C:\Users\[Link]\AppData\Local\Programs\Python\Python36\[Link] C:\
Users\[Link]\PycharmProjects\Test\[Link] -s C:\Users\[Link]\PycharmProjects\Test\
[Link] -d C:\Users\[Link]\PycharmProjects\Test\[Link]
Then to crosscheck go to C:\Users\[Link]\PycharmProjects\Test in another window and you can see [Link] created
WAP to oreform following operations on 2 files using shutil module: compare 2 files, accept 2 files and merge them in 3 rd file.
>>> [Link](b"Hello") …Here it shows how many bytes are written in string. B for binary
>>> [Link](b"Helloworld")
>>> [Link](9)
b''
>>> [Link](0, 0)
0
>>> [Link](9)
b'Hello'
There are 6 tubelights in classrooms so each tubelight is 1 instance of class electrical appliances.
Abstraction: something which is hidden from object itself and obviously outer world.
Our brain is hidden from us, not visible. Functionality is hidden from object itself.
Data hidden is what brain is made of, it is hidden. Function of brain is hidden because we don’t know how it
works, this is function abstraction.
Polymorphism: manager says angrily “didn’t u get it?” your reply is polite. But for same question by friend your answer may be
“shut up u idiot”. i.e. behaving as per condition. It’s a run time behavior. Response at a time depending on context. 1 interface
multiple methods. Contractor of building who is our single PoC.
Inheritance: Rectangle is a Shape. Square is a Shape. Triangle is a Shape. i.e. rectangle, square, triangle are derived classes and
Shape is base class. When there is “is a” relationship then it’s a inheritance. Bike is a vehicle, car is a vehicle.
“Has a” relationship is also inheritance. Human has a heart, college has a student, company has an employee. Containment.
Object is same as instance. It is an instance of class. Every object is associated with 4 things
State: - static or dynamic state. If you do homework your state will change to intelligent.
Behavior: - You are doing homework because it’s your duty or responsibility.
When an object is created it is created by constructor method and destructed by destructor method.
All methods inside class and which are to be applied on object must have an argument “self”.
Methods which changes the state is called as setter or mutator. i.e. with every breath our breath count changes.
Getter or accessor method shows the current state. Get color method shows color of vehicle. It just states current state.
#usr/bin/python
class Human:
def __init__(self,n,a): #initialization
[Link] = n #attribute name
[Link] = a #attribute address
def main():
j = Human ("amey","Pune") #object j
k = Human ("ajay","Mumbai") #object k
print (j.__dict__)
print (k.__dict__)
if __name__ == '__main__':
main()
o/p: -
#/usr/bin/python
class stack:
def __init__(self,size): #this is constructor, gets called when new obj is
created
self.__mstack = []
self.__msize = size
def Push (self,data):
if [Link]() == False:
self.__mstack.append(data)
return True
return False
def Pop(self):
if [Link]() == False:
return self.__mstack.pop()
return False
def isfull(self):
return len(self.__mstack) == self.__msize
def isempty(self):
return 0 == len(self.__mstack)
def main():
intstack = stack(5)
while True:
print("1. Push")
print("2. Pop")
print("3. Exit")
choice = eval(input("Enter your choice:"))
if choice == 1:
data = input("enter data to push: ")
[Link](data)
elif choice == 2:
data = [Link]()
print (data) #data popped out is shown
else:
break
if __name__ == '__main__':
main()
1. Push
2. Pop
3. Exit
1. Push
2. Pop
3. Exit
1. Push
2. Pop
3. Exit
1. Push
2. Pop
3. Exit
1. Push
2. Pop
3. Exit
1. Push
2. Pop
3. Exit
1. Push
2. Pop
3. Exit
1. Push
2. Pop
3. Exit
1. Push
2. Pop
3. Exit
1. Push
2. Pop
3. Exit
1. Push
2. Pop
3. Exit
1. Push
2. Pop
3. Exit
1
1. Push
2. Pop
3. Exit
#/usr/bin/python
class Queue:
def __init__(self,size): #this is constructor, gets called when new obj is
created
self.__mstack = []
self.__msize = size
def Enqueue (self,data):
if [Link]() == False:
self.__mstack.append(data)
return True
return False
def Dequeue(self):
if [Link]() == False:
return self.__mstack.pop(0)
return False
def isfull(self):
return len(self.__mstack) == self.__msize
def isempty(self):
return 0 == len(self.__mstack)
def main():
intstack = Queue(5)
while True:
print("1. Enqueue")
print("2. Dequeue")
print("3. Exit")
choice = eval(input("Enter your choice:"))
if choice == 1:
data = input("enter data to push: ")
[Link](data)
elif choice == 2:
data = [Link]()
print (data)
else:
break
if __name__ == '__main__':
main()
o/p: 1. Enqueue
2. Dequeue
3. Exit
Enter your choice:1
1. Enqueue
2. Dequeue
3. Exit
1. Enqueue
2. Dequeue
3. Exit
1. Enqueue
2. Dequeue
3. Exit
1. Enqueue
2. Dequeue
3. Exit
1. Enqueue
2. Dequeue
3. Exit
1. Enqueue
2. Dequeue
3. Exit
1. Enqueue
2. Dequeue
3. Exit
1. Enqueue
2. Dequeue
3. Exit
#usr/bin/python
class PrivatePublic:
def __init__(self):
[Link] = 100
self.__iPrivate = 1000 # self.__value is syntax of private value assigning
def get_private(self):
return self.__iPrivate
def set_private(self,data):
self.__iPrivate = data
def __PrivateFunction(self):
print("(called private function)")
def display(self):
self.__PrivateFunction()
def main():
t1 = PrivatePublic()#t1 is object assigned to class PrivatePublic
[Link] = 1100 #declared here only
print([Link], t1.get_private())# print(t1.__iPrivate, t1.get_private())
print(t1._PrivatePublic__iPrivate) #(public value of a line above,
[Link] is called)
[Link]()
if __name__ == '__main__':
main()
1000
#/usr/bin/python
class Banking:
account_no_generator = 1 #variable for new account creation
def __init__(self,Name,Address,Balance=0):
self.__Name = Name
self.__Address = Address
self.__Balance = Balance
self.__Number = Banking.account_no_generator
Banking.account_no_generator += 1 #when new acc is created variable value
needs to be increased to be used for next account
def Withdraw (self,Amount):
if (self.__Balance > Amount):
self.__Balance -= Amount
return True
return False
def Deposite (self,Amount):
self.__Balance += Amount
return True
def BalanceCheck (self):
return self.__Balance
def main():
b1 = Banking("Amey", "Kothrud", 100)
while True:
print("1. Withdraw")
print("2. Deposite")
print("3. Balance Check")
choice = eval(input("Enter your choice:"))
if choice == 1:
amount = eval(input("Enter Amount to Withdrawn:"))
[Link](amount)
print([Link]())
elif choice == 2:
amount = eval(input("Enter Amount to be Deposite"))
[Link](amount)
print([Link]())
elif choice == 3:
print([Link]())
if __name__ == '__main__':
main()
o/p:
C:\Python30\[Link] C:/Users/[Link]/PycharmProjects/Test/[Link]
1. Withdraw
2. Deposite
3. Balance Check
Enter your choice:1
Enter Amount to Withdrawn:10
90
1. Withdraw
2. Deposite
3. Balance Check
Enter your choice:2
Enter Amount to be Deposite10
100
1. Withdraw
2. Deposite
3. Balance Check
Enter your choice:3
100
1. Withdraw
2. Deposite
3. Balance Check
Enter your choice:
WAP to implement complex no class. Which has real part and imaginary part
With operations: add 2 complex no, subtract, compare, multiply a complex no with an integer
WAP to implement a class student with attributes name, address, marks, age, gender
Add student, remove student, modify student, display all students, add attendance of every student.
In 3.x python all classes are derived from Object class. We need not explicitly mention it. Prog: OOPS6
But in 2.x we should mention it explicitly because it follows incorrect MRO (Method Resolution Order).
Regular Expression
import re
help (re)
WAP to accept a pattern and i/p string from user and print start and end of all matches found in i/p string.
Prog: regex1
#usr/bin/python
import re
a = eval(input("give string you want to search: "))
b = eval(input("give string where you want to search in: "))
x = [Link](a,b)
for y in x:
print([Link](),[Link]())
o/p :
give string you want to search: "a"
give string where you want to search in: "aaaa"
01
12
23
34
Here finditer function gives us start index and end index of a matching word and how many times it has occurred.
WAP to accept search pattern, replace pattern and i/p string in which a search pattern is to be searched and replaced
by replace pattern
Prog: regex2
#/usr/bin/python
def replacebysub(search_pattern,replace_pattern,input_string):
import re
output = [Link](search_pattern,replace_pattern,input_string)
return output
def main():
input_string = eval(input("write input string: "))
search_pattern = eval(input("write search pattern as a string: "))
replace_pattern = eval(input("write pattern to be used to replace as a string: "))
output = replacebysub(search_pattern,replace_pattern, input_string)
print (output)
if __name__ == '__main__':
main()
o/p:
write input string: "abababababab"
write search pattern as a string: "a"
write pattern to be used to replace as a string: "r"
rbrbrbrbrbrb
Prog: regex 3
#/usr/bin/python
import re
def main():
pattern = eval(input("enter pattern to be search: "))
regexobj =[Link](pattern)
while True:
input_string = eval(input("enter string in which we need to search: "))
for match in [Link](input_string):
print([Link](),[Link]())
if __name__ == '__main__':
main()
Needs to be changed so that it asks input only for required times like menu driven prog
o/p:
enter pattern to be search: "abcde"
enter string in which we need to search: "a"
WAP to accept a pattern from user, compile it in such a way that it will ignore case while matching input data.
WAP to implement your own finditer method and it should on string
Read special characters
IGNORECASE:
>>> import re
>>> regex0bj = [Link]("a",[Link])
>>> a= [Link]("sdsdfAfgh")
>>> a
<_sre.SRE_Match object; span=(5, 6), match='A'>
>>> [Link](),[Link]()
(5, 6)
MULTILINE:
Prog: regex4
Write a text file containing a and A at the starting in some lines at the location of pycharm project.
C:\Users\[Link]\PycharmProjects\Test
[Link]
abc
Abc
gahas
sadadad
asaaaa
hhasas
apppldo
Program:
#/usr/bin/python
import re
fd = open("[Link]")
x = [Link]()
o/p:
0 1
4 5
22 23
36 37
Here o/p shows the position of a (case insensitive) where a is at beginning of line.
22,23 are start and end positions of a at that position.
Here \n is also considered as a separate position so while counting add \n at the end of each line.
. means 1 occurance of any character and * means 0 or more occurrences of any character.
i.e. a.b means any character between a and b; but only 1 character. i.e. acb, adb, asb, afb
When a.*b is there then any character with more than 1 occurrence is allowed. i.e. ab , acfgb, adadb, abbbnnbnnb
+ means 1 or more occurrences. i.e. (ab)+ means atleast 1 occurrence is necessary for searching ab.
>>> x = [Link] ("(ab)+","hdhfhsababababdjfjdsf")
>>> [Link](),[Link]()
(6, 14)
? is given for searching only 1st occurrence of given string. i.e. (ab)*? here it gives o/p of positions when 1st occurrence of ab is
found.
ab{2,3} means a followed by b for 2 or 3 times is searched in string. i.e. dggsgsabbbasasjjadj, sadsadsdabbsdjfif
>>> x=[Link]("ab{2,3}","hsfdhshdaabbhhsdh")
>>> [Link](),[Link]()
(9, 12)
\ is an escape character. i.e. if you want dot “.” To be treated as actual . (dot) then before dot \ needs to be given.
\d+\.\d+\.\d+\.\d is used for searching ipv4 IPs.
Ex:-
>>> x = [Link] ("(\$)","abhdh$fhsababababdjfjdsfab")
>>> [Link](),[Link]()
(5, 6)
[^a-z] means anything without lower case alphabates. Here ^ is treated as negation
^[a-z] means starting with any lower case character is allowed. Here ^ is treated as starting of line.
Greedy and non greedy behavior: greedy means if a pattern matches multiple times then it takes a pattern as a whole match
and shows. Nongreedy means it shows a separate occurrences.
WAP to validate passwd. Passwd should be 8 length,atleast 1 capital and small char and atleast 1 numerical and atleast 1 special
char.
WAP to accept a list of patterns from user and i/p data and display all matches in given i/p for respective pattern.
Prog: regex5
#/usr/bin/python
ID = eval(input("give input data: "))
IP = eval(input("give pattern list to be searched: "))
import re
for pattern in IP:
for match in [Link](pattern, ID, [Link]):
print(pattern, [Link](), [Link](), ID[[Link]():[Link]()])
o/p:
give input data: "badfsabfnsafbsafaababababababa"
give pattern list to be searched: ["a.b", "a.c", "a*b"]
a.b 10 13 afb
a.b 16 19 aab
a*b 0 1 b
a*b 5 7 ab
a*b 12 13 b
a*b 16 19 aab
a*b 19 21 ab
a*b 21 23 ab
a*b 23 25 ab
a*b 25 27 ab
a*b 27 29 ab
another ex:
give input data: "abcdefghijklmnop"
give pattern list to be searched: ["^a" , "p$"]
^a 0 1 a
p$ 15 16 p
ab
ab*
ab+
ab+?
ab{3}
ab{5,10}
give these i/ps to above program (regex5) and give related i/p as below.
"sgsgabdhsahyhhabbbabbabbabbhdhhdhdabbbabbbuiiiuabbbbbbb"
Patterns:
either a or b;
a followed by 1 or more a or b ;
a followed by 1 or more a or b nongreedy;
a|b or [ab]
a[ab]+
a[ab]+?
Same as above. Give this pattern i/p in regex5 prog and give respective i/p
\b matches empty string but only at the start or end of the word
WAP which reads a name of directory and display all python scripts which are having shebang line in them on prompt.
#!\usr\bin\python is shebang line.
Check also if the program contains main.
Validate whether indentation is proper or not.
WAP to accept a name of python file which contains single line as well as multiline comments.
Remove all the single line and multiline comments using regex and write respective uncommented lines to specified file.
Prog to read another prog and give output only lines which are not having any comment in it.
Prog regex6
#/usr/bin/python
import re
fd=open("[Link]")
x =[Link]()
while x!= "":
y=[Link]("#",x)
if y:
if [Link]()!=0:
a=x[0:[Link]()]
print (a)
x = [Link]()
print(x)
o/p:
C:\Python30\[Link] C:/Users/[Link]/PycharmProjects/Test/[Link]
IP = eval(input("give pattern list to be searched: "))
import re
for pattern in IP:
#/usr/bin/python
import re
fd=open("[Link]")
x = [Link]()
r=[Link]("\"\"\"([\w\s]*)\"\"\"")
for y in [Link](x):
print([Link](),[Link]())
print ([Link](1))
o/p:
3 28
EXCEPTION HANDLING:
Try block will contain what we want to execute and inside that there will be except block which caches executions occurred and
respective code for operations.
Finally block:
This block gets executed always no matte exception occurs or not or whatever is the code written above it.
Program: exception1
#/usr/bin/python
#exception handling for division
import sys
def exceptionhandlingdivision(Numerator,Denominator):
try:
result=Numerator/Denominator
print("result:"+str(result))
except ZeroDivisionError as e:
print("Denominator is zero")
[Link](0)
except ArithmeticError as e:
print("Its an arithmatic error")
[Link](0)
except BaseException as e:
print("Its base class of all exception")
[Link](0)
else:
print("This else block of except is executed if there is no excption")
finally:
print("This finally block gets executed no matter what is written above")
def main():
Numerator = eval(input("Give numerator value: "))
Denominator = eval(input("Give Denominator value: "))
# exceptionhandlingdivision(20,10)
# exceptionhandlingdivision(20,0)
exceptionhandlingdivision(Numerator,Denominator)
if __name__ == '__main__':
main()
WAP to open a file in read mode and try to perform write operation on same file. Add this code in try/except block and observe
an exception that occurs because of trying to write on file opened in read mode.
Program exception2:
#/usr/bin/python
import sys
def exceptionforfile():
try:
fd=open("[Link]","r")
try:
[Link]("Hello")
finally:
[Link]()
except Exception as e:
print([Link])
print("exception occured as u r trying to open readable file")
print([Link])
print (type(e).__name__)
def main():
exceptionforfile()
if __name__ == '__main__':
main()
O/P:
None
exception occured as u r trying to open readable file
('[Link]() not supported',)
UnsupportedOperation
Suppose we give any file name which does not exist then o/p is as follows: give filename as [Link] in program only
o/p:
2
exception occured as u r trying to open readable file
(2, 'No such file or directory')
IOError
SUBPROCESS
Open command prompt at python masters directory.
>>> [Link]("copy",shell=True)
The syntax of the command is incorrect.
1
>>> subprocess.check_call("copy",shell=True)
The syntax of the command is incorrect.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python30\lib\[Link]", line 417, in check_call
raise CalledProcessError(retcode, cmd)
[Link]: Command 'copy' returned non-zero exit status 1
>>>
Here check_call gives exception but call does not gives exception. So when we want to take logs use check_calls so it gives
exception and program terminates we come to know that this is where error occurred.
Go to IDLE
>>> subprocess.check_output("dir")
This will show all the contents of current directory.
WAP to accept a complete path of a python script to be launched from python program and launch the same.
Program: [Link]
This program will call another program [Link]
WAP to accept a name of a file whose line count, word count and character count should be redirected to an output file
accepted from user.
Program: subprocess1
#/usr/bin/python
import subprocess
inputfile = eval(input("give file whose word,line,char count is needed: "))
outputfile = eval(input("give file where output is to be stored: "))
fd_in = open(inputfile) #opens input file
fd_out = open(outputfile,"w") #opens oputpufile
output = [Link]("wc",stdin=fd_in,stdout=fd_out)#wc of ip file is stored in op file
Output:
give file whose word,line,char count is needed: "[Link]"
give file where output is to be stored: "[Link]"
Here input file needs to be already created. Ex:- “[Link]” needs to be already present with some data in it.
Output file gets created with name we give.
preexec_fn : this call is used when we want to pass any argument to a child process before child process gets executed.
Ex:- if you are passing some machine name to a child process from parent process then before the child process gets executed u
want to close some ports of that machine then write a function which closes a required ports and then we call that function in
preexec_fn call.
Program: preexex_fn
#/usr/bin/pyton
import subprocess
def foo():
print("parent process")
[Link](['echo', '"child process"'],preexec_fn= foo)
Here,
[Link] is child process and in that’s attributes we are passing preexex_fn = foo. This foo will print parent process.
So in the final output “parent process” is displayed 1st and then “child process” is displayed.
This prog will not work on windows as process of process execution is different in windows. This prog will work in unix only.
WAP which runs periodically and displays status of currently running processes.
Tasklist on windows and ps -eaf on unix
Program: Subprocess2
#/usr/bin/bash
import subprocess
import time
def SubprocessStatus(timeout):
count = 0
while count != 10:
output=[Link](["tasklist"," /v"])
print(output)
count +=1
[Link](timeout)
def main():
timeout = eval(input("enter the time after which u want to run tasklist command:
"))
SubprocessStatus(timeout)
if __name__ == '__main__':
main()
Threads in Python:
Global Interpreter Lock. This lock allows only 1 process to use resources at a time.
Go through presentation by david. This is drawback of python. Must read.
Multithreading is not allowed in python because of GIL. Thread acquires lock and does not allow other thread to acquire lock
and keeps it on hold. Video about this is on git.
Module which helps to create threads in python is “Threading”. It needs to be started explicitly by calling start on it.
#/usr/bin/python
import threading
def worker():
"""thread worker function"""
print("worker")
if__name__='__main__'
t = [Link](target=worker)
[Link]()
Here, in main [Link] is written explicitly so that it will start. Target=worker states that when we will do [Link] which function
needs to be run by this thread. Here it will start worker function.
If u want to create thread class, it will inherit from Thread class. Then it needs to have its own run method.
[Link] means threading named module has a class named Thread which is base class of all threads and it has its own
run method but here we are creating our own thread so we need to write our own run method.
#/usr/bin/python
import threading
class subthread([Link]):
def run(self):
print("running ...........\n")
return
for i in range(5):
t = subthread()
[Link]()
o/p:
running ...........
running ...........
running ...........
running ...........
running ...........
there is a mechanism called lock in thread to lock a resource. Resource can be a variable.
lock = [Link]()
.
.
.
.
.
.
[Link]() #this release must be before return.
Producer Consumer
Event can be set or cleared. Once event is cleared it needs to be cleared so that later it can be used by other thread.
Program: producer_consumer.py
data = []
produce_event = Event()
consume_event = Event()
def read():
global data
while True:
if len(data) == 0:
produce_event.clear()
produce_event.wait()
print("\nConsumed ", data[0])
if data[0] == "end":
consume_event.set()
break
del data[0]
consume_event.set()
[Link](1)
def write():
global data
while True:
if len(data) == 10:
consume_event.clear()
consume_event.wait()
val = input("Enter Data (to stop enter end):-")
[Link](val)
if val == "end":
produce_event.set()
break
if len(data) == 10:
produce_event.set()
[Link](0.1)
o/p:
Enter Data (to stop enter end):-1
Enter Data (to stop enter end):-2
Enter Data (to stop enter end):-3
Enter Data (to stop enter end):-4
Enter Data (to stop enter end):-5
Enter Data (to stop enter end):-6
Enter Data (to stop enter end):-7
Enter Data (to stop enter end):-8
Enter Data (to stop enter end):-9
Enter Data (to stop enter end):-0
Consumed 1
Enter Data (to stop enter end):-
Consumed 2
Consumed 3
Consumed 4
Consumed 5
Consumed 6
Consumed 7
Consumed 8
Consumed 9
Consumed 0
Lambda Generator:
#!/usr/bin/python
def Square(x):
return x*x
x = lambda y: y*y
print(x(3))
Map:
When we want to map a function on a data. Where function needed to be applied on whole data.
#!/usr/bin/python
fd = open("[Link]")
lines = [Link]()
z = map(lambda x : len(x), lines)
y = iter(z)
print(next(y))
print(next(y))
print(next(y))
[Link]()
Here if we use for loop for next(y) then it will parse data till last line automatically.
Here we have gven i/p file [Link] which has 3 lines data. Then o/p is:
18
16
6
Program: lmbda2
#/usr/bin/python
#WAP to accept data from user and print no which are not divisible by 2 and 3
def notdivisible2and3(x):
return x%2 != 0 and x%3 != 0
print (filter(notdivisible2and3, range(2,25)))
print (map(notdivisible2and3, range(2,25)))
print (filter (lambda x:x%2 !=0 and x%3 != 0, range(2,25)))
print (map(lambda x:x%2 !=0 and x%3 !=0 , range(2,25)))
Here filter will give output of those numbers which satisfy the criteria and will give those numbers.
And map will give output as True or false depending on number that is received as input.
Here we need to edit the program as above program or give for loop to parse the data.
Reduce:
o/p:
12
23
64
24 5
120 6
720 7
5040 8
40320 9
362880
Here 1*2 is done and its o/p is taken as i/p for 2nd multiplication and so on.
Yield:
Suppose we are executing a caller function which calls other function in it then control goes from caller function to a function
which is getting called. i.e. if function A calls function B inside it then control goes from A to B and it performs necessary
operation and then using yield the control goes back to A from where it invoked B. here control does not go to starting of A.
Control goes to location from where B was invoked.
Program: yield1
#/usr/bin/python
def samplegenerator():
yield 1
yield 2
yield 3
yield 4
def incrementor():
x = 1
while True:
yield x
x += 1
if __name__ == '__main__':
x = samplegenerator()
print(next(x))
print(next(x))
print(next(x))
print(next(x))
x = incrementor()
print(next(x))
print(next(x))
print(next(x))
O/p:
1
2
3
4
1
2
3