0% found this document useful (0 votes)
2 views

Pythonnotes

The document provides an extensive overview of Python programming, covering its features, syntax, data types, operators, control statements, loops, and functions. It includes examples of variable assignments, output statements, and various operations such as arithmetic and comparison. Additionally, it discusses data structures like lists, tuples, dictionaries, and arrays, along with exercises for practice.

Uploaded by

GOD OF AMW
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Pythonnotes

The document provides an extensive overview of Python programming, covering its features, syntax, data types, operators, control statements, loops, and functions. It includes examples of variable assignments, output statements, and various operations such as arithmetic and comparison. Additionally, it discusses data structures like lists, tuples, dictionaries, and arrays, along with exercises for practice.

Uploaded by

GOD OF AMW
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 28

Python

It is a cross-platform programming language


Developed by guido van rossum during 1985-1990.
Features -> Easy to learn, write, maintain, oops and Gui programming

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

Variable and Data Types

In python don’t need to declare variable


Data type
Int
long
float
complex
string

Rules for variable name


 empno=111
× emp no=111
 emp_no=111
 empno1=111
× 1empno=111
× emp.no=111
 employeenumber=111
× print=111

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

s1="csc computer education"


s2="villianur"
print s1
print s2
print s1+s2
print s1[0]
print s1[2:5]
print s1[:2]
print s1[2:]
print s1[-1]
print s1+ ' '+s2
print s2*2
print '-'*10

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

Convertion data types


a=5
print float(a)
b=5.6
print int(b)

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;

print 'Total mark = ' , tot


print 'Average mark = ' ,avg

output
enter eng mark = 98
enter tam mark = 98
enter maths mark = 99

Total mark = 295


Average mark = 98.3333333333

x=raw_input("enter character = ")


y=raw_input("enter name = ")
print x
print y

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

a=input("enter a value = ")


if a>0:
print 'given number is +ve'

If else statement

If <condition>:
Statements
else:
statements

a=input("enter a value = ")


b=input("enter b value = ")
if a>b:
print 'a is great'
else:
print 'b is great'

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

a=input("enter a value = ")


if a>0:
print "Given no is +ve"
else:
if a<0:
print "Given no -ve"
else:
print "Given no is zero"

Exercise:
 Great of 3 numbers

If elif statement

If <cond>:
Statements
elif <cond>:
statements
elif <cond>:
statements
--
else:
statements

a=input("enter a value = ")


if a>0:
print "Given no is +ve"
elif a<0:
print "Given no -ve"
else:
print "Given no is zero"

Exercise:

1) Find age status


Age<=5 -> child
6 to 12 -> boy/girl
13 to 20 -> teen age
21 to 50 -> middle age
>50 -> old age
2) Find bonus based on salary
Salary <=10000 -> 2000
10001 to 20000 ->3000
20001 to 30000 -> 4000
>30000 -> 5000
3) convert day of week from number to character

While loop

While <condition>:
Statements

a=1
while a<=5:
print "csc"
print "villianur"
a=a+1

while with else


a=1
while a<=5:
print a
a=a+1
else:
print "end"
print "Thank you"

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 <variable> in <range/sequence>:


statements

range(st value, end value, step value)

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

break and continue statement

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:

 Find given no is prime/not


 Print prime no upto 100
 Print fibnocci series
 Sum the digits 457 – 16
 Print the digits
 Reverse the no.
 Print only odd nos from list
 Sum the list

Sequences

LIST

List is an ordered sequence of different type of item


It is given within []

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

""" other function


print a.index(20)
print a.count(20)
print len(a)
print max(a)
print min(a)
a.sort()
print a
a.reverse()
print a """

Tuple

tuple is an ordered sequence of different type of item like a list


Item cannot be alter(immutable)
It is given within ()

a=(10,20,30,40)
print a[1]=99  error

Dictionary

Collection of unordered collection os key-value pairs


Key:value

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

from array import *


typecode -> i –int, f – float, l –long , d –double, c- char

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)

Convert array to string, list

b=array('c',['r','a','j','a'])
print b.tostring()
c=b.tolist()
print c

Function

Types
 Udf
 Buit in function

Udf (user defined function)

def functionname(parameter1,para2,arg3,…):
-----

-----
-----
Functionname(para1, arg2,..)

#example without parameter and without return value


def display():
print 'csc welcomes you'
print 'villianur'

print 'hello student'


display()
print 'thank you'

output
hello student
csc welcomes you
villianur
thank you

#example with parameter and no return value


def add(a,b):
print a+b
def sub(a,b):
print a-b
def mul(a,b):
print a*b
def div(a,b):
print a/b

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

#example with parameter and with return value


def great(a,b):
if a>b:
g=a
else:
g=b
return(g)

a=10
b=3
c=great(a,b)
print c
print great(67,89)
print 'thank you'

output
10
89
thank you

#example without parameter and with return value


def great():
a=input("Enter a value = ")
b=input("Enter b value = ")
if a>b:
g=a
else:
g=b
return(g)

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

#function to find vowels


def vowel(st):
v=0
for i in st:
if i=='a' or i=='e' or i=='i' or i=='o' or i=='u':
v=v+1
return(v)

st=input("enter name = ")


print 'No of vowels = ', vowel(st)

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

Function with default argument

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

Formal and arbitary argument

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

n=input("enter n value = ")


print 'factorial of ',n, ' is ', fact(n)

output
enter n value = 5
factorial of 5 is 120

Files

It is used to store data permanently


To Open
f=open(filename,mode)
mode -> r, w,a, bw,br,r+,w+

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

print f.readline() -> print first line


print f.readlines() -> print remaining lines

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

enter two values = 10 3


comma is missing

enter two values = 10,0


Dont divide by zero

enter two values = 10,y


wrong input

try:
f=open("star.txt","r")
print f.read()
f.close()
except IOError:
print 'file not found'

user defined exception

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

You might also like