Roshan Book

My Tech Notebook

Tag Archives: python tutorial

Python tutorial 8 – Conditional Statement

Python programming tutorial 15–Databases

Creating a database in sqlite 3

import sqlite3

def main():
    db=sqlite3.connect(‘test.db’)
    db.execute(‘drop table if exists test’)
    db.execute(‘create table test(t1 text,i1 int)’)
    db.execute(‘insert into test (t1,i1) values(?,?)’,(‘one’,1))
    db.execute(‘insert into test (t1,i1) values(?,?)’,(‘two’,2))
    db.execute(‘insert into test (t1,i1) values(?,?)’,(‘three’,3))
    db.execute(‘insert into test (t1,i1) values(?,?)’,(‘four’,4))
    db.commit()
    cursor=db.execute(‘select * from test order by t1’)
    for row in cursor:
        print(row)
   
if __name__ == “__main__”: main()

 

Using row factory in sqllite3. It returns rows in dictionary mode

import sqlite3

def main():
    db=sqlite3.connect(‘test.db’)
    db.row_factory=sqlite3.Row # It allows you to specify how rows will be returned
    db.execute(‘drop table if exists test’)
    db.execute(‘create table test(t1 text,i1 int)’)
    db.execute(‘insert into test (t1,i1) values(?,?)’,(‘one’,1))
    db.execute(‘insert into test (t1,i1) values(?,?)’,(‘two’,2))
    db.execute(‘insert into test (t1,i1) values(?,?)’,(‘three’,3))
    db.execute(‘insert into test (t1,i1) values(?,?)’,(‘four’,4))
    db.commit()
    cursor=db.execute(‘select * from test order by t1’)
    for row in cursor:
        print(dict(row))
        print(row[‘t1’], row[‘i1’])
   
if __name__ == “__main__”: main()

 

 

Output

{‘i1’: 4, ‘t1’: ‘four’}
four 4
{‘i1’: 1, ‘t1’: ‘one’}
one 1
{‘i1’: 3, ‘t1’: ‘three’}
three 3
{‘i1’: 2, ‘t1’: ‘two’}
two 2

Python programming tutorial 15–Databases

Creating a database in sqlite 3

import sqlite3

def main():
    db=sqlite3.connect(‘test.db’)
    db.execute(‘drop table if exists test’)
    db.execute(‘create table test(t1 text,i1 int)’)
    db.execute(‘insert into test (t1,i1) values(?,?)’,(‘one’,1))
    db.execute(‘insert into test (t1,i1) values(?,?)’,(‘two’,2))
    db.execute(‘insert into test (t1,i1) values(?,?)’,(‘three’,3))
    db.execute(‘insert into test (t1,i1) values(?,?)’,(‘four’,4))
    db.commit()
    cursor=db.execute(‘select * from test order by t1’)
    for row in cursor:
        print(row)
   
if __name__ == “__main__”: main()

 

Using row factory in sqllite3. It returns rows in dictionary mode

import sqlite3

def main():
    db=sqlite3.connect(‘test.db’)
    db.row_factory=sqlite3.Row # It allows you to specify how rows will be returned
    db.execute(‘drop table if exists test’)
    db.execute(‘create table test(t1 text,i1 int)’)
    db.execute(‘insert into test (t1,i1) values(?,?)’,(‘one’,1))
    db.execute(‘insert into test (t1,i1) values(?,?)’,(‘two’,2))
    db.execute(‘insert into test (t1,i1) values(?,?)’,(‘three’,3))
    db.execute(‘insert into test (t1,i1) values(?,?)’,(‘four’,4))
    db.commit()
    cursor=db.execute(‘select * from test order by t1’)
    for row in cursor:
        print(dict(row))
        print(row[‘t1’], row[‘i1’])
   
if __name__ == “__main__”: main()

 

 

Output

{‘i1’: 4, ‘t1’: ‘four’}
four 4
{‘i1’: 1, ‘t1’: ‘one’}
one 1
{‘i1’: 3, ‘t1’: ‘three’}
three 3
{‘i1’: 2, ‘t1’: ‘two’}
two 2

Python tutorial 12.1- Classes Object

Example:

   
class Duck:   # Creation of Class
 
        def quack(self,x): # Creation of methods
            self.x=x
            if self.x==”jhilam”:
                print(‘{} is depressive ‘.format(self.x))
            elif self.x==”rita”:
                print(‘{} , I Love You ‘.format(self.x))
            else: print(‘{} is Normal’.format(self.x))
           
        def walk(self,y):
            self.y=y
            print(‘{} Walk’.format(self.y))

i = input(“Enter your name t”)

donald=Duck()
donald.quack(i)

 

Encapsulation

self is passed, means name donald is passed.It is the first argument of method. It happens due to dot operator.

def __init__(self,value):  #This is constructor

This value can be used inside class saving in a local variable self.v=value . This is called encapsulation

def __init__(self,value):

  self.v=value;

Practical use of encapsulation 

Here you are passing any variable inside class and saving it in a dictionary and retrieving it from dictionary

 

class Duck:
    def __init__(self, **kwargs):
        self.variables=kwargs
       
    def quack(self):
        print(‘Quaaack!’)

    def walk(self):
        print(‘Walks like a duck.’)
   
    def set_variable(self,k,v):
        self.variables[k]=v
   
    def get_variable(self,k):
        return self.variables.get(k,None)

def main():
    donald = Duck(feet=2)
    print (donald.get_variable(‘feet’))

if __name__ == “__main__”: main()

Inheritance

Methods in one class inheriting methods from other class

 

E.g. class Dog(Animal):  # Dog class inheriting parent class methods

Example

class Animal:
    def talk(self):
        print(‘I have something to say’)
    def clothes (self):
        print(‘I have nice clother’)

class Duck(Animal): # Duck inherited Animal methods
    def __init__(self, **kwargs):
        self.variables=kwargs
       
    def quack(self):
        print(‘Quaaack!’)

    def walk(self):
        super().walk()
        print(‘Walks like a duck.’)
   
    def set_variable(self,k,v):
        self.variables[k]=v
   
    def get_variable(self,k):
        return self.variables.get(k,None)

def main():
    donald = Duck(feet=2)
    donald.clothes()

if __name__ == “__main__”: main()
   
#walk in child class override parent class
#to ingeritent from parent function just write super().walk(). And now both walk methods will work

 

# Polymorphism is using object of one class as if it is an object of another class

class Duck():
    def method1(self):
        None

class Dog():
    def method1(self):
        None
def main():
    donald=Duck()
    fido=Dog()

def in_the_forest(dog):
    dog.method1()

def in_the_pond(duck):
    duck.method1()

#Now if we pass duck in the forest, it gives back result of method1 of dog object#

#like
in_the_pond(fido)# – now fido passed in the pond like duck and then fido method 1 is called

for o in (donald, figo):
    o.method1()
# here we call all methods in both the objects

if __name__ == “__main__”: main()
   
#To use polymorphically common interface is reuired in both classes
# That is same methods in two classes
# Then define a for loop and call method of the objects

# any function that is present in the object can be run inside a different function expecting that object and its method regarding of what type of object it is.

# Generator object

# Overriding a class

# our own range object which will inclusive of last value
# we will override the initial propoerty of range class of excluding last item

class inclusive_range:
    def __init__(self, args):
           
        numargs=len(args)
        if numargs<1:raise TypeError(‘require at  least one argument’)
        elif numargs==1:
            self.stop=args[0]
            self.start=0
            self.step=1
        elif numargs==2:
            (self.start,self.stop)=args
            self.step=1
        elif numargs==3:
            (self.start,self.stop,self.step)=args
        else: raise TypeError(‘expected at least 3 arguments, got {}’.format(numargs))
   
   
    def __iter__(self): # makes object an iterable objetc
        i=self.start
        while i<=self.stop:
            yield i
            i+=self.step # This makes it an iterator
   

 

def main():
        o=inclusive_range(5,25)
        for i in o:print(i, end=”)
if __name__==”__main__”:main()

 

# Decorators – functions that return other functions. Modify the way function works

you can set functions of same name with different methods

Inside a class

@propertydef color(self):

    self.properties.get(‘’color’,None)=c

@color.setter

def color(self,c):

     self.properties[‘color’]=c

@color.deleter

def color(self):

del self.properties[‘color’]

now you can just create the object donald=Duck()

and without passing the color=’blue ’ inside duck you can just fix as donald.color=’blue’ (uses @properties)

print (“donald.color”)   This ultimately print the color from color.setter

Python tutorial 11- Functions

use pass statement if you want nothing inside function

e.g

def testfunc():

    pass

You can pass multiple parameters inside python

Once you must pass all parameters when defined

You can also define a default value, for in case all arguments are getting passed

You can also assign value none for parameters, if you don’t want to give default value for parameter.

#To get arbitrary/optional number of arguments

def main():
    testfunc()

def testfunc(arg1,arg2, *args):
    print(‘This is a test function’)

if __name__ == “__main__”: main()

 

 

args gives other values as tuple

It is immutable. No change, no addition

# passing a named parameters

def main():

testfunction(one=1,two=2,three=42)

def testfunc(**kwargs):

print(‘This is a test function’,kwargs[‘one’])

Kwargs are dictionary and arguments are passing from the caller as dictionary

Sequence of occurrence in a function – Named argument, Arbitary tuple argument and then Keyword arguments

i.e. arg1, arg2, *args, **kwargs

# return values from function

return- loop breaks

yield – that loop breaks and continue from next loop

# Sequence with generator function

Function that generates iterators in function

Range(start,stop,step)

stop, when only one value

start default value 0

step default value 1

 

def inclusive_range(*args):

numargs=len(args)

if numargs<1:raise typeError(‘requires at least one argument’)

elif numargs==1

start=0

stop=args[0]

step=1

 

elif numargs==2start=0

stop=args[0]

(start,stop)=args

step=1

elif numargs==3

(start,stop,step)=argsstop=args[0]

else: raise Typeerror(“atmax 3 arguments in range function”)

i=start

while i<=stop:

yield i

i+=step

Python tutorial 10- Exception handling

Example

def main():
    try:
        fh=open(line.txt)
    except:
        print(‘could not open the file’)

     else:

           for line in fh: print(line.strip())
        
main()

For particular error

def main():
    try:
        fh=open(line.txt)
    except IOError:
        print(‘could not open the file’)

     else:

           for line in fh: print(line.strip())
        
main()

Getting error message

def main():
    try:
        fh=open(line.txt)
    except IOError as e:
        print(‘could not open the file’),e

     else:

           for line in fh: print(line.strip())
        
main()

We can also remove else statement and put the command directly into try. In this way execution stops once error occurs.

 

# Raising own exception

def main():

for line in readfile(‘x.lines.txt’)

: print(line.strip())

except IOError as e:

print(‘cannot read file:’,e)

except valueerror as e:

print(‘bad filename’,e)

def readfile(filename):

if filename.endswith(‘.txt’)

           fh=open(filename)

           return fh.readlines()

else:raise ValueError(‘Filename must end with .txt’)

main()

Python tutorial 9.2–Using Regular Expressions

It is for matching patterns in text

It is implemented in python with “re” module

working

import re

patter=re.compiler(r’ddd’)

if re.search(regex, line): print (line)

example. If you have a text file name raven.txt and wants to print words which matched lenore or nevermore

For pattern and print the line

def main():

fh=open(‘raven.txt’)

for line in fh:

if re.search(‘(len/neverm)ore’, line):

print(line, end=’’)

if __name__=”__main__”:main()

For matching

def main():

fh=open(‘raven.txt’)

for line in fh:

match=re.search(len/neverm)ore’, line)

if match:

print(match.group())

if __name__=”__main__”:main()

For search and replace

def main():

fh=open(‘raven.txt’)

for line in fh:

print( re.sub(‘(len/neverm)ore’, ‘what replaces with’,line):,ened=’’)

if __name__=”__main__”:main()

For search and replace match method – printing only those line where match and replace happens

def main():

fh=open(‘raven.txt’)

for line in fh:

match=re.search
(‘(len/neverm)ore’, ‘line)

if match:

print(line.replace(match.group()),’###’

),end=’’)

if __name__=”__main__”:main()

Re Compiling

def main():

fh=open(‘raven.txt’)

pattern=re.compile(‘len/neverm)ore’, re.IGNORECASE)

for line in fh:

match=re.search
(‘attern, ‘line)

if match:

print(line.replace(match.group()),’###’

),end=’’)

if __name__=”__main__”:main()

Python tutorial 9.2–Using Regular Expressions

It is for matching patterns in text

It is implemented in python with “re” module

working

import re

patter=re.compiler(r’ddd’)

if re.search(regex, line): print (line)

example. If you have a text file name raven.txt and wants to print words which matched lenore or nevermore

For pattern and print the line

def main():

fh=open(‘raven.txt’)

for line in fh:

if re.search(‘(len/neverm)ore’, line):

print(line, end=’’)

if __name__=”__main__”:main()

For matching

def main():

fh=open(‘raven.txt’)

for line in fh:

match=re.search(len/neverm)ore’, line)

if match:

print(match.group())

if __name__=”__main__”:main()

For search and replace

def main():

fh=open(‘raven.txt’)

for line in fh:

print( re.sub(‘(len/neverm)ore’, ‘what replaces with’,line):,ened=’’)

if __name__=”__main__”:main()

For search and replace match method – printing only those line where match and replace happens

def main():

fh=open(‘raven.txt’)

for line in fh:

match=re.search
(‘(len/neverm)ore’, ‘line)

if match:

print(line.replace(match.group()),’###’

),end=’’)

if __name__=”__main__”:main()

Re Compiling

def main():

fh=open(‘raven.txt’)

pattern=re.compile(‘len/neverm)ore’, re.IGNORECASE)

for line in fh:

match=re.search
(‘attern, ‘line)

if match:

print(line.replace(match.group()),’###’

),end=’’)

if __name__=”__main__”:main()

Python tutorial 7–Calculations

5//3 – floor division – 1 (integer only)

5/3 – 1.6666

5%2 –2

2**3 -8

divmod(5,3) – division with integer result and mod –(1,2) – result as tuple

python supports x+=1 with other opertaors like *, /, –,//

printing binary values

def b(n): print (‘{:08b}’.format(n))

now calling this function b(5) – would output binary value of 5 i.e. 00000101

Operators

x is y – id is compared

x is not y-id is compared

and  –  comparing boolean conditions

or- comparing boolean conditions

Slice operator

list = [1,2,3,4]

list[0:2] – gives slice of first 2 items, i.e. index 0, 1

for i in range(0,10)  :  print(i)

gives 0-9, last item is always non inclusive in a range

list [:]= range() – this gives 100 items in our list starting from 0 – 0to 99

list[27:42] – slice of from 27 index to 41 index (42 is non inclusive)

list[27:42:3] – list of 27 to 41 index with every 3rd item

list[27:43:3]=[99,99,99,99,99,99]- it replaces third element from 27 to 42 is replaced to 99

Operator precedence

Python follows bodmas rule

* and / is upper than +-. * and / has same preferably thus, when * and / both are there, then in the order of occurrence from left calculation happens.

For comparison operator like <==,in,not,is,isnot,!= etc , associativity is from right to left

Use parentheses

Python tutorial 7–Calculations

5//3 – floor division – 1 (integer only)

5/3 – 1.6666

5%2 –2

2**3 -8

divmod(5,3) – division with integer result and mod –(1,2) – result as tuple

python supports x+=1 with other opertaors like *, /, –,//

printing binary values

def b(n): print (‘{:08b}’.format(n))

now calling this function b(5) – would output binary value of 5 i.e. 00000101

Operators

x is y – id is compared

x is not y-id is compared

and  –  comparing boolean conditions

or- comparing boolean conditions

Slice operator

list = [1,2,3,4]

list[0:2] – gives slice of first 2 items, i.e. index 0, 1

for i in range(0,10)  :  print(i)

gives 0-9, last item is always non inclusive in a range

list [:]= range() – this gives 100 items in our list starting from 0 – 0to 99

list[27:42] – slice of from 27 index to 41 index (42 is non inclusive)

list[27:42:3] – list of 27 to 41 index with every 3rd item

list[27:43:3]=[99,99,99,99,99,99]- it replaces third element from 27 to 42 is replaced to 99

Operator precedence

Python follows bodmas rule

* and / is upper than +-. * and / has same preferably thus, when * and / both are there, then in the order of occurrence from left calculation happens.

For comparison operator like <==,in,not,is,isnot,!= etc , associativity is from right to left

Use parentheses

%d bloggers like this: