Roshan Book

My Tech Notebook

Tag Archives: learn python

Python tutorial 18- Using python in netbeans

 

  • Start NetBeans 7
  • Click on Tools > Plugins
  • When the Plugins window opens click the Settings Tab
  • In the Settings tab click the Add button
  • Type whatever Name you want for this, I used ‘Developer Updates’
  • Under URL put http://deadlock.netbeans.org/hudson/job/nbms-and-javadoc/lastStableBuild/artifact/nbbuild/nbms/updates.xml.gz and click OK
  • The plugin list should refersh and may take a moment, when it does click on the ‘Available Plugins’ tab.
  • In the search box there type ‘python’ to find the python plugin, check the box for that plugin and click Install.

Python tutorial 0–Resources

Python tutorial 17.2 Working with modules

Opening and encoding a webpage

def main():
    import urllib.request
    page=urllib.request.urlopen(‘http://bw.org/’)
    for line in page: print(str(line, encoding =’utf_8′), end=”)

if __name__ == “__main__”: main()

 

 

Module resource : http://docs.python.org/py3k/index.html

Python tutorial 17–Objects in database

import sqlite3

class database:
    def __init__(self, **kwargs):
        self.filename = kwargs.get(‘filename’)
        self.table = kwargs.get(‘table’, ‘test’)
   
    def sql_do(self, sql, *params):
        self._db.execute(sql, params)
        self._db.commit()
   
    def insert(self, row):
        self._db.execute(‘insert into {} (t1, i1) values (?, ?)’.format(self._table), (row[‘t1’], row[‘i1’]))
        self._db.commit()
   
    def retrieve(self, key):
        cursor = self._db.execute(‘select * from {} where t1 = ?’.format(self._table), (key,))
        return dict(cursor.fetchone())
   
    def update(self, row):
        self._db.execute(
            ‘update {} set i1 = ? where t1 = ?’.format(self._table),
            (row[‘i1’], row[‘t1’]))
        self._db.commit()
   
    def delete(self, key):
        self._db.execute(‘delete from {} where t1 = ?’.format(self._table), (key,))
        self._db.commit()

    def disp_rows(self):
        cursor = self._db.execute(‘select * from {} order by t1’.format(self._table))
        for row in cursor:
            print(‘  {}: {}’.format(row[‘t1’], row[‘i1’]))

    def __iter__(self):
        cursor = self._db.execute(‘select * from {} order by t1’.format(self._table))
        for row in cursor:
            yield dict(row)

    @property
    def filename(self): return self._filename

    @filename.setter
    def filename(self, fn):
        self._filename = fn
        self._db = sqlite3.connect(fn)
        self._db.row_factory = sqlite3.Row

    @filename.deleter
    def filename(self): self.close()

    @property
    def table(self): return self._table
    @table.setter
    def table(self, t): self._table = t
    @table.deleter
    def table(self): self._table = ‘test’

    def close(self):
            self._db.close()
            del self._filename

def main():
    db = database(filename = ‘test.db’, table = ‘test’)

    print(‘Create table test’)
    db.sql_do(‘drop table if exists test’)
    db.sql_do(‘create table test ( t1 text, i1 int )’)

    print(‘Create rows’)
    db.insert(dict(t1 = ‘one’, i1 = 1))
    db.insert(dict(t1 = ‘two’, i1 = 2))
    db.insert(dict(t1 = ‘three’, i1 = 3))
    db.insert(dict(t1 = ‘four’, i1 = 4))
    for row in db: print(row)

    print(‘Retrieve rows’)
    print(db.retrieve(‘one’), db.retrieve(‘two’))

    print(‘Update rows’)
    db.update(dict(t1 = ‘one’, i1 = 101))
    db.update(dict(t1 = ‘three’, i1 = 103))
    for row in db: print(row)

    print(‘Delete rows’)
    db.delete(‘one’)
    db.delete(‘three’)
    for row in db: print(row)

if __name__ == “__main__”: main()

Python tutorial 16–CRUD application

import sqlite3

def insert(db, row):
    db.execute(‘insert into test (t1, i1) values (?, ?)’, (row[‘t1’], row[‘i1’]))
    db.commit()

def retrieve(db, t1):
    cursor = db.execute(‘select * from test where t1 = ?’, (t1,))
    return cursor.fetchone()

def update(db, row):
    db.execute(‘update test set i1 = ? where t1 = ?’, (row[‘i1’], row[‘t1’]))
    db.commit()

def delete(db, t1):
    db.execute(‘delete from test where t1 = ?’, (t1,))
    db.commit()

def disp_rows(db):
    cursor = db.execute(‘select * from test order by t1’)
    for row in cursor:
        print(‘  {}: {}’.format(row[‘t1’], row[‘i1’]))

def main():
    db = sqlite3.connect(‘test.db’)
    db.row_factory = sqlite3.Row
    print(‘Create table test’)
    db.execute(‘drop table if exists test’)
    db.execute(‘create table test ( t1 text, i1 int )’)

    print(‘Create rows’)
    insert(db, dict(t1 = ‘one’, i1 = 1))
    insert(db, dict(t1 = ‘two’, i1 = 2))
    insert(db, dict(t1 = ‘three’, i1 = 3))
    insert(db, dict(t1 = ‘four’, i1 = 4))
    disp_rows(db)

    print(‘Retrieve rows’)
    print(dict(retrieve(db, ‘one’)), dict(retrieve(db, ‘two’)))

    print(‘Update rows’)
    update(db, dict(t1 = ‘one’, i1 = 101))
    update(db, dict(t1 = ‘three’, i1 = 103))
    disp_rows(db)

    print(‘Delete rows’)
    delete(db, ‘one’)
    delete(db, ‘three’)
    disp_rows(db)

if __name__ == “__main__”: main()

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 14.2–input and output

 

Opening a file – read mode

def main():
    f = open(‘lines.txt’)
    for line in f:
        print(line, end = ”)

if __name__ == “__main__”: main()

f = open(‘lines.txt’,’r’) – open just to read a file. Default

f = open(‘lines.txt’,’w’) – write mode

f = open(‘lines.txt’,’a’) – append, what you write gets appended
f = open(‘lines.txt’,’r+’) – read and write
f = open(‘lines.txt’,’rt’) – text file mode

f = open(‘lines.txt’,’rb’) – binary mode

for line in f.readlines:

print(line,end=’’)

do the same thing as mentioned in above loop

 

# Creating a new file with text from old file

def main()

infile=opemn(‘line.txt’,’r’)

outfile=open(‘new.txt ’,w)  # new file which we want to create

for line in infile:

print(line,file=outfile,end=’’)

print(‘done’)

if __name__=”__main__”

                                                     

This will create a new file new.txt with content from line.txt

def main()

buffersize=50000

infile=open(‘line.txt’,’r’)

outfile=open(‘new.txt ’,w)  # new file which we want to create

buffer=infile.read(buffersize)

while len(buffer):

outfile.write(buffer)

print(‘.’end=’’)

buffer=infile.read(buffersize)

print(‘done’)

if __name__=”__main__”

# Working with binary file like jpg – creating exact duplicate

def main():
    buffersize=50000
    infile = open(‘olives.jpg’,’rb’)
    outfile=open(‘new.jpg’,’wb’)
    buffer = infile.read(buffersize)
    while len(buffer):
        outfile.write(buffer)
        print(‘.’,end=”)
        buffer=infile.read(buffersize)
    print()
    print(‘Done’)   

if __name__ == “__main__”: main()

Python tutorial 14- Tuples and Lists

Tuple

t=1,2,3 or t=tuple(range(25))

t[-1] returns last element

len[t] gives length of the tuple

min[t] gives minimum value of tuple

max[t] gives maximum value of the tuple

Tuple is deifned by ,

 

Lists are created with square bracket

same methods as tuple

You can also change things

x=list(range(25))

to change a position x[10]= 45

Why to use tuple

smaller class, simpler, faster, don’t allow you to change stuff

Operations in tuples and lists

t.count()

t.index(5)

list_x.append(100) – put 100 at the end of it

len(x) – length og lust x

x.extend(range(20)) – range 20 added to end of list x

x.insert(0,25) – insert 25 at positon 0

x.remove(12) – remove element with value 12

del x[12] – delete index 12

x.pop() – remove last value of the list and return it

x.pop(0) – pop from beginning

similarly x.pop(index) – remove that index value

# Dictionaries

Python verison of associative arrays

Created with curly braces

d={‘one’:1,’two’:2}

another way

d=dict(one=1,two=2)

x=dict(four=2,five=5)

you can say d=dict(one=1,two=2,**x)

This addds dict x into dict d

# to iterate

for k in d : print(k ) – prints all keys

for k, v in d.items() : print(k,v) – gives key and value

x.get(‘three’,’not found’) – gives three key value or give some default value if not there

del x[‘four’] – del key four

x.pop(‘five’) – remove and returns index five

You could store dic , tuple inside dictionary

Python tutorial 13–Strings

Common methods :

#string.upper() – This will change everything to upper case
#’This is a string {}’.format(42) –  will publish This is a string 42
# s.capitalize()- Publish in sentence case
#s.lower()
#s.swapcase() -opposite case
# s.find(‘is’) – returns the postion
#s.replace(‘This’,’That’) – This is entirely dirreferen objetc that returns
#s.strip()- this removes white space from beginning and end
#s.rstrip() – removes white space from end of string
#s1.rstri(‘n’)- takes out only new line
#s.isalnum()-if checks it has only alphanumeric charactures
#s.isalpha()-checks only for alpha charcters, like a to z onle
#s.isdigit()- checks if only digit
#s.isprintable()- checks if all characters are printable

 

Format method

#s=”this is {},that is {}”.format(a,b)
#now you can do s.format(d,e) and this geenrates a new objetc which youc an save in a different vairable

# You can also specify as ‘this is {1} and that is {0}’.format(a,b))
# this will print this is b and that is a
# you can also use dictionary to rpint than postion like ‘this is {bob} and that is {fred}’.format(bob=a,fred=b)
# another way is to define dictionaly first d=dict(bob=a, fred=b) and then use ‘this is {bob} and that is {fred}’.format(**d)

# Splitting and joining stings
s= ‘This is string a strng of words’
#s.split() splits depending on white space i.e. [“This”,’is’,’string’,’of’,’words’
                                               
# to specify argument to splits
#words=split(‘i’)  # this gives strings with all i removed and words splitter on i character
#    joining   
# ‘,’join(words) # This will join back all the words
                           
# docs for string methods : http://docs.python.org/py3k/library/stdtypes.html#string-methods
# Python full library at http://docs.python.org/py3k/library/

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

%d bloggers like this: