0% found this document useful (0 votes)
4 views64 pages

Python Notes

The document provides an extensive overview of Python data types, including integers, floats, strings, and complex numbers, along with their operations and indexing methods. It covers various Python concepts such as slicing, primitive containers, operators, control flow statements, loops, and functions, with examples illustrating their usage. Additionally, it includes exercises for practicing these concepts.

Uploaded by

dawood mamtule
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views64 pages

Python Notes

The document provides an extensive overview of Python data types, including integers, floats, strings, and complex numbers, along with their operations and indexing methods. It covers various Python concepts such as slicing, primitive containers, operators, control flow statements, loops, and functions, with examples illustrating their usage. Additionally, it includes exercises for practicing these concepts.

Uploaded by

dawood mamtule
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

For reference [Link] or book given in notes.

Data Types in Python:


Integer:- >>>a =3.14

>>> type (a)

<class 'float'>

>>> type (c)

<class 'complex'>

In python everything is a string. String and character is same in python.

A = ‘C’ and A = “C” both is same.

>>> name = "Amey"

>>> type (name)

<class 'str'>

>>> name [0]

'A'

>>> name [2]

'e'

Every character is given a no for its location in mem.

>>> name [0] = 'q'

Traceback (most recent call last):

File "<pyshell#37>", line 1, in <module>

name [0] = 'q'

TypeError: 'str' object does not support item assignment

Changing individual character is not allowed.

We can change name directly. Ex : name = “India”

=======================================================================================================

Reverse Indexing:
>>> name = 'amey'

>>> name [-1]

'y'

>>> name [-2]

'e'

>>> name [-6]

Traceback (most recent call last):

File "<pyshell#61>", line 1, in <module>

name [-6]

IndexError: string index out of range

>>>

Python does negative indexing. It counts from right side and 1st char is -1 from RHS

=======================================================================================================

Slicing a data
>>> name = 'amey'

>>> name [3:]

'y'

>>> name [1:3]

'me'

1 is start index and 3 is end index. Start is from 0.

1 gives 2nd character and 3 gives 4th character.

Start index : end index is syntax.

>>> name [: : 2]

'ae'

Ex:- >>> name = 'opportunity'

>>> name [::3]

'oout'

Here [start index: end index: step value]

Step value means the difference in characters we want to be printed.

Ex:- >>> name [1:9:3]


'prn'

>>> name [2:8]

'portun'

>>> name [3::]

'ortunity' this shows data from 4th character till end.

>>> name [4:11]

'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.

Ex: ->>> name

'opportunity'

>>> name [5:1:-1]

'trop' Here using negative indexing it starts counting from RHS and shows characters from RHS.

Ex:- >>> name [-2:-7:-2]

'tnt'

Ex:- >>> name [::-1]

'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:

url = input ("enter URL")


print (url [4:-4:])

this asks for url. Give [Link]. Then it prints only google.

=======================================================================================================

Primitive Containers in Python are String, List, Tuple, Dictionary


=======================================================================================================

Operations on Data
Operator

Arity precedence associativity

Arity is no of operands an operator takes:- unary :-

Binary :-

Precedence gives priority: BODMAS/ PEMDAS rule


Associativity decides in case when 2 priorities are remaining only. Ex:- 10 x 5 / 2

Only unary, ternary, and combinational assignments are operated/associated from right to left. All others go from Left to Right.

Combinational means += or -= etc

Python does not support ++ or –

>>> a =10

>>> --a

10

>>> a++

SyntaxError: invalid syntax

>>> a--

SyntaxError: invalid syntax

>>> ++a

10

>>>

>>> b=++a

>>> print (b)

10

>>> -a

-10

>>> --a

10

If we want to increase by 1 then go for a+=1 or a-=1 for decreasing a by 1.

>>> a +=1

>>> print (a)

11

And

>>> a-=1

>>> print (a)

=======================================================================================================
Classification of operators
Arithmetic Operators:

5**5 is s raised to 5 and 5//2 is 2 only as a no after decimal point is omitted.

>>> 5 / 2.0

2.5

>>> 5//2.0

2.0

Relational operators:

Greater than , less than, == , !=

Logical Operators:

&& , || , !

&& is replaced by word ‘and’

|| is replaced by word ‘or’

! is replaced by word ‘not’ ……in python.

Identity Operators:

Is , is not are 2 identity operators.

Ex:-

>>> a = [1,2,3]

>>> b=[1,2,3]

>>> c=a

>>> a is b

False here it checks if both are referring to same location or not??

>>> id (a) == id (b)

False

>>> a == b

True

>>> a is c

True
>>> c == b

True

== checks only values and not the locations.

>>> a is not b

True

Is not checks the locations.

Membership Operators:

In , not in are 2 operators.

Ex:- >>> 'h' in 'hello'

True

>>> 'h' not in 'hello'

False

>>> 'b' in 'hello'

False

It checks the presence of a character in a string.

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

Bitwise or i.e. | :- to turn on a bit or bits

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:- 218 | 32 = 250 in idle


Left shift i.e. << used to multiply ….. OR turns on the bit

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

Right shift i.e. >>

Ex: - a = 80 i.e. 01010000 >> 1; then it becomes 001010000 i.e. 40

This is division by 2s power

In case of negative no. As for -ve no MSB ie. Left most bit is 1 showing it is a -ve no.

-ve no is 1s complement + 1 of a 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.

Left shift and right shift is not done on -ve no usually.

Toggling: ^ is used as a sign. This is Ex- OR operation.

When bits are same result is 0 . and when bits are different then ans is 1.

0110110100

0000011100

0110101000

Compliment ~

Invert the no. 0 to 1 and 1 to 0

i.e. ~ 1010 = 0101

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.

A,b = 10,5 then a =10 and b =5 This is python specific feature.

Ex:- a,b= eval(input("Enter 2 no using comma"))


print ("%d - %d is %d" %(a,b,a-b))

Enter 2 no using comma20,10

20 - 10 is 10

Selection statements.

If -else statement : -

a,b = eval(input("Enter 2 no using comma"))


result = 0
if a > b :
result = a - b
else:
result = b - a
print ("result = %d " % result)

Enter 2 no using comma10,20

result = 10

Enter 2 no using comma40,10

result = 30

Ex:-

a,b,c = eval(input("Enter 3 no using comma"))


if a > b:
print ("Hello")
if a > c:
print ("Bye")
else:
print ("Its a catch")
Here all if statements are checked and depending on condition result is shown.

Ex:-

a,b,c = eval(input("Enter 3 no using comma"))


if a > b:
print ("Hello")
elif a > c:
print ("Bye")
else:
print ("Its a catch")
Here if 1st if fails then only it will switch to elif. And if both 2 above fails then only it will shift to else part.

Nested if :

a,b,c = eval(input("Enter 3 no using comma"))


if a > b:
print ("Hello")
if a > c:
print ("Bye")
else:
print ("Its a catch")
Here 1st if is checked and o/p is shown if it is correct. If it fails it goes in 2nd if.

HW: Write a prog to accept 3 nos and display a maximum out of them

Display min of 3

Accept a rating out of 5 and print grade/rating.

Prog to accept dd,mm,yy from user and check if it is valid or not. Print accordingly.

dd,mm,yy = eval(input("enter date,month,year"))


if dd > 0 and dd <= 31:
if mm > 0 and mm <=12:
if yy > 0:
print ("your date is %d / %d/ %d " %(dd, mm ,yy))
else:
print ("yy = %d is invalid"% yy)
else:
print ("mm = %d is invalid"%mm)
else:
print ("dd = %d is invalid" %dd)

Or 7th line can be as print ("your date is {0}:{1}:{2}".format(dd,mm,yy))


On 3.x series of pycharm

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 “ “

Repetition: - loop comes in picture.

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>:

<condition control statement/s>

Ex:- Accept value of n and display sum of even no from 0 to n.

n = eval (input ("enter no : "))


sum = 0
i = 0
while i <= n:
if i%2 == 0: # 6%3=0. % shows digit next to decimal point
sum = sum + i
i+=1 ……………………….…………if this line is written with 1 more tab then its infinite loop
print ("sum of %d numbers is %d"%(n,sum))

For <loop variable> in <container>

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.

If we give 2 arguments it considers them as start and stop value

If 3 given then all 3 are considered.

Ex:-

# Program to add sum of even no till given value


n = eval (input ("enter upper bound"))
sum = 0
for x in range (2,n+1,2): #from 2, upper bound & its exclusive, step value
sum = sum + x
print ("sum of even no upto %d is %d"%(n,sum))

o/p:- enter upper bound20

sum of even no up to 20 is 110 …here 20 is exclusive. It adds from 0 to 18

Time delay loops:

If we want to pass some time i.e. give sleep

for i in range (100):

pass

then it will do nothing till 100 count is arrived in iteration

Jump statements:

Continue , break are 2 Jump statements

Ex:-

Add no which are not multiple of 5 from given input range.


n = eval (input("give no till u want to add "))
sum = 0
for i in range (0,n):
if i % 5 == 0:
continue
sum = sum + i
print ("sum of non 5 no is %d"%(sum))

o/p is : - give no till u want to add 10

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:

l = eval (input ("lower boud plz : "))


u = eval (input ("upper bound +1 plz : "))
sum_even = 0
sum_odd = 0
for i in range (l,u,1):
if i % 2 == 0:
sum_even = sum_even + i
else:
sum_odd = sum_odd + i
print ("sum of even numbers in range is %d" %(sum_even))
print("sum of odd numbers in range is %d" % (sum_odd))

o/p: lower boud plz : 2

upper bound +1 plz : 11

sum of even numbers in range is 30

sum of odd numbers in range is 24


Prog accept a range from user & display sum of multiples of 6 in given rang.

l = eval(input("enter lower bound plz : "))


u = eval(input("enter upper bound plz : "))
sum = 0
for i in range (l,u):
if i % 6 == 0:
sum = sum + i
else:
pass #This else and pass is not necessary
i+=1
print ("sum of multiples of 6 is %d" % (sum))

o/p: enter lower bound plz : 2

enter upper bound plz : 20

sum of multiples of 6 is 36

Prog to keep on adding a nos until user enters 0

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:

plz enter no: 1

plz enter no: 2

plz enter no: 4

plz enter no: 8

plz enter no: 0

you entered 0, sum till now is 15

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:-

for x in range (1,5):


print (x)
else:
print ("loop complete")
o/p: 1

loop complete

This facility is used when we want to check upper loop getting executed successfully or not.

Is there any break in between or not.

Ex:- for x in range (1,10):


print (x)
if x % 7 == 0:
break
else:
print ("loop complete")
o/p : 1

Process finished with exit code 0

Function:
def <fun_name> (<argument to fun>):

<statement to be executed>

Ex:-

def add (a,b):


return a + b
result = add (10,20)
print ("result is %d"% (result))

o/p: result is 30

here position of a and b is fixed. This is positional arguments.


Another type of argument is default arguments.

def add (a,b=10): #here 10 is default value of b in case not given.


return a + b
result = add (100,200)
print ("result is %d"% (result))
result = add (100) #here b is taken as 10 by default coz we didn’t specify here.
print ("result is %d"% (result))

o/p: result is 300

result is 110

HW:- prog to multiply 2no,3no,4no,5no separately. Single function.

def multiply (a=1,b=2,c=3,d=4,e=5):


return a*b*c*d*e
result = multiply(10,20)
print ("result is %d"%(result))

o/p: result is 12000

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()

Here values are assigned to abcde as lmnop …need to try out

Ex:- def add (a,b,c=20):


return a+b+c
result = add (10,10)
print ("result is %d" %(result))
result = add (10,b=30)
print ("result is %d" %(result))
result = add (b=10,a=20)
print ("result is %d" %(result))
result = add (1,c=200,b=100)
print ("result is %d" %(result))

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.

We can start with a/b/c= something.

HW:-Write Add fun which takes 5 arguments and try out with min 5 different combinations of function call with positional and
keyword argument.

Hw: fun to add any no of arguments

Variable number of arguments:

def VariableArgsAdd(*args):
print (type (args))
for x in args:
print (x)
result = VariableArgsAdd (1,2,3)
result = VariableArgsAdd (1,2,3,4,5)

o/p: <class 'tuple'> #this is because 2nd statement

<class 'tuple'>

5
Prog to add all even and odd no is given range using functions:

def sumofevenodd (lb,ub):


sum_even = 0
sum_odd = 0
while lb <= ub:
if lb % 2 == 0:
sum_even += lb
else:
sum_odd += lb
lb += 1
return sum_even , sum_odd

if __name__=='__main__': #optional statement


lb = eval(input("enter lb"))
ub = eval(input("enter ub"))
sum_even,sum_odd = sumofevenodd(lb,ub)
print ("sum of even no is:%d "%sum_even)
print ("sum of odd no is:%d "%sum_odd)

o/p = enter lb12

enter ub29

sum of even no is:180

sum of odd no is:189

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:-

Go to cmd and go to your pycharm programs directory

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

Type "help", "copyright", "credits" or "license" for more information.

>>>

>>>

>>>

>>> import fun_sumofevenodd #here we are importing our file which has function we need to use later

>>> fun_sumofevenodd.sumofevenodd(2,10) #[Link](arguments)

(30, 24)
Prog to accept 2 no from users and find GCD of them. Greatest common divisor.

Ex:- 35,49 ans is 7.

#!/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:

give 1st no: 25

give 2nd no: 100

gcd is: 25

Prog to accept a no from user and print its reverse.

#/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 :

give a number to reverse:23456

reverse of given number is 65432

Check if a no is palindrome or not


HW:Prog to accept a no from user and define a function of sum of cubes of digits.

i.e. no is 123 then 1cube + 2cube + 3cube = 27 + 8 + 1 = 36

HW: prog to accept a no from user and check if it is Armstrong no

i.e. sum of cubes of digit = original no . ex: 153 = 1 + 125 + 27 = 153

HW:prog to accept a no from user and display the count and digit which occurs maximum no of times

i.e. 112311 should show 1 is 4 times

Prog to print *s for given no:

#!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")

o/p is : give no for start: 4

* *

* * *

* * * *

HW: show mirror image of above. Hint: n-1


Prog to print reverse of above:

#!/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("")

o/p : give no for start: 4

* *

* * *

* * * *

Prog to make a diamond of starts: NEED TO CORRECT

#!/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 :

give no for start: 4

* * *

* * * * *

* * * * * * *
* * * * * * * * *

* * * * * * *

* * * * *

* * *

THIS NEEDS TO BE CORRECTED

HW: Prog to accept no of rows from user and print pattern like following:

B A B

C B A B C
LIST :

It’s a changeable , represented by []

Ex: l1=[]

>>> l2 = [1,2,3]

>>> type (l2)

<class 'list'>

To append an element in list:

>>> [Link](4) This is for adding 1 element only

>>> print (l2)

[1, 2, 3, 4]

To add multiple elements in list:

>>> [Link] ([5,6,7])

>>> print (l2)

[1, 2, 3, 4, 5, 6, 7]

>>> for x in l2:

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)

>>> print (l2)

[1, 2, 4, 3, 4, 5, 6, 7]

Here it adds no 4 at position 2. Positioning starts from 0……

>>> [Link](5)

>>> print ([Link]())

>>> print (l2)

[1, 2, 4, 3, 4, 5, 6]

>>>

Pop removes last number in list

>>> print ([Link](3))

>>>

>>> print (l2)

[1, 2, 4, 4, 5, 6]

Here 3rd position number is popped out

>>> [Link](1)

>>>
>>> print (l2)

[2, 4, 4, 5, 6]

>>> [Link]()

>>> print (l2)

[6, 5, 4, 4, 2]
============================================================================================

>>> x = list ("pythonclass")

>>> print (x)

['p', 'y', 't', 'h', 'o', 'n', 'c', 'l', 'a', 's', 's']

>>> list1 = [1,2,3]

>>> list2 = [4,5,6]

>>> list3 = list1 + list2

>>> print (list3)

[1, 2, 3, 4, 5, 6]

Here list1 and list2 remain intact

>>> [Link](2)

Here it shows index value of 2 i.e. 1..here indexing starts from 0.

Prog to reverse the list:

Prog to implement a stack using list.

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()

Need to change this program.

Current incorrect o/p is:

enter elemnts in a list: 12345

max is 12345

min is 12345

Prog to check contents of 2 lists is same or not. [Link]

#/usr/bin/python
def listCompare(l1,l2):
if type (l1) != list or type (l2) != list: #we check if input is of type list/not

print ("1st or 2nd list is not list")


return
if len (l1) != len (l2):
return 0
for i in range (len(l1)):
if l1[i]==l2[i]:
continue
break
else:
return 1
return 0

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 :

give list1: [1,2,3] …we have to give input in [] only

give list2: [2,3,4]

Input Lists are not Same

Another o/p:

give list1: (12,3,434)

give list2: [12,3,434]

1st or 2nd list is not list


Input Lists are not Same

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

All 3 can be clubbed in 1 prog

Prog to accept nested list of any no but o/p should be single level list

I.e. if i/p is [1,2[3,4],[5,[6,7],8,9][10,11]] then o/p is [1,2,3,4,5,6,7,8,9,10,11]

========================================================================================================

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

#this does not work when a no comes multiple times in 1 list

inverse intersection:

def invintersection (l1,l2):


l3 = []
i = 0
while i < len (l2):
if l2[i] in l1:
[Link] (l2[i])
else:
[Link] (l2[i])
i+=1
[Link](l1)
return l3

Prog for nested list….list inside list [1,2[2,4],5,6[7,8,9]]


def NeutralizeList(l1):
i = 0
l2 = []
while (i < len (l1)):
if type (l1[i]) != list:
[Link] (l1[i])
else:
ExtendList (l2,l1[i])
i+=1
return l2
def ExtendList(l2,l3):
j = 0
while j < len (l3):
if type (l3[j]) != list:
[Link] (l3[j])
else:
ExtendList (l2,l3[j]) #we r calling same function again so if nested
list comes it should call same function again
j+=1
def main ():
l1 = eval (input ("enter list l1: "))
output = NeutralizeList(l1)
print ("output is ",output)
if __name__ == '__main__':
main()

Read bubble,select,insertion sort

Prog to implement queue using list i.e. 1st in 1st out

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.

Help (tuple) and we can see details

>>> l1 = (1,2,3)

>>> type (l1)

<class 'tuple'>

Ex:

>>> l1 + l1

(1, 2, 3, 1, 2, 3)

>>> print (l1)

(1, 2, 3)

Here original l1 remains intact

>>> 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

Replace 1st letter of string by replace character:

def replacefirstcharoccurence (input_string,replace-by):


return input_string[0]+input_string[1:].replace(input_string[0],replace_by)
# 'b' 'ubble' . ('b', '*' )
# this b is carried forward and this becomes u**le
#here suppose input_string is "bubble' and replace character is * then; above
condition happens

Cracking coding interview by mc’dowell …..book for interviews

-============-=-==-=-====================-======================-==================-==================-

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()

enter input string: "jeetendra"

give string to be checked if it is rotation of i/p string: "jeetendra"

jeetendra

jeetendra
Checking for Rotation.

jeetendra is rotation of jeetendra

Prog to generate all possible rotations of input string


==============================================================

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 display count of vowels and consonants and other characters in string

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

If i/p is [1,2,2,2,3] then o/p should be [1,2,3] remove adjacent

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.

Its not sequential hashing.

>>> help (set) shows all operations that can be performed on set.

>>> x = set ("maharashtra")

>>> x

{'r', 'a', 's', 'h', 't', 'm'}

>>> [Link]("e")

>>> x

{'e', 'r', 'a', 's', 'h', 't', 'm'}

>>> id (x)

1663118181544

>>>
>>> y=x

>>> id (y)

1663118181544

>>>

>>> [Link] ("f")

>>>

>>> id (y)

1663118181544

>>>

>>> id (x) since python follows reference model, x and y have same id. i.e. shallow copy

1663118181544

>>> y

{'e', 'r', 'a', 's', 'h', 't', 'm', 'f'}

>>> x

{'e', 'r', 'a', 's', 'h', 't', 'm', 'f'}

>>> z = [Link]

>>> id (z)

1663118192784

deep copy means pointing to diff locations.

>>> 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

[1, 2, 3, [4, 5, 6, 0]]

>>> z

[1, 2, 3, [4, 5, 6, 0]]

>>> [Link](9)

>>> x

[1, 2, 3, [4, 5, 6, 0]]

>>> z

[1, 2, 3, [4, 5, 6, 0], 9]

>>> w = [Link](x)

>>> w

[1, 2, 3, [4, 5, 6, 0]]

>>> x

[1, 2, 3, [4, 5, 6, 0]]

>>> y

[1, 2, 3, [4, 5, 6, 0]]

>>> z

[1, 2, 3, [4, 5, 6, 0], 9]

>>> 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 = set ([1,2,3,4,5])


>>> y = set ([4,5,6,7,8])

>>>

>>> x

{1, 2, 3, 4, 5}

>>> y

{4, 5, 6, 7, 8}

>>> [Link] (y)

{1, 2, 3}

>>> [Link] (x)

{8, 6, 7}

>>> x.difference_update(y)

>>> x

{1, 2, 3}

Discard and Remove operations:

>>> [Link](2)

>>> y

{4, 5, 6, 7, 8}

>>> [Link](2)

Traceback (most recent call last):

File "<pyshell#113>", line 1, in <module>

[Link](2)

KeyError: 2

>>> y

{4, 5, 6, 7, 8}

>>> [Link] (6)

>>> y

{4, 5, 7, 8}

>>> [Link](9)

Traceback (most recent call last):

File "<pyshell#117>", line 1, in <module>

[Link](9)

KeyError: 9

>>> [Link](7)
>>> y

{4, 5, 8}

isdisjoint(...) : Return True if two sets have a null intersection.

>>> [Link](y)

True

>>> [Link](y)

False

>>> [Link]()

>>>

>>> x

{2, 3}

>>> [Link]()

pop(...)

| Remove and return an arbitrary set element.

| Raises KeyError if the set is empty.

>>> z = ([1,2,3,4,5,6,7,8,9])

>>>

>>> [Link]()

>>> [Link]()

Dictionary:

>>> student = {"name":"amey","age":"30"}

>>>

>>> student

{'name': 'amey', 'age': '30'}


>>>

Colon separated key-value pairs can be added in dictionary.

>>> student ["name"]

'amey'

>>> student ["age"]

'30'

Adding a key to dictionary. It can be added anywhere.

>>> student ["marks"]=100

>>>

>>>

>>> student

{'name': 'amey', 'age': '30', 'marks': 100}

>>> [Link]()

dict_items([('name', 'amey'), ('age', '30'), ('marks', 100)])

>>> [Link]()

dict_keys(['name', 'age', 'marks'])

>>>

>>> for key in student:

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.

def from_keys (d1,ValuesList=None):


#VERIFY D1 IS DICTIONARY
#VERIFY IF VALUELIST IS A CONTAINER

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

Indentation Is wrong. Correct it and prog will work

>>> x = {}

>>> x [1] =100

>>>

>>> x [2] =2

>>>

>>> x

{1: 100, 2: 2}

>>>

>>> [Link](x)

{1: None, 2: None}

>>> [Link](x,[1,2])

{1: [1, 2], 2: [1, 2]}

Prog to accept 2 dictionaries to compare key and values.

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

HW: create a file as folllows

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]")

>>> help (fd) …shows brief description of fd

>>> [Link]()

Now open another file

>>> 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.

Read advanced programming in unix environment

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 to count no of lines, no of words, no of characters in given file.

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

And show avg of price of petrol statewise

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 = “”:

Longest and shortest line in a file:

def LongestShortestLine (name)


fd = open (name)
if fd != None:
line = [Link]()
maxline = line
minline = line
while line != "":
line = [Link]()
if line == "":
break
if len (line) > len(maxline):
maxline = line
if len (line) < len (minline)
minline = line

i/p file should be some txt file

>>> help ([Link]) Shows the file handling operation. Some of them are as follows:

Absolute path of a file:

>>> import [Link]

>>>

>>> [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.

>>> [Link] ("python")


False

>>> [Link] ("[Link]")

True

Here there is no file named as Python in my pwd so it returns False. If its there it shows True.

Join the input:

>>> [Link]("a", "b", "C")

'a\\b\\C'

If we give / as 2nd character in input then in output 1st charater is not shown.

>>> [Link]("i", "/","a", "b", "C")

'/a\\b\\C'

>>> >>> [Link]("i", "\","a", "b", "C")

SyntaxError: invalid syntax

isfile(path)

>>> [Link]("[Link]")

True

>>> [Link]("[Link]")

('python', '.exe')

Separates extension from file.

>>> help ([Link])

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.

Read full details in help.

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.

>>> import sys

>>> help ([Link])


Prog to copy source file to destination file by passing name of files as command line args.

#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

>>> import argparse

Name of file in this prog must not be argparse.

>>> parser = [Link]() …here object is created of parser

>>> parser.add_argument("-s", type=str, help="sourse file name") …how we want to define argument of source file

_StoreAction(option_strings=['-s'], dest='s', nargs=None, const=None, default=None, type=<class 'str'>, choices=None,


help='sourse file name', metavar=None)

>>> parser.add_argument("-d", type=str, help="dest file name") …how we want to define argument of destination file

_StoreAction(option_strings=['-d'], dest='d', nargs=None, const=None, default=None, type=<class 'str'>, choices=None,


help='destination file name', metavar=None)

>>> args = parser.parse_args()

Prog name in pycharm: [Link]

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)

Then to run this goto cmd and:

C:\Users\[Link]>C:\Users\[Link]\AppData\Local\Programs\Python\Python36\[Link] C:\Users\[Link]\
PycharmProjects\Test\[Link] -s source -d dest

source dest …this is source and destination file name


>>> import shutil

Prog name in pycharm= [Link]

#/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)

Then to run this go to cmd:

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.

WAP to demonstrate use of temp file module

>>> import tempfile

>>> x = [Link]() …file name is stored as x variable

>>> [Link](b"Hello") …Here it shows how many bytes are written in string. B for binary

5 … Here 5 bytes were written

>>> [Link](b"Helloworld")

10 ….Here we have 10 bytes written

>>> [Link]() …it tells where curser is, position of curser

>>> [Link](9)

b''

>>> [Link](0, 0)

0
>>> [Link](9)

b'Hello'

OBJECT ORIENTED PROGRAMMING

Class is human and amey is 1 of the instances. i.e. [Link]

There are 6 tubelights in classrooms so each tubelight is 1 instance of class electrical appliances.

Encapsulation: binding data and function which operate on data.

Walking is method or function of data human.

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.

It can be data or function abstraction.

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

wiz. Identity: - amey has a fixed Aadhar card no.

State: - static or dynamic state. If you do homework your state will change to intelligent.

Responsibility: - it is our responsibility or duty to do homework.

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.

These methods are called implicitely i.e. auomatically.

These methods are known as a manager methods

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.

Program name: OOPS1

#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: -

{'name': 'amey', 'address': 'Pune'}

{'name': 'ajay', 'address': 'Mumbai'}

Push Pop program: OOPS2

#/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

Enter your choice:1

enter data to push: 1

1. Push

2. Pop

3. Exit

Enter your choice:1

enter data to push: 2

1. Push

2. Pop

3. Exit

Enter your choice:1

enter data to push: 3

1. Push

2. Pop

3. Exit

Enter your choice:1

enter data to push: 4

1. Push

2. Pop

3. Exit

Enter your choice:1

enter data to push: 5

1. Push

2. Pop
3. Exit

Enter your choice:1

enter data to push: 6

1. Push

2. Pop

3. Exit

Enter your choice:1

enter data to push: 7

1. Push

2. Pop

3. Exit

Enter your choice:2

1. Push

2. Pop

3. Exit

Enter your choice:2

1. Push

2. Pop

3. Exit

Enter your choice:2

1. Push

2. Pop

3. Exit

Enter your choice:2

1. Push

2. Pop

3. Exit

Enter your choice:2

1
1. Push

2. Pop

3. Exit

Enter your choice:

Queue Implementation: OOPS3

First in 1st out:

#/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

enter data to push: 1

1. Enqueue

2. Dequeue

3. Exit

Enter your choice:1

enter data to push: 2

1. Enqueue

2. Dequeue

3. Exit

Enter your choice:1

enter data to push: 3

1. Enqueue

2. Dequeue

3. Exit

Enter your choice:1

enter data to push: 4

1. Enqueue

2. Dequeue

3. Exit

Enter your choice:2

1. Enqueue

2. Dequeue

3. Exit

Enter your choice:2

1. Enqueue

2. Dequeue

3. Exit

Enter your choice:2

1. Enqueue
2. Dequeue

3. Exit

Enter your choice:2

1. Enqueue

2. Dequeue

3. Exit

Understanding Private and Public:

Program name : OOPS4

#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()

o/p = 1100 1000

1000

(called private function)


WAP to simulate following linked list operation.

1. Insert at any position.


2. Delete based on position
3. Delete based on data
4. Search based on data
5. Count occurrence of given data

WAP to implement a bank account having following attributes:


Acc no, acc holder name, address, balance

Prog name: OOPS5

#/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:

Mail this file to:


imranisherecs@[Link]

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)

>>> [Link] ("a","amey")


<_sre.SRE_Match object; span=(0, 1), match='a'>
>>>
>>> [Link] ("a","xamey")
Here match checks 1st character and if found gives its start and end

>>> [Link] ("a","zamey")


<_sre.SRE_Match object; span=(1, 2), match='a'>
>>>
>>>
>>> [Link] ("a","zameyasgodse")
<_sre.SRE_Match object; span=(1, 2), match='a'>
Search method gives 1st occurrence only and not next occurrences.

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]()

for i in [Link]("^a",x,[Link] | [Link]):


print([Link](),[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.

Try programs with DOTALL and VERBOSE

. 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)

Searching ab at end of string:


>>> x = [Link] ("(a+b)$","hdhfhsababababdjfjdsfab")
>>> [Link](),[Link]()
(21, 23)
Searching ab at start of string:
>>> x = [Link] ("^(a+b)","abhdhfhsababababdjfjdsfab")
>>> [Link](),[Link]()
(0, 2)

\ 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 any lower case alphabate.


[a-zA-z0-9]+ means lower case alphabate and upper case alphabate and any number from 0 to 9 is allowed.
Here there is no separator in a-z and A-Z.

[^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

Write a regex for following pattern:


a followed by single b.
a followed by 0 or more b.
a followed by 1 or more b.
a followed by 1 or more b non greedy.
a followed by 3 bs
a followed by 5 to 10 b.

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

Sequence of only lower case letters [a-z]+


Sequence of only upper case [A-Z]+
Sequence of lower or upper case [a-zA-Z]+
Validating a start of sentence is with a capital letter or not. ^[A-Z]
Sequence of digits [0-9]+
Sequence of non digits [^0-9]+

\b matches empty string but only at the start or end of the word

All the words which contains t in them :


give pattern list to be searched: ["\\bt\w+"]
give input data: "ttas tata t as"
\bt\w+ 0 4 ttas
\bt\w+ 5 9 tata
Last word with t at the start of it:
give pattern list to be searched: ["\w+t\\b"]
give input data: "this is test"
\w+t\b 8 12 test

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: "))

ID = eval(input("give input data: "))

import re #this needs to be written to import regex

import re
for pattern in IP:

for match in [Link](pattern, ID, [Link]):

print(pattern, [Link](), [Link](), ID[[Link]():[Link]()])

Process finished with exit code 0

Prog to give o/p as a content in between “”” “””.


Prog regex7

#/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

This is src file

Serialization and deserialization


Read presentation from Python Masterpresentationpython_pickling
It serializes the data line by line and de-serializes the data line by line.

WAP to serialize employee objects and store them in a file.

EXCEPTION HANDLING:

Exception is used to handle the graceful termination of a program.


We can write our code when any error occurs then what should be done or what exactly error has occurred and we can notify
user that this error has occurred. And in that code we can write that if we get this error then we should close the program
gracefully and intimate the user before closing the program.

Try and except block:

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()

O/P: give commented examples to check output

Give numerator value: 20


Give Denominator value: 10
result:2.0
This else block of except is executed if there is no excption
This finally block gets executed no matter what is written above

Give numerator value: 20


Give Denominator value: 0
Denominator is zero
This finally block gets executed no matter what is written above

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

For user defined exception go to C:\Users\[Link]\Downloads\Python-master\Python-master\exception_handling and


read user_defined_exception.py

SUBPROCESS
Open command prompt at python masters directory.

>>> [Link]("copy",shell=True)
The syntax of the command is incorrect.
1

Here 1 is error code.

>>> 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

Here we will need import subprocess and time both modules.

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()

This prog is for windows. For linux use ps -eaf command

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.

Code is given in C:\Users\[Link]\Downloads\Python-master\Python-master\threadsinpython -> [Link]

Program: producer_consumer.py

from threading import Thread, Event


import time

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)

consumer = Thread(target=read, name="consumer")


producer = Thread(target=write, name="producer")
[Link]()
[Link]()

[Link]() # Wait for the threads to finish naturally


[Link]()
print
"done"

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

Read Modules and Packages in presentation

Lambda Generator:

#!/usr/bin/python

# Lambdas are useful for creating Anonymous Functions

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:

This function is under functools module in 3.x


Reduce is used when we want to take output of a previous calculation and use it as an input for next function.
Here we are supposed to do similar calculation multiple times on given range of data, then reduce is usefull.
Program : lambda3
#/usr/bin/python
import functools
def multiply(x,y):
print (x,y)
return x*y
print ([Link](multiply, range(1,10)))

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

You might also like