Skip to content

Python Programing

Starting the interpreter (Interpreter mode) :-

/usr/local/bin/python   (Unix – depends on install pat)

c:\Python27\python     (Windows – depends on install path)

C:\Python27>python

Python 2.7.7 (default, Jun  1 2014, 14:17:13) [MSC v.1500 32 bit (Intel)]

Win 32

Type “help”, “copyright”, “credits” or “license” for more information.

>>>                                  (>>> interpreter mode)

File Mode :-

Created welcome.py in python install directory (C:\Python27) and executed below command

C:\Python27>python welcome.py          (If in different path than need to give complete                                                                              path/need to set PYTHONPATH)

welcome to python

C:\Python27>

NOTE :- Like wise you can create code in .py file and execute using above command

Python IDLE :-

Python Integrated Development Environment (IDLE) usually comes with python installation, it’s an interpreter mode working tool and can be used to do python programing

NOTE :- We will execute all programing aspects from here through interpreter mode. Same code can be copied and executed through file mode

NOTE :- Executing 2.7.X style of code, Python 3 has very minor differences in coding style. You can check in our python2 vs python3 tutorial

Printing to console in Python :-

>>> print “welcome to python”

welcome to python

>>>

>>> print welcome                (Here welcome is considered as variable. If not variable we                                                          need to use quotes as above)

Traceback (most recent call last):

File “<pyshell#3>”, line 1, in <module>

print welcome

NameError: name ‘welcome’ is not defined

>>>

Identifiers & assignment :-

>>> a=1        (a is identifier for which value 1 is assigned)

>>> a             (prints the variable 1)

1

>>> print a         (prints the variable 1 since a is defined unlike above where welcome                                        not defined)

1

>>> type(a)        (displays type of variable a)

<type ‘int’>

Statements :-

>>> a=1

>>> print “I am statement”       (Upon going to new line it’s a statement)

I am statement

Multi Line Statements :-

>>> print “h” \   (Need to use \ symbol for multiline)

“i” \

Comments :-

>>> print “hi”   #printing hi   (after # statement is considered as comment so it is not                                                                  printed)

hi

>>>

Multiline Comments :-

#This is a long comment         (Typing statements after # one line after another)
#and it extends
#to multiple lines

Indentation :-

>>> if 1:                    (Blocks like if/for/functions etc block are represented by Indentation                                       unlike C/C++ which use braces)

print “hi”

Hi

>>> if 1:

print “hi”

print “welcome to python”

print “all the best”

 

hi

welcome to python

all the best

>>>

DataTypes :-

NOTE :- type() displays type of the variable and also complete information on datatypes can be found in our tutorial

NOTE :- Below a is variable

>>> a=1          (integer type likewise you can assign float 1.0, long 1L etc)

>>> type(a)

<type ‘int’>

 

>>> a=”hi”       (String type)

>>> type(a)

<type ‘str’>

 

>>> a=[1,2,3,4]       (List type)

>>> type(a)

<type ‘list’>

 

>>> a=(3,4,5)         (Tuple type)

 

>>> type(a)

<type ‘tuple’>

 

>>> a={1,2,3,”h”}    (Set type)

>>> type(a)

<type ‘set’>

 

>>> a={1:2, “r”:5}      (Dictionay type)

>>> type(a)

<type ‘dict’>

 

Accessing Values of variable :-

NOTE :- (Accessing can be done by calling variable name, indexing for sequence or printing it through print function as below)

>>> a=1.0        (Numeric value int/float/long etc)

>>> print a

1.0

>>> a=”hello”     (String value)

>>> print a

hello

>>> a

‘hello’

>>> a[0]          (String indexing like a[0])

‘h’

>>> a[0:2]       (Slicing like a[0:2])

‘he’

>>> a[-1]         (Negative indexing also possible but print from last)

‘o’

>>> a[-1:-3]      (Not printing anything – Reverse slicing is not getting printed)

>>> a[-1:-2]

>>> a[-2]

‘l’

>>> a[-3:-1]

‘ll’

>>> print a[3]

l

>>> a=[3,4,”hi”]    (List value)

>>> a

[3, 4, ‘hi’]

>>> print a

[3, 4, ‘hi’]

>>> a[0]         (List indexing)

3

>>> a[1:2]        (List slicing)

[4]

>>> a[0:2]

[3, 4]

>>> a[-1]            (Negative indexing)

‘hi’

>>> a[-1:-3]

[]

>>> a[-3:-1]       (Negative slicing)

[3, 4]

 

>>> print a[0]

3

>>> print a[-3:-1]

[3, 4]

>>> a=(4,5,”hi”)           (Tuple value)

>>> a

(4, 5, ‘hi’)

>>> print a

(4, 5, ‘hi’)

>>> a[1]                      (Accessing tuple value)

5

>>> a[0:2]                 (Tuple slicing)

(4, 5)

>>> a[-1]                     (Negative index and slicing)

‘hi’

>>> a[-3:-1]

(4, 5)

 

>>> print a[1]

5

>>> print a[-3:-1]

(4, 5)

 

>>> a={4,5,”y”}    (Set value)

>>> a[1]                                          (Set indexing is not possible. Please check our tutorial)

Traceback (most recent call last):

File “<pyshell#166>”, line 1, in <module>

a[1]

TypeError: ‘set’ object does not support indexing

>>> a

set([‘y’, 4, 5])

>>> a.add(6)                     (add() is set method to add value to set)

>>> a

set([‘y’, 4, 5, 6])

>>> a={1:2,”t”:”Y”,5:”hi”}                 (dictionary value)

>>> a

{1: 2, ‘t’: ‘Y’, 5: ‘hi’}

 

>>> print a

{1: 2, ‘t’: ‘Y’, 5: ‘hi’}

>>> a[1]                         (Dictionary indexing can be done through keys)

2

>>> a[‘t’]

‘Y’

>>> a[t]                       (variable should be either declared or need to be given in quotes or                                         else it throws error as below)

Traceback (most recent call last):

File “<pyshell#188>”, line 1, in <module>

a[t]

NameError: name ‘t’ is not defined

>>> a[5]

‘hi’

>>> a[1:5]                    (Dictionary Slicing – Requires to write program for the same)

Traceback (most recent call last):

File “<pyshell#194>”, line 1, in <module>

a[1:5]

TypeError: unhashable type

Input & Output :-

>>> print “hi”              (print() o/ps value or string into console)

hi

 

>>> ip = input(“enter the value”)           (input() accepts input from keyboard)

enter the value 4

>>> ip

4

 

>>> ip = raw_input(“enter the value”)              (raw_input() accepts input from keyboard)

enter the value “tt”

>>> ip

‘ “tt”‘

NOTE :- Input vs raw_input please check our tutorial

Import :-

>>> import os            (Here import keyword is used to import os built-in module)

>>> os.name          (After importing we can access its attribute/methods. Similarly there are lot of modules like sys etc)

‘nt’

>>> os.path

<module ‘ntpath’ from ‘C:\Python27\lib\ntpath.pyc’>

>>> import sys

>>> sys.copyright

‘Copyright (c) 2001-2014 Python Software Foundation’

>>> import random

>>> random.random()

0.6432874634400966

Output Formatting :-

NOTE :-  format() is used to pass string, numeric values, variables etc

>>> “welcome.{}”.format(“to”)

‘welcome.to’

>>> print “{},{},{}”.format(1,2,”kk”)

1,2,kk

>>> print “{2} {1} {0}”.format(1,2,”kk”)

kk 2 1

>>> print “welcome to %s” % “python”   (Old style formatting)

welcome to python

>>> a=7

>>> print “welcome to %d” % a   (Old style formatting)

welcome to 7

>>> “welcome.{}”.format(a)

‘welcome.7’

NOTE :- complete information of formatting can be found in our tutorial

Operators :-

>>> a=5

>>> b=6

>>> a+b    (Arithmetic Operator like wise you can do for – , *, / etc)

11

>>> a-b

-1

>>> a<b       (Comparison operator. True since a<b)

True

>>> a>b

False

>>> x=10

>>> y=4

>>> x&y       (operate on bits 1010 like that)

0

>>> a+=b     (Assignment operator)

>>> a

11

>>> h=1

>>> b=1

>>> h is b   (identity operator True sine both are pointing to same object)

True

>>> id(h)    (id() displays identity of object)

20774736

>>> id(b)

20774736

>>> h is not b

False

>>> f=1

>>> g=5

>>> f is g   (Both are not pointing to same object)

False

>>> f is not g

True

>>> L=[5,6,7,”h”]

>>> 5 in L          (membership test since 5 in is in L)

True

>>> 10 in L

False

>>> 5 not in L

False

>>> n=True

>>> m=False

>>> n and m    (True if both operands are True)

False

>>> n or m

True

>>> not m

True

>>>

NOTE :- Try 0 and 1 for and,or,not operator

If-else :-

>>> a=6

>>> if a:     (non zero and None, other values are considered as true)

print “h”

h

>>> a=0       (Not printed since 0 is considered as false)

>>> if a:

print “h”

>>> a=”hello”

>>> if a[1]==’e’:        (a[1] is e)

print “hello”

hello

>>> if a[1]==’f’:     (else statement is printed since a[1] is not f)

print “if”

else:

print “else”

else

>>> if a[1]==’f’:    (elif 2 is printed is it satisfies a[1]=’e’)

print “if”

elif a[1]==’z’:

print “elif”

elif a[1]==’e’:

print “elif 2”

elif 2

>>>

>>> if a[1]==’f’:    (else is printed since either if nor elif satisfies condition)

print “if”

elif a[1]==’z’:

print “elif”

elif a[1]==’o’:

print “elif 2”

else:

print “else”

else

>>>

NOTE :- Here print statement are intended and elif, else is considered to be align with if statement

for and else statement :-

>>> a

‘hello’

>>> for i in a:    (loop through a and printing i)

print i

h

e

l

l

o

 

>>> for i in range(len(a)):  (range generates list of numbers, len gives length of the string)

print i,a[i]

0 h

1 e

2 l

3 l

4 o

>>>

>>> for i in a:      (print “hello” twice since ‘l’, ‘l’ occurs twice in “hello”)

if i==’l’:

print a

hello

hello

>>>

>>> for i in a:         (print “else” since p is not available in “hello”)

if i==’p’:

print a

else:

print “else”

else

>>>

While and else loop :-

>>>

>>> while a[1]==’e’:  (No expression and also condition always returns true, so continues                                        infinite loop)

print a

 

hello

hello

hello

hello

hello

Hello

KeyboardInterrupt

>>>

>>> a=5

>>> i=0

>>> while i<=a:   (Expression and condition matches so print 5 times)

print a

i+=1

 

5

5

5

5

5

5

>>> i

6

>>>

>>> while i<=a:   (Since i=6 after above example else is printed)

print a

i+=1

else:

print “else”

else

>>> i=0

>>> while i<=a:   (I becomes 0, so both a and else is printed)

print a

i+=1

else:

print “else”

 

5

5

5

5

5

5

else

>>>

Break and Continue :-

>>> a

‘hello’

>>> for i in a:  (After encountering break come out of the loop, so only ‘h’ is printed)

print i

break

 

h

 

>>> for i in a:    (Whereas continue – continues to loop, so ‘hello’ is printed)

print i

continue

 

h

e

l

l

o

>>>

NOTE :- One more clear example below

>>> for i in a:

if i==’e’:   (Only prints ‘e’ when i become ‘e’)

print I

e

>>> for i in a:

if i==’e’:   (Only prints ‘h’ since it comes out of loop after i becomes ‘e’)

break

print i

h

>>> for i in a:

if i==’e’:    (prints ‘h l l o’ jumps to for loop when continue is encountered after i becomes ‘e’, so ‘e’ is not printed)

continue

print i

h

l

l

o

>>>

Pass Statement :-

>>> class b:              (Pass generally used as placeholder)

pass

 

>>> class b:

 

KeyboardInterrupt

>>>

>>> def func():

pass

 

>>>

>>> def func():

 

KeyboardInterrupt

>>>

 

Functions :-

>>> def func():

print “hi”

>>> func()

hi

 

>>> def f(a,b):

c=a+b

return c

>>> f(10,20)

30

>>> def f(a,b):

return a+b

>>> f(4,5)

9

>>>

>>> def f2(a,b):

“””This function returns the absolute

value of the entered number”””

return a+b

>>> f2.__doc__

This function returns the absolute\n\tvalue of the entered number’

 

Default arguments function :-

>>> def f3(a=5,b):    (non-default argument should not follow default one)

return a+b

SyntaxError: non-default argument follows default argument

>>>

>>> def f3(a,b=3):

return a+b

>>> f3(4)     (Only non-default value is provided)

7

>>> f3(5,6)  (Overwrite default value)

11

>>>

>>> f3()     (at least one argument required since one is non default)

Keyword Argument function :-

>>> def f4(a,b):

return a+b

>>> f4(a=4,b=7)   (Passing values while calling)

11

>>>

>>> f4(6,6)

12

>>>

>>> f4(1,b=3)

4

>>>

>>> def f5(a,b=4):    (b has default value)

return a+b

>>> f5(4)

8

>>>

>>> f5(a=5,b=7)

12

>>>

>>> f5(b=0,a=6)

6

>>>

>>> f5(b=8)   (a value needs to be passed)

 

Traceback (most recent call last):

File “<pyshell#752>”, line 1, in <module>

f5(b=8)

TypeError: f5() takes at least 1 argument (1 given)

 

>>> f5(b=8, 9)     (Python will not be knowing which value to assign to which variables after keyword arg)

SyntaxError: non-keyword arg after keyword arg

>>>

Arbitrary Arguments :-

 

>>> def f10(*a):    (To print lot of variables at a time (tuple))

print a

>>> f10(1,2,3)

(1, 2, 3)

>>> def f11(*a):    (To get the individual items

for i in a:

print i

>>> f11(3,4,5)

3

4

5

>>> def f8(**a):   (To print key-value pair, dictionary)

print a

>>> f8(name=”ss”, bb=”kk”, yy=8, uu=89)

{‘yy’: 8, ‘uu’: 89, ‘name’: ‘ss’, ‘bb’: ‘kk’}

>>>

>>> def f7(**a):                (To print individual items of dictionary)

for i,v in a.iteritems():

print i,v

>>> f7(name=”ss”, bb=”kk”, yy=8, uu=89)

yy 8

uu 89

name ss

bb kk

>>>

>>> def f13(arg1, arg2, arg3):

print “arg1:”, arg1

print “arg2:”, arg2

print “arg3:”, arg3

>>> dict={“arg3”: 3, “arg2”: “two”,”arg1″:5}

>>> f13(**dict)                 (Using **dict and *k in function call)

arg1: 5

arg2: two

arg3: 3

 

>>> f13(*k)

arg1: 1

arg2: 2

arg3: 3

 

Recursion Function :-

>>> def rec(a):   (Calling same function again & again in function definition)

if a==1:

return 1

else:

return (a * rec(a-1))

 

>>> a=3

>>> rec(a)

6

>>> a=a

>>> rec(4)

24

>>>

Lambda Functions :-

>>> double = lambda x: x * 2

>>> double(5)

10

>>>

>>> (lambda x:5+1)(10)   (Called without any identifier)

6

>>> (lambda x:10+1)(10)

11

>>> my_list

[1, 5, 4, 6, 8, 11, 3, 12]

>>> new_list = list(filter(lambda x: (x%2 == 0) , my_list))   (Return items from list which                                                                                                               are true for condition)

>>> new_list

[4, 6, 8, 12]

>>> new_list = list(map(lambda x: (x%2 == 0) , my_list))  (Returns items which are changed by condition)

>>> new_list

[False, False, True, True, True, False, False, True]

>>> (lambda x: (x%2 == 0)) (my_list)     (Error – condition didn’t applied for individual                                                                               items of list)

 

Traceback (most recent call last):

File “<pyshell#1006>”, line 1, in <module>

(lambda x: (x%2 == 0)) (my_list)

File “<pyshell#1006>”, line 1, in <lambda>

(lambda x: (x%2 == 0)) (my_list)

TypeError: unsupported operand type(s) for %: ‘list’ and ‘int’

>>

Type Conversion :-

>>> a=5

>>> str(5)

‘5’

>>> a

5

>>> g=str(a)

>>> g

‘5’

>>> int(a)

5

>>> h=”ss”

>>> int(h)  (Non numeric value is not converted to

Traceback (most recent call last):

File “<pyshell#16>”, line 1, in <module>

int(h)

ValueError: invalid literal for int() with base 10: ‘ss’

>>> float(a)

5.0

More on string operation :-

>>> a=”hello”

>>> a[0]

‘h’

>>> a[0]=t                    (Assignment is not possible in string)

Traceback (most recent call last):

File “<pyshell#37>”, line 1, in <module>

a[0]=t

NameError: name ‘t’ is not defined

>>> a[0]=”t”

Traceback (most recent call last):

File “<pyshell#40>”, line 1, in <module>

a[0]=”t”

TypeError: ‘str’ object does not support item assignment

>>> a

‘hello’

>>> del a

>>> a

Traceback (most recent call last):

File “<pyshell#51>”, line 1, in <module>

a

NameError: name ‘a’ is not defined

>>> a=”tt”

>>> b=”yy”

>>> a+b

‘ttyy’

>>> f=”hello”

>>> for i in f:     (Printing individual elements)

print i

 

h

e

l

l

o

>>> for i in range(len(f)):

print i, f[i]

 

0 h

1 e

2 l

3 l

4 o

>>> h

‘ss’

>>> a

‘tt’

>>> f

‘hello’

>>> enumerate(f)

<enumerate object at 0x01FE9A30>

>>> for i in enumerate(f):   (return index and value)

print i

 

(0, ‘h’)

(1, ‘e’)

(2, ‘l’)

(3, ‘l’)

(4, ‘o’)

>>> d=”abc\ncc”

>>> d

‘abc\ncc’

>>> print “abc\ncc”

abc

cc

>>> print r”abc\ncc”  (raw string ‘r’ will igonre escape sequence)

abc\ncc

>>> d.upper()               (upper & find are methods)

‘ABC\nCC’

>>> d.find(‘a’)

0

>>> d.find(‘j’)

-1

>>> d.find(‘c’)

2

>>> d.find(‘b’)

1

>>>

NOTE :- More on string methods can be found in our tutorial

Bit more on List :-

>>> L=[3,4,5,6]

>>> L[1]=’t’    (Updating List value)

>>> L

[3, ‘t’, 5, 6]

>>> L.append(‘yy’)

>>> L

[3, ‘t’, 5, 6, ‘yy’]

>>> del L[2]

>>> L

[3, ‘t’, 6, ‘yy’]

>>> del L[0:2]

>>> L

[6, ‘yy’]

>>> del L                   (Deleting entire list)

>>> L = [5,6,7,’uu’]

>>> L.pop()                   (pop() will remove item and return it)

‘uu’

>>> L.pop()

7

>>> L

[5, 6]

>>> L = [x for x in range(6)]      (List comprehension)

>>> L

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

>>> L = [x for x in range(20) if x%2==0]            (List comprehension with if statement)

>>> L

[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

>>> l = [x for x in range(20) if x%2==0 print x]            (Print not allowed with if]

SyntaxError: invalid syntax

>>> for i in L:      (Iterating for loop)

print i

 

0

2

4

6

8

10

12

14

16

18

 

NOTE :- Built in functions and list methods can be found in our tutorial

Bit more on tuples :-

>>> t=(3,4,5,6)

>>> t

(3, 4, 5, 6)

>>> t[0]=2     (Assignment is not possible)

Traceback (most recent call last):

File “<pyshell#206>”, line 1, in <module>

t[0]=2

TypeError: ‘tuple’ object does not support item assignment

>>> t

(3, 4, 5, 6)

>>> for i in t:            (Iterating individual items)

print i

 

3

4

5

6

>>> del t[0]            (deleting individual item not possible)

Traceback (most recent call last):

File “<pyshell#223>”, line 1, in <module>

del t[0]

TypeError: ‘tuple’ object doesn’t support item deletion

>>> del t            (deleting entire list)

>>> t=3,             (Single item list)

>>> t

(3,)

Bit more on Set ;-

>>> s=set(1,2,3,4)           (Accepts single argument)

 

Traceback (most recent call last):

File “<pyshell#234>”, line 1, in <module>

s=set(1,2,3,4)

TypeError: set expected at most 1 arguments, got 4

>>> L=[1,2,3,4]

>>> s

set([1, 2, 3, 4])

>>> s[0]=’t’                       (Assignment not supported)

Traceback (most recent call last):

File “<pyshell#249>”, line 1, in <module>

s[0]=’t’

TypeError: ‘set’ object does not support item assignment

 

>>> s.add(‘t’)            (add() to add element)

>>> s

set([1, 2, 3, 4, ‘t’])

>>> s.update(L)

>>> s

set([1, 2, 3, 4, ‘t’])       (discard and remove to remove elements)

>>> s.discard(2)

>>> s

set([1, 3, 4, ‘t’])

>>> s.remove(3)

>>> s

set([1, 4, ‘t’])

>>> s.remove(6)         (remove raises keyerror if item is not present unlike discard)

Traceback (most recent call last):

File “<pyshell#274>”, line 1, in <module>

s.remove(6)

KeyError: 6

>>> s.discard(6)

>>> s

set([1, 4, ‘t’])

>>> s.pop()

1

>>> s

set([4, ‘t’])

>>> A = {1, 2, 3, 4, 5}

>>> B = {4, 5, 6, 7, 8}

>>> A and B                       (set operations)

set([8, 4, 5, 6, 7])

>>> print(A | B)

set([1, 2, 3, 4, 5, 6, 7, 8])

>>> A.union(B)

set([1, 2, 3, 4, 5, 6, 7, 8])

>>> frozenset(1,4,5,6)

Traceback (most recent call last):

File “<pyshell#299>”, line 1, in <module>

frozenset(1,4,5,6)

TypeError: frozenset expected at most 1 arguments, got 4

>>> L

[1, 2, 3, 4]

>>> frozenset(L)                          (Forzenset creation)

frozenset([1, 2, 3, 4])

>>> h=frozenset(L)

>>> h

frozenset([1, 2, 3, 4])

>>> h[2]=’j’

Traceback (most recent call last):

File “<pyshell#311>”, line 1, in <module>

h[2]=’j’

TypeError: ‘frozenset’ object does not support item assignment

>>> for i in h:

print i

 

1

2

3

4

>>> for i in s:

print i

 

4

t

>>>

Bit on dictionary :-

>>> d={1:2,3:4,’t’:’y’}

>>> d

{1: 2, 3: 4, ‘t’: ‘y’}

>>> d[1]=’h’

>>> d

{1: ‘h’, 3: 4, ‘t’: ‘y’}

>>> del d[1]

>>> d

{3: 4, ‘t’: ‘y’}

>>> d.pop(3)

4

>>> d

{‘t’: ‘y’}

>>> d.popitem()

(‘t’, ‘y’)

>>> d

{}

>>> squares = {x: x*x for x in range(6)}

>>> squares

{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

>>> odd_squares = {x: x*x for x in range(11) if x%2 == 1}

>>> odd_squares

{1: 1, 3: 9, 9: 81, 5: 25, 7: 49}

>>> for i,v in odd_squares.iteritems():

print i,v

 

1 1

3 9

9 81

5 25

7 49

 

Array :-

>>> import array

>>> a=array.array(‘i’,(1,2,3))   (Array creation)

>>> a

array(‘i’, [1, 2, 3])

>>> b=array.array(‘i’,(1,2,3,’h’))           (error because ‘h’ is given in array)

Traceback (most recent call last):

File “<pyshell#444>”, line 1, in <module>

b=array.array(‘i’,(1,2,3,’h’))

TypeError: an integer is required

>>>

>>> for i in a:

print i

1

2

3

>>> a.insert(1,6)

>>> a

array(‘i’, [1, 6, 2, 3])

>>> a.pop()

3

>>> a

array(‘i’, [1, 6, 2])

>>> a

array(‘i’, [1, 6, 2])

>>> a.tolist()                 (Convert array to list)

[1, 6, 2]

>>> a

array(‘i’, [1, 6, 2])

Matrix :-

>>> n=3

>>> m=4

>>> a=[0]*n

>>> for i in range(n):   (Creation of matrix)

a[i]=[0]*m

>>> print a

[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]

>>>

>>> a = [[‘Roy’,80,75,85,90,95],

[‘John’,75,80,75,85,100],

[‘Dave’,80,80,80,90,95]]

>>> a[0][1]                  (accessing matrix element)

80

>>> a[1][2]

80

>>> a[-1]

[‘Dave’, 80, 80, 80, 90, 95]

>>> a[-1][-2]

90

>>> a[-2][-1]

100

>>> a[-2][-1]=77                   (Updating matrix element)

>>> a

[[‘Roy’, 80, 75, 85, 90, 95], [‘John’, 75, 80, 75, 85, 77], [‘Dave’, 80, 80, 80, 90, 95]]

>>> a[-2][-1]

77

>>>

File Operation :-

>>> f = open(“test.txt”,’w’)  (create and open test.txt)

>>> f.write(“abc”)

>>> f.read()            (needs to open file in reading format)

Traceback (most recent call last):

File “<pyshell#4>”, line 1, in <module>

f.read()

IOError: File not open for reading

>>> f.readline()

Traceback (most recent call last):

File “<pyshell#7>”, line 1, in <module>

f.readline()

IOError: File not open for reading

>>> f = open(“test.txt”,’r’)

>>> f.read()

‘abc’

>>> f.tell()

3L

>>> f.seek(0)   (push back the cursor to first character)

>>> f.read()

‘abc’

>>> f.read()

>>> f.seek(0)

>>> f.read()

‘abc’

>>> for line in f:

print line

>>> f.readline()

>>> f.seek(0)          (reading pushes the cursor and seek will bring back cursor to 0                                                  position)

>>> for line in f:

print line

abc

>>>

NOTE :- More information can be found in our tutorial

Exception Handling :-

>>> try:    (Exception occurred)

r/0

except:

print “exception”

 

exception

>>>

>>> try:         (Exception occurred so name error is printed)

r/0

except NameError:

print “catched”

 

catched

>>> try:               (NameError Exception occurred so name is printed)

r/0

except ValueError:

print “va;ue”

except TypeError:

print “type”

except NameError:

print “name”

 

 

name

 

>>> try:              (Exception caught before raising so name is printed)

r/0

raise ValueError(“That is not a positive number!”)

except NameError:

print “name”

except ValueError:

print “value”

except TypeError:

print “type”

 

name

>>> try:                (ValueError is raised so value is getting printed)

raise ValueError(“That is not a positive number!”)

except NameError:

print “name”

except ValueError:

print “value”

except TypeError:

print “type”

 

value

 

>>> try:

raise TypeError

except NameError:

print “name”

except ValueError:

print “value”

except TypeError:

print “type”

 

type

 

>>> try:                    (Finally gets printed no matter exception caught or not)

raise TypeError

except NameError:

print “name”

except ValueError:

print “value”

except TypeError:

print “type”

finally:

print “exception caught”

 

type

exception caught

User defined exception :-

>>> class CustomError(Exception):

pass

 

>>> raise CustomError

Traceback (most recent call last):

File “<pyshell#133>”, line 1, in <module>

raise CustomError

CustomError

 

>>> raise CustomError(“An error occurred”)

Traceback (most recent call last):

File “<pyshell#136>”, line 1, in <module>

raise CustomError(“An error occurred”)

CustomError: An error occurred

 

>>> raise UserError  (UserError was not defined)

Traceback (most recent call last):

File “<pyshell#139>”, line 1, in <module>

raise UserError

NameError: name ‘UserError’ is not defined

 

>>> class UserError(Exception):       (Now defining UserError)

pass

 

>>> raise UserError

Traceback (most recent call last):

File “<pyshell#145>”, line 1, in <module>

raise UserError

UserError

 

>>> class Error(Exception):

“””Base class for other exceptions”””

pass

>>> class ValueTooSmallError(Error):

“””Raised when the input value is too small”””

pass

>>> class ValueTooLargeError(Error):

“””Raised when the input value is too large”””

pass

>>> try:

if (1<2):      (ValueTooSmallError is caught and small is printed)

raise ValueTooSmallError

else:

raise ValueTooLargeError

except ValueTooSmallError:

print “small”

except ValueTooLargeError:

print “large”

 

small

>>> a=2

>>> try:

if (a<1):

raise ValueTooSmallError

else:

raise ValueTooLargeError

except ValueTooSmallError:

print “small”

except ValueTooLargeError:

print “large”

 

 

large

>>> try:                               (Passing argument to exception)

var=raw_input(“enter input: “)

int(var)

except ValueError, Argument:

print “The argument does not contain numbers\n”, Argument

 

enter input: xy

The argument does not contain numbers

invalid literal for int() with base 10: ‘xy’

>>>

Classes & Objects :-

>>> class abc:

a=0

def __init__(self,b):

self.b=b

def dis(self):

print self.b

print self.a

>>> g=abc(4)

>>> g.dis()

4

0

>>> abc.b   (b to be accessed by instance)

Traceback (most recent call last):

File “<pyshell#282>”, line 1, in <module>

abc.b

AttributeError: class abc has no attribute ‘b’

>>> abc.a                   (a can be accessed by class name)

0

>>> abc.a=5

>>> abc.a

5

>>> g.dis()

4

5

>>> w=abc(66)                (creating new object, b value is 66 but a value is 5)

>>> w.dis()

66

5

>>> g.dis()                        (b is not altered in g, a is shared by all instance but b is particular to instance)

4

5

>>> class abc:

a=0

def __init__(self,b):

self.b=b

def dis(self):

print self.b

print self.a

def __del__(self):

class_name = self.__class__.__name__

print “deleting”

>>> a=abc(55)

>>> del a

deleting

>>>

Inheritance :-

>>> class abc:

a=4

def __init__(self,b):

self.b=2

def getval(self):

print self.a, self.b

>>> class abc1(abc):       (abc1 is inheriting abc parent class)

a=56

def __init__(self,b):

self.b=52

def getval(self):

print self.a, self.b

>>> a=abc(5)

>>> a.getval()

4 2

>>> b=abc1(23)    (Child object call override method)

>>> b.getval()

56 52

 

Operator Overloading :-

>>> class Point:

def __init__(self, x = 0, y = 0):

self.x = x

self.y = y

def __str__(self):

return “({0},{1})”.format(self.x,self.y)

def __add__(self,other):         (__add__ method is used to overload + operator)

x = self.x + other.x

y = self.y + other.y

return Point(x,y)

>>> p1 = Point(2,3)

>>> p2 = Point(-1,2)

>>> print(p1 + p2)

(1,5)

Data Hiding :-

>>> class JustCounter:

__secretCount = 0          (Hides from direct access)

def count(self):

print self.__secretCount

>>> counter = JustCounter()

>>> print counter.__secretCount

Traceback (most recent call last):

File “<pyshell#77>”, line 1, in <module>

print counter.__secretCount

AttributeError: JustCounter instance has no attribute ‘__secretCount’

>>> print counter._JustCounter__secretCount            (Need to use _classname to access hidden attributes)

0

>>>

Iterator :-

>>> L=[1,2,3,4]

>>> a=iter(L)

>>> next(a)

1

>>> next(a)

2

NOTE :- For user defined iterators you need to define iter and next method in a class

Generators :-

>>> def gen():   (Remembers the state for each call)

for i in range(5):

yield i

>>> a=gen()

>>> a.next()

0

>>> a.next()

1

>>> next(a)

2

>>> next(a)

3

>>> b=(x for x in range(7))

>>> next(b)

0

>>> next(b)

1

>>> next(b)

2

>>

Decorator :-

>>> def decod(func):  (Decorator function definition)

def wrapper():

print “bfr somefunc”

func()

print “after somefunc”

return wrapper

>>> def func():

print “I am func”

>>> func=decod(func)  (Creating function wrapper object)

>>> func()

bfr somefunc

I am func

after somefunc

>>> def test():   (creating another func ‘test’)

print “test”

>>> t=decod(test)

>>> test()

test

>>> def decod(test):

def wrapper():

print “bfr somefunc”

test()

print “after somefunc”

return wrapper

>>> test()

test

>>> func()

bfr somefunc

I am func

after somefunc

>>> func

<function wrapper at 0x02097470>

>>> test                                              (Test contains still only ‘test’ object)

<function test at 0x020974B0>

>>>

>>> test=decod(test)                      (Decorating test)

>>> test                                             (test is now pointing to function wrapper address)

<function wrapper at 0x020970B0>

>>> test()

bfr somefunc

test

after somefunc

>>> t                               (t also points to wrapper address)

<function wrapper at 0x020974F0>

>>> t()

bfr somefunc

test

after somefunc

>>> @decod                   (@decod represents test2=decod(test2))

def test2():

print “test2”

>>> test2()

bfr somefunc

test2

after somefunc

>>> def init(run):      (wrapper can be used to check condition before execution of function)

def wrapper(x):

if (x==2):

run(x)

else:

print “cannot run”

return wrapper

>>> @init

def run(x):

for i in range(5):

print i*x

>>> run(2)

0

2

4

6

8

>>> run(5)     (‘5’ is not equal to ‘2’)

cannot run

@Property

>>> class student:

def __init__(self,name,marks):

self.name=name

self.marks=marks

self.gotmarks = self.name + ‘ obtained ‘ + self.marks + ‘ marks’

>>> st = student(“san”, “25”)

>>> print st.name, st.marks, st.gotmarks

san 25 san obtained 25 marks

>>> st.name = “Anusha”

>>> print(st.name)

Anusha

>>> print(st.gotmarks)          (Pointing name to san itself)

san obtained 25 marks

>>> class student:

def __init__(self,name,marks):

self.name=name

self.marks=marks

# self.gotmarks = self.name + ‘ obtained ‘ + self.marks + ‘ marks’

def gotmarks(self):              (Defining function which prints specific to object as we are passing object ‘self’)

return self.name + ‘ obtained ‘ + self.marks + ‘ marks’

>>> st = student(“san”, “25”)

>>> print st.marks

25

>>> print st.gotmarks()

san obtained 25 marks

>>> st.name=”dep”

>>> print st.gotmarks()           (If more number of students are there we can’t modify                                                                  gotmarks to gotmarks())

dep obtained 25 marks

>>> class student:

def __init__(self,name,marks):

self.name=name

self.marks=marks

# self.gotmarks = self.name + ‘ obtained ‘ + self.marks + ‘ marks’

@property                          (placing @property helps user to use gotmarks as property and                                                     not as function)

def gotmarks(self):

return self.name + ‘ obtained ‘ + self.marks + ‘ marks’

>>> st1=student(“san”, “25”)

>>> st1.gotmarks

‘san obtained 25 marks’

>>> st1.name=’roy’

>>> st1.gotmarks

‘roy obtained 25 marks’

Regular Expression :-

>>> s = “Regular expressions easily explained!”    (Simple search using ‘in’)

>>> “easily” in s

True

 

>>> import re                  (module for regular expression)

>>> r=re.search(r”hi”, “hi i am dep”)

>>> print r                                 (search() searches the pattern)

<_sre.SRE_Match object at 0x01F65330>

>>> r1=re.search(r”hello”, “hi i am dep”)           (“hello” is not found so returning none)

>>> print r1

None

>>> r2=re.search(r”.s”, s)               (. Is a placeholder so printing es)

>>> print r2

<_sre.SRE_Match object at 0x0208FE90>

>>> r2.group()

‘es’

>>> r3=re.search(r” .s”, s)        (space is not found after .)

>>> r3.group()

Traceback (most recent call last):

File “<pyshell#196>”, line 1, in <module>

r3.group()

AttributeError: ‘NoneType’ object has no attribute ‘group’

>>> r3=re.search(r” .at ” ,”A cat and a rat can’t be friends.”)

>>> r3.group()

‘ cat ‘

>>> r4=re.search(r'[cr]at’,”A cat and a rat can’t be friends.”)  ([cr] specifies either c or r)

>>> r4.group()                                                 (To print rat also need to use findall() which we                                                                             see below)

‘cat’

>>> r5=re.search(r”M[ae][iy]er”, “Maier, Mayer, Meier, Meyer”)    (To print all also need                                                                                                                            to  use findall() )

>>> r5.group()

‘Maier’

>>> r6=re.search(r'[cr]at’,”A rat can’t be friends.”)   (Cat is removed so only rat is printed)

>>> r6.group()

‘rat’

>>> r10=re.search(r'[^d]’, “abcde”)              (^ more on this see in google)

>>> r10.group()

‘a’

>>> r11=re.search(r'[d]’, “abcde”)

>>> r11.group()

‘d’

>>> r12=re.search(r'[a-z]at’,”A cat and a rat can’t be friends.”)  ([a-z) specifies from a to z)

>>> r12.group()

‘cat’

>>> f=open(“reg.txt”,”r”)

>>> f.read()

‘test6 \n test7 \n test8 \n test9 \n test10′

>>> a=0

>>> f.seek(0)

>>> a

0

>>> for line in f:    (To print line and also to count line)

print line

a+=1

 

test6

 

test7

 

test8

 

test9

 

test10

>>> a

5

>>> for line in f:

r13=re.search(r’test.*’,line)   (print all letters in a file which start with test)

print r13.group()

test6

test7

test8

test9

test10

>>> f.seek(0)

>>> for line in f:

r13=re.search(r’.6′,line)        (printing line ends with 6 in a file, like wise print line for                                                               particular line count if (a==3))

print r13.group()

t6

>>> s=”hi I am fine, hi i am also good”

>>> r14=re.search(“hi”, s)   (search searchers anywhere in string)

>>> r14.group()

‘hi’

>>> r15=re.match(“hi”, s)         (match only matches at the beginning of the string)

>>> r15.group()

‘hi’

>>> s1=”I am fine, hi i am also good”

>>> r16=re.search(“hi”, s1)           (search searchers anywhere in string)

>>> r16.group()

‘hi’

>>> r17=re.match(“hi”, s1)          (match only matches at the beginning of the string, so                                                                    return none for s1)

>>> r17.group()

Traceback (most recent call last):

File “<pyshell#495>”, line 1, in <module>

r17.group()

AttributeError: ‘NoneType’ object has no attribute ‘group’

>>> mo = re.search(“[0-9]+”, “Customer number: 232454, Date: February 12, 2011”)

>>> mo.group()

‘232454’

>>> mo.group(1)      (only searching digits)

Traceback (most recent call last):

File “<pyshell#514>”, line 1, in <module>

mo.group(1)

IndexError: no such group

>>> mo = re.search(“([0-9]+).*: (.*)”, “Customer number: 232454, Date: February 12, 2011″)

>>> mo.group()               (‘:’ act as parting the group)

‘232454, Date: February 12, 2011’

>>> mo.group(1)

‘232454’

>>> mo.group(2)

‘February 12, 2011′

>>> r18=re.findall(r'[a-z]at’,”A cat and a rat can’t be friends.”)  (findall returning all                                                                                                                                   matchings)

>>> print r18

[‘cat’, ‘rat’]

>>> r5=re.findall(r”M[ae][iy]er”, “Maier, Mayer, Meier, Meyer”)

>>> print r5               (findall returning all matchings)

[‘Maier’, ‘Mayer’, ‘Meier’, ‘Meyer’]

>>> items = re.findall(“[0-9]+.*: .*”, “Customer number: 232454, Date: February 12, 2011”)

>>> print items

[‘232454, Date: February 12, 2011’]

>>> str = “The destination is London!”

>>> mo = re.search(r”destination.*(London|Paris|Zurich|Strasbourg)”,str)  (| for                                                                                                                                                            comparing)

>>> print mo.group()

destination is London

>>> regex=r”destination.*(London|Paris|Zurich|Strasbourg)”

>>> compile_test=re.compile(regex)            (re.compile to compile re to use in future)

>>> mo = re.search(compile_test,str)

>>> print mo.group()

destination is London

>>> msub=re.sub(r”London”, “Paris”, str)   (sub() replaces the string with the given string)

>>> print msub

The destination is Paris!

>>>

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

%d bloggers like this: