Pythonnotes
Pythonnotes
Output statement
x=10; y="raja"
print "age = ",x
print "name = ",y
print x,y
multiline statement
a=10+20+\
50+10+\
20
print a
or using (), []
a=(10+20+
50+10+
20)
print a
a=['raja','mani',
'bala']
print a
comment
non exicutable statement
# sample prg
Multiline
“”” sample prg
For if stat “””
value assingment
a=5
b=7.2
c=’raja’
print a,b,c
a,b,c=5,7.2,’raja’
print a,b,c
multiple assignment
a=b=c=100
print a,b,c
output
csc computer education
villianur
csc computer educationvillianur
c
cc
cs
c computer education
n
csc computer education villianur
villianurvillianur
----------
a=5
print (a, " type is ", type(a))
b=7.2
print (b, "type is ",type(b))
output
(5, ' type is ', <type 'int'>)
(7.2000000000000002, 'type is ', <type 'float'>)
c='5.6'
#print c +5
print float(c)+5
d=45
#print 'age ' + d
print 'age ' + str(d)
output
5.0
5
10.6
age 45
Output Statement
print('hello world')
print("good")
print "happy"
print 'nice'
a=25
print a
print 'age = ' , a
print (1,2,3,4)
b=(5,6,7,8)
print b
output
hello world
good
happy
nice
25
age = 25
(1, 2, 3, 4)
(5, 6, 7, 8)
Input
m1=input('enter eng mark = ')
m2=input('enter tam mark = ')
m3=input('enter maths mark = ')
tot=m1+m2+m3
avg=tot/3.0;
output
enter eng mark = 98
enter tam mark = 98
enter maths mark = 99
output
enter character = y
enter name = muthu
y
muthu
Operators
Arithmatic
+
-
*
/
% -remainder
// - rounded value
** - power
a=15
b=4
print 'a+b = ',a+b
print 'a-b = ',a-b
print 'a*b = ',a*b
print '10/3 = ',10/3.0
print 'a%b = ',a%b
print '10//3 = ',10//3.0
print 'a**b = ',a**b
output
a+b = 19
a-b = 11
a*b = 60
10/3 = 3.33333333333
a%b = 3
10//3 = 3.0
a**b = 50625
comparison(Realation) operator
>
<
>=
<=
==
!=
a=15
b=4
print 'a>b = ', a>b
print 'a<b = ', a<b
print 'a>=b = ', a>=b
print 'a<=b = ', a<=b
print 'a==b = ', a==b
print 'a!=b = ', a!=b
output
a>b = True
a<b = False
a>=b = True
a<=b = False
a==b = False
a!=b = True
Assignment Operato
=
+=
-=
*=
/=
%=
//=
**=
Logical operator
and, or, not
Special operator
Is
Is not
a=15
b=15
c='raja'
d='raja'
print a is b
print a is not b
print c is d
print c is not d
output
True
False
True
False
Membership operator
In
not in
a='hello world'
b={1:'a',2:'b'}
print 'h' in a
print 'h' not in a
print 'H' in a
print 1 in b
print 'a' in b
output
True
False
False
True
False
Exercise:
Find Area of rectangle
Find Area of circle
Get loan amt, interest rate, no of year, find due amt
Control statement
Contitional statement
If statement
If else statement
If elif statement
Nested if statement
Loop statement
While loop
For loop
If statement
If <Condition>:
Statements
If else statement
If <condition>:
Statements
else:
statements
Exercise:
Given no is +ve/-ve
Given no is odd/even
Given two numbers are same/not
Given age is eligible for voter/not
Given character is vowel or not
Given age is teen age or not
Get 3 marks, Find Total, average, result
Nested if statement
Exercise:
Great of 3 numbers
If elif statement
If <cond>:
Statements
elif <cond>:
statements
elif <cond>:
statements
--
else:
statements
Exercise:
While loop
While <condition>:
Statements
a=1
while a<=5:
print "csc"
print "villianur"
a=a+1
output
1
2
3
4
5
end
Thank you
Exercise:
Print 1,2,3,…..10
Print 1,2,3,…..n
Print 1,3,5,….n
Print 2,4,6,….n
Print 10,9,8,…1
Sum 1+2+3….n
Sum 1+3+5….n
Find factorial 1*2*3….n
Sum 1-2+3-4+5-6….100
for loop
for a in range(1,10,):
print a
output -> 1 to 9
for a in range(1,10,2):
print a
output -> 1 3 5 7 9
for a in range(2,10,2):
print a
output -> 2 4 6 8
for a in range(10,0,-1):
print a
output -> 10 9 8 .. 1
sequence(string,list,tuple,dictionary,array)
for a in "csc":
print a
output
c
s
c
a=[10,20,30,40,50,7.2,'csc']
for i in a:
print i
output
10
20
30
40
50
7.2
csc
for a in range(1,11,1):
if a==5: continue
print a
if a==7:
break
else:
print "end"
print "Thank you"
output
1
2
3
4
6
7
Thank you
.0
Exercise:
Sequences
LIST
a=[10,20,3.3,4.5,7.3,"csc","villianur"]
"""print a
print a[1]
print a[:3]
print a[3:]
print a[2:4]
print a[:]
print a[-1] """
""" change
a[0]=5
print a
a[1:4]=[6,7,8]
print a """
""" add
a.append(10)
print a
a.extend([7,8,8])
print a
a.insert(1,55)
print a
a[2:2]=[77,88]
print a """
""" delete
del a[2]
print a
del a[1:4]
print a
del a
a.remove("csc")
print a
a.pop(1)
print a """
Tuple
a=(10,20,30,40)
print a[1]=99 error
Dictionary
a={1:'sun',2:'moon','sky':100}
print a
print ("a[1] = ", a[1])
print ("a[2] = ", a[2])
print ("a['sky'] = ", a['sky'])
print ("a[100] = ", a[100])
output
{1: 'sun', 2: 'moon', 'sky': 100}
('a[1] = ', 'sun')
('a[2] = ', 'moon')
("a['sky'] = ", 100)
Traceback (most recent call last):
File "D:\soft\sara\ex2", line 6, in -toplevel-
print ("a[100] = ", a[100])
KeyError: 100
ARRAY
Collection of same type values
ar=array('i',[5,10,15,20,25])
for b in ar:
print b
print ar[2]
add
ar.append(30)
print ar
ar.insert(0,40)
print ar
ar2=array('i',[30,35,40,45])
ar.extend(ar2)
print ar
c=[40,45,50]
ar.fromlist(c)
print ar
delete
ar.remove(10)
print ar
ar.pop()
ar.pop(1)
print ar
other function
print ar.index(10)
ar.reverse()
print ar
print ar.count(10)
b=array('c',['r','a','j','a'])
print b.tostring()
c=b.tolist()
print c
Function
Types
Udf
Buit in function
def functionname(parameter1,para2,arg3,…):
-----
-----
-----
Functionname(para1, arg2,..)
output
hello student
csc welcomes you
villianur
thank you
a=10
b=3
add(a,b)
sub(a,b)
mul(a,b)
div(a,b)
add(5,5)
add(a,5)
print 'thank you'
output
13
7
30
3
10
15
thank you
a=10
b=3
c=great(a,b)
print c
print great(67,89)
print 'thank you'
output
10
89
thank you
c=great()
print c
print great()
print 'thank you'
output
Enter a value = 6
Enter b value = 8
8
Enter a value = 99
Enter b value = 33
99
thank you
output
enter name = 'computer'
No of vowels = 3
Exercise:
Write function for swap two numbers
Write function for factorial
Write function to find simple interest Si=pnr/100
def sum(x=10,y=20,z=30):
return(x+y+z)
print sum(5,5,5)
print sum(5,5)
print sum(5)
print sum()
output
15
40
55
60
Arbitary arguments
def display(*x):
for na in x:
print "hello ",na
display('raja','mani','muthu','arun')
output
hello raja
hello mani
hello muthu
hello arun
def display(x,*y):
print 'formal arg ' ,x
for na in y:
print "another arg ",na
display('raja','mani','muthu','arun',5000)
output
formal arg raja
another arg mani
another arg muthu
another arg arun
another arg 5000
Recursion function
def fact(x):
if x==1:
return 1
else:
return(x*fact(x-1))
output
enter n value = 5
factorial of 5 is 120
Files
Read
f=open(“first.txt”,”r”)
print f.read(5) -> print first 5 char from first.txt
print f.read() - >print remaining char from first.txt
f.seek(0) -> move cursor to starting position of file
print f.tell() print cursor position of file
for i i
print i
Read line by line
To close
f.close()
Write
f=open(“second.txt”,”w”)
f.write(“csc\n”)
f.write(“computer\n”)
f.write(“education\n”)
f=open("abc.txt","w")
ch='y'
while ch=='y':
x=raw_input("Enter name = ")
f.write(x + "\n")
ch=raw_input("continue = ")
f.close()
Binary files
Using dictionary
import pickle
f=open("stud.dat","w")
c={1001:['raja','dca',7500],1002:['mani','hdca',12500]}
pickle.dump(c,f)
f.close()
f1=open("stud.dat","r")
c1=dict(pickle.load(f1))
f1.close()
r =input("Enter no = ")
for id,cc in c1.items():
if id==r:
print 'name = ', cc[0]
print 'balance fees = ' , cc[2]
amt=inp c1[id]=[cc[0],cc[1],cc[2]-amt]
f1=open("stud.dat","w")
print c1
pickle.dump(c1,f1)
f1.close()
output
Enter no = 1001
name = raja
balance fees = 7500
E nter amount = 2500
{1001: ['raja', 'dca', 5000], 1002: ['mani', 'hdca', 12500]}
using List
import pickle
f=open("stud1.dat","w")
c=[[1001,'raja','dca',7500],[1002,'mani','hdca',12500]]
pickle.dump(c,f)
f.close()
f1=open("stud1.dat","r")
c1=list(pickle.load(f1))
f1.close()
r=int(input("Enter no = "))
for i in c1:
if i[0]==r:
print 'name = ', i[1]
print 'balance fees = ' , i[3]
amt=input("Enter amount = ")
i[3]=i[3]-amt
break;
print c1
f1=open("stud1.dat","w")
pickle.dump(c1,f1)
f1.close()
output
Enter no = 1001
name = raja
balance fees = 7500
Enter amount = 2500
[[1001, 'raja', 'dca', 5000], [1002, 'mani', 'hdca', 12500]]
Directory
import os
print os.getcwd()
os.chdir('d:\\anbu')
print os.getcwd()
print os.listdir('d:\\tani')
os.mkdir('sun')
os.rename('sun','moon')
os.remove('abc.txt')
os.rmdir('moon') #rmdir removes only empty directry
to remove non-empty directry use rmtree in shutil module
import shutil
shutil.rmtree('sun')
exception
error(syntax,logic,runtime)
try:
stataments
except exp1:
statements
except exp2:
statements
else:
statements
try:
a,b=input("enter two values = ")
c=a/b
print c
except ZeroDivisionError:
print 'Dont divide by zero'
except SyntaxError:
print 'comma is missing'
except:
print 'wrong input'
else:
print 'no error'
output
enter two values = 10,3
3
no error
try:
f=open("star.txt","r")
print f.read()
f.close()
except IOError:
print 'file not found'
class MyError(Exception):
pass
class ZeroValueError(Exception):
pass
try:
n=input("enter n value = ")
if n==0:
raise ZeroValueError
if n<0:
raise MyError
else:
print n
except MyError:
print 'Give positive no'
except ZeroValueError:
print 'Dont give zero'
output
enter n value = 5
5
enter n value = 0
Dont give zero
enter n value = -3
Give positive no