Sunday 20 August 2017

Python Basic Programs-3

 1. Format method
age = '25' or 25
name = 'manish'
print('{0} was {1} years old when he wrote this book'.format(name, age))


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

3. Keyword based, Manish wrote a Byte of Python
print('{name} wrote {book}'.format(name='Manish',book='A Byte of Python'))

4. 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)
#ALITER
print\
       (s)

5.Break statement

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

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

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

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

9. Default argument
def say(message, times = 1):
    print(message * times)

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

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

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

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

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

14. 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__)

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

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

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

17. Dir function
import sys
print(dir(sys))
print(dir())

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

19. 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]))

20. Dictionary
ab = {'Manish'  : 'manish.bidsar@hotmail.com',
      'Mohan'   : 'mohan@hotmail.com',
      'Rahul'     : 'Rahul@hotmail.com',
      }
print('Manish addres is: ', ab['Manish'])
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'])

21. Sequence
shoplist = ['apple','mango','carrot','banana']
name = 'Manish'
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])

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

23. 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

24. Strings
name = 'manish'
if name.startswith('man'):
    print('Yes, the string starts with "man"')
if 'a' in name:
    print('Yes, it contains the string "a"')
if name.find('ish') != -1:
    print('Yes, it contains the string "ish"')
delimiter = '_*_'
mylist = ['USA','UK', 'India', 'Nepal']
print(delimiter.join(mylist))

25. Import
import os
import time
source = '/Users/manishpython_training'
target_dir = '/Users/manish/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')

26. Classes
class Person():
    pass
p = Person()
print(p)

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

#ALITER
Person().sayHi()

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

29. 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()

30. 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('Manish', 25, 80)

print() # print blank line

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

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

32.  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()

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

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

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

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

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

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

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

40. Swap to values.
a = 5; b =8
a, b = b, a
print(a, b)

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

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

43. List comprehension
listone = [2, 3, 4]
listtwo = [2*i for i in listone if i > 2]
print(listtwo)

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

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

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



1 comment:

  1. We as a team of real-time industrial experience with a lot of knowledge in developing applications in python programming , aws training , ccna training (7+ years) will ensure that we will deliver our best in python training in chennai. , and we believe that no one matches us in this context.

    ccna training in chennai
    aws training in chennai
    aws devops training in chennai
    python training
    python training in chennai

    ReplyDelete

Note: only a member of this blog may post a comment.