Pages

Monday, May 29, 2017

Python Examples

# The format method
age = '30' or 30
name = 'nawraj'
print('{0} was {1} years old when he wrote this book'.format(name, age))

#decimal (.) precision of 3 for float '0.333'
print('{0:.3}'.format(1/3))

# fill with underscores (_) with the text centered (^) to 11 width '___hello___'
print('{0:_^11}'.format('hello'))

#keyword based, nawraj wrote a Byte of Python
print('{name} wrote {book}'.format(name='nawraj',book='A Byte of Python'))

## multiline in python
s = '''This is a multi-line string.
This is the second line...'''
print(s)

s = 'This is a string. \
This continues the string.'
print(s)
#or
print\
       (s)

or

if False: '''
...statements...

'''

## break statement
while True:
    s = input('Enter something: ')
    if s == 'quit':
        break
    print('length of the string is:', len(s))
print('Done')

## continue statement
while True:
    s = input('Enter something: ')
    if s == 'quit':
        break
    if len(s) < 3:
        print('too small')
        continue
    print('Input is of insufficient length')

## local variables
x = 50
def func(x):
    print('x is', x)
    x = 2
    print('changed local x to', x)

func(x)
print('x is still', x)

## global statement
x = 50
def func():
    global x

    print('x is', x)
    x = 2
    print('changed global x to', x)

func()
print('Value of x is', x)

## default argument
def say(message, times = 1):
    print(message * times)

say('hello')
say('World', 5)

##keyword arguments
def func(a, b=5, c=10):
    print('a is', a, 'and b is', b, 'and c is', c)

func(3,7)
func(25, c=24)
func(c=50, a=100)

##VarArgs parameters
def total(initial=50, *numbers, **keywords):
    count = initial
    for number in numbers:
        count += number
    for key in keywords:
        count += keywords[key]
    return count
print(total(10, 1, 2, 3, vegetables=50, fruits=100))

## keyword-only parameters
def total(initial=5, *numbers, extra_number):
    count = initial
    for number in numbers:
        count += number
    count += extra_number
    print(count)
total(10, 1, 2, 3, extra_number=50)

##return statement
def maximum(x,y):
    if x > y:
        return x
    elif x == y:
        return 'The number are equal'
    else:
        return y
print(maximum(3,3))

## DocStrings
def printMax(x,y):
    '''print the maximum of two numbers.
        The two values must be integers..'''
    x = int(x)
    y = int(y)

    if x > y:
        print(x, 'is maximum')
    else:
        print(y, 'is maximum')

printMax(3,5)
print(printMax.__doc__)

## Modules
import sys
print('The command line arguments are: ')
for i in sys.argv:
    print(i)

print('\n\nThe PYTHONPATH is', sys.path, '\n')

## module name
if __name__ == '__main__':
    print('This program is being run by itself')
else:
    print('I am being imported from other module')

## dir function
import sys
print(dir(sys))
print(dir())

## List
shoplist = ['apple', 'mango', 'carrot', 'banana']
print('i have', len(shoplist), 'items to purchase')
print('These items are:', end= ' ')
for item in shoplist:
    print(item, end= ' ')
print('\n I also have to buy rice.')
shoplist.append('rice')
print('My shopping list is now', shoplist)

print('i will sort my list now')
shoplist.sort()
print('sorted shopping list is now', shoplist)

print('The first item i will buy is', shoplist[0])
olditem = shoplist[0]
del shoplist[0]
print('i bought the', olditem)
print('My shopping list is now', shoplist)

## Tuple
zoo = ('python','elephant','penguin')
print('Number of elements in the zoo', len(zoo))
new_zoo = 'monkey', 'camel', 'zoo'
print(type(new_zoo))
print('number of cages in the new zoo : ', len(new_zoo))
print('All animals in the new zoo are ', new_zoo)
print('Animals brought from old zoo are', new_zoo[2])
print('Last animal brought from the old zoo is', new_zoo[2][2])
print('Number of animals in the new zoo is', len(new_zoo)-1+len(new_zoo[2]))

## dictionary
ab = {'nawraj'  : 'nawraj.lekhak@hotmail.com',
      'Mohan'   : 'mohan@hotmail.com',
      'Ram'     : 'Ram@hotmail.com',
      }
print('nawraj addres is: ', ab['nawraj'])
print('There are {0} contacts in the address book'.format(len(ab)))

for name, address in ab.items():
    print('Contact {0} at {1}'.format(name, address))

ab['John'] = 'john@hotmail.com'

if 'John' in ab:
    print('John address is', ab['John'])

## Sequence
shoplist = ['apple','mango','carrot','banana']
name = 'nawraj'
print('Item 0 is', shoplist[0])
print('Item 1 is', shoplist[1])
print('Item 2 is', shoplist[2])
print('Item 3 is', shoplist[3])

print('Item -1 is', shoplist[-1])
print('Item -2 is', shoplist[-2])
print('Item -3 is', shoplist[-3])
print('Character 0 is', name[0])

print('Item 1 to 3 is', shoplist[1:3])
print('Item 2 to end is', shoplist[2:])
print(shoplist)
print('Item 1 to -1 is', shoplist[1:-1])
print('Item start to end is', shoplist[:])

print('Character 1 to 3 is', name[1:3])
print('Character 2 to end is', name[2:])
print('Character 1 to -1 is', name[1:-1])
print('Character start to end is', name[:])

print(shoplist[::1])
print(shoplist[::2])
print(shoplist[::3])
print(shoplist[::-1])

# set
bri = set(['brazil','russia','india'])
'india' in bri
'usa' in bri
bric = bri.copy()
bric.add('china')
print(bric)
bric.issuperset(bri)
print(bric)
bri.remove('russia')
print(bri)
bri & bric # OR bri.intersection(bric)
print(bri)
print(bric)

## References
print('Simple assignment')
shoplist = ['apple', 'mango', 'carrot','banana']
mylist = shoplist
del shoplist[0]
print('shoplist is:', shoplist)
print('mylits is:', mylist)
==> both will print same list

print('Copy by making a full slice')
mylist = shoplist[:]
del mylist[0]

print('shoplist is ', shoplist)
print('mylist is', mylist)
==> now the two list are different

## Strings
name = 'nawraj'
if name.startswith('naw'):
    print('Yes, the string starts with "naw"')
if 'a' in name:
    print('Yes, it contains the string "a"')
if name.find('raj') != -1:
    print('Yes, it contains the string "raj"')
delimiter = '_*_'
mylist = ['Brazil','Russia', 'India', 'Nepal']
print(delimiter.join(mylist))

## import
import os
import time
source = '/Users/nawlekha/python_training'
target_dir = '/Users/nawlekha/test'
today = target_dir + os.sep + time.strftime('%Y%m%d')
now = time.strftime('%H%M%S')

comment = input('Enter a comment --')
if len(comment) == 0:
    target = today + os.sep + now + '.zip'
else:
    target = today + os.sep + now + '_' + \
             comment.replace(' ', '_') + '.zip'

if not os.path.exists(today):
    os.mkdir(today)
    print('Successfully created directory', today)

zip_command = 'zip -qr {0} {1}'.format(target, ' '.join(source))

if os.system(zip_command) == 0:
    print('successful backup to', target)
else:
    print('Backup failed')

## Classes
class Person():
    pass
p = Person()
print(p)

## Object Modules
class Person:
    def sayHi(self):
        print('Hello, how are you?')
p = Person()
p.sayHi()
#or
Person().sayHi()

## The init method
class Person:
    def __init__(self, name):
        self.name = name
    def sayHi(self):
        print('Hello, my name is', self.name)
p = Person('nawraj')
p.sayHi()
#or
Person('nawraj').sayHi()

## class and object variables
class Robot:
    population = 0
    def __init__(self, name):
        self.name = name
        print('Initializing {0}'.format(self.name))
        Robot.population += 1

    def __del__(self):
        print('{0} is being destroyed!'.format(self.name))
        Robot.population -= 1

        if Robot.population == 0:
            print('{0} was the last one'.format(self.name))
        else:
            print('There are still {0:d} robots working'.format(Robot.population))

    def sayHi(self):
        print('Greetings, my masters call me {0}'.format(self.name))

    def howMany():
        print('We have {0:d} robots'.format(Robot.population))

    howMany = staticmethod(howMany)

droid1 = Robot('R2-D2')
droid1.sayHi()
Robot.howMany()

droid2 = Robot('C-3PO')
droid2.sayHi()
Robot.howMany()

print('\nRobots can do some work here.\n')
print('Robots have finished their work. so let destroy them.')
del droid1
del droid2
Robot.howMany()

## Inheritance
class SchoolMember:
    def __init__(self,name,age):
        self.name = name
        self.age = age
        print('Initialized schoolmember: {0}'.format(self.name))

    def tell(self):
        print('name: "{0}", Age: "{1}"'.format(self.name, self.age), end='')

class Teacher(SchoolMember):
    def __init__(self, name, age, salary):
        SchoolMember.__init__(self, name, age)
        self.salary = salary
        print('Initialized teacher: {0}'.format(self.name))

    def tell(self):
        SchoolMember.tell(self)
        print('Salary: "{0:d}"'.format(self.salary))

class Student(SchoolMember):
    def __init__(self, name, age, marks):
        SchoolMember.__init__(self, name, age)
        self.marks = marks
        print('Initialized student: {0}'.format(self.name))

    def tell(self):
        SchoolMember.tell(self)
        print('Marks: "{0:d}"'.format(self.marks))

t = Teacher('Mr shiva', 40, 30000)
s = Student('nawraj', 25, 80)

print() # print blank line

members = [t, s]
for member in members:
    member.tell()

## Input from the user
def reverse(text):
    return text[::-1]

def is_palindrome(text):
    return text == reverse(text)

something = input('Enter text: ')
if (is_palindrome(something)):
    print('Yes, it is palindrome')
else:
    print('No, it is not a palindrome')

## Files
one = '''\
hello world
how are you doing
have fun
'''
f = open('one.txt', 'w')
f.write(one)
f.close()

f = open('one.txt') ## r is default mode
while True:
    line = f.readline()
    if len(line) == 0:
        break
    print(line, end=' ')
f.close()

## Pickle : use to store any Python object in a file and then get it back later
import pickle
shoplistfile = 'shoplist.data'
shoplist = ['apple', 'mango', 'carrot']

f = open(shoplistfile, 'wb')
pickle.dump(shoplist, f) ## dump the object to the file
f.close()

del shoplist

f = open(shoplistfile, 'rb')
storedlist = pickle.load(f) # load the object from the file
print(storedlist)

## Handling Exceptions
try:
    text = input("Enter something-->") ## pres ctrl-d
except EOFError:
    print("Why did you do EOF on me? ")
except KeyboardInterrupt:
    print('You cancelled the operation')
else:
    print('You entered {}'.format(text))

## Raising exception
class ShortInputException(Exception):
    def __init__(self, length, atleast):
        Exception.__init__(self)
        self.length = length
        self.atleast = atleast
    try:
        text = input('Enter something->')
        if len(text) < 3:
            raise ShortInputException(len(text), 3)
    except EOFError:
        print('Why did you do an EOF on me')
    except ShortInputException as ex:
        print('ShortInputException: The input was {0} long, expected at least {1}'.format(ex.length,ex.atleast))
    else:
        print('No exception raised')

## Try
import time
try:
    f = open('one.txt')
    while True:
        line = f.readline()
        if len(line) == 0:
            break
        print(line, end= ' ')
        time.sleep(2)
except KeyboardInterrupt:
    print('!! you cancelled reading from the file')
finally:
    f.close()
    print('CLeaning up. file closed.')

# with statement
with open("one.txt") as f:
    for line in f:
        print(line, end= " ")

## Logging module
import os, platform, logging
if platform.platform().startswith('Windows'):
    logging_file = os.path.join(os.getenv('HOMEDRIVE'),
    os.getenv('HOMEPATH'))
else:
              logging_file = os.path.join(os.getenv('HOME'), 'test.log')

print('Logging to', logging_file)

## Passing tuple
a, *b = [1,2,3,4]
print(a)
print(b)

# swap
a = 5; b =8
a, b = b, a
print(a, b)

# Single statement block
flag = True
if flag: print("Yes")

## Lambda Forms : used to create new function objects.
points = [{'x' : 2, 'y': 3}, {'x' : 4, 'y' : 1}]
points.sort(key=lambda i : i['y'])
print(points)

# list comprehension
listone = [2, 3, 4]
listtwo = [2*i for i in listone if i > 2]
print(listtwo)

# Receiving tuples and dictionaries in functions
def powersum(power, *args):
    total = 0
    for i in args:
        total += pow(i, power)
    return total

powersum(2, 3, 4)

## assert statement
mylist = ['item']
assert len(mylist) >= 1
mylist.pop()
print(mylist)
assert len(mylist) >= 1

## Escape sequence
cmd = "This is the first sentence. \
This is the second sentence"
print(cmd)