#!/usr/bin/env python
# Filename: method.py
class Person:
def sayHi(self):
print 'Hello, how are you?'
p=Person()
p.sayHi()
# This short example can also be written as Person().sayHi()
#!/usr/bin/env python
# Filename: class_init.py
class Person:
def __init__(self,name):
self.name=name
def sayHi(self):
print 'Hello, my name is',self.name
p=Person('Swaroop')
p.sayHi()
# This short example can also be written as Person('Swaroop').sayHi()
#!/usr/bin/env python
# Filename: objvar.py
class Person:
'''Represents a person.'''
population=0
def __init__(self,name):
'''Initializes the person's data.'''
self.name=name
print '(Initializing %s)' %self.name
#When this person is created, he/she adds to the population
Person.population+=1
def __del__(self):
'''I am dying.'''
print '%s says bye.' %self.name
Person.population-=1
if Person.population==0:
print 'I am the last one.'
else:
print 'There are still %d people left.' %Person.population
def sayHi(self):
'''Greeting by the person.
Really, that's all it does.'''
print 'Hi, my name is %s.' %self.name
def howMany(self):
'''Prints the current population.'''
if Person.population==1:
print 'I am the only person here.'
else:
print 'We have %d persons here.' %Person.population
swaroop=Person('Swaroop')
swaroop.sayHi()
swaroop.howMany()
kalam=Person('Abdul Kalam')
kalam.sayHi()
kalam.howMany()
swaroop.sayHi()
swaroop.howMany()
#!/usr/bin/env python
# Filename: inherit.py
class SchoolMember:
'''Represents any school member.'''
def __init__(self,name,age):
self.name=name
self.age=age
print '(Initialized SchoolMember: %s)' %self.name
def tell(self):
'''Tell my details.'''
print 'Name:"%s" Age:"%s"' %(self.name,self.age),
class Teacher(SchoolMember):
'''Represents a teacher.'''
def __init__(self,name,age,salary):
SchoolMember.__init__(self,name,age)
self.salary=salary
print '(Initialized Teacher: %s)' %self.name
def tell(self):
SchoolMember.tell(self)
print 'Salary: "%d"' %self.salary
class Student(SchoolMember):
'''Represents a student.'''
def __init__(self,name,age,marks):
SchoolMember.__init__(self,name,age)
self.marks=marks
print '(Initialized Student: %s)' %self.name
def tell(self):
SchoolMember.tell(self)
print 'Marks: "%d"' %self.marks
t=Teacher('Mrs. Shrividya',40,30000)
s=Student('Swaroop',22,75)
print # prints a blank line
members=[t,s]
for member in members:
member.tell() # works for both Teachers and Students
#!/usr/bin/env python
# Filename: using_file.py
poem='''\
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!
'''
f=file('poem.txt','w') # open for 'w'riting
f.write(poem) # write text to file
f.close() # close the file
f=file('poem.txt')
# if no mode is specified, 'r'ead mode is assumed by default
while True:
line=f.readline()
if len(line)==0: # Zero length indicates EOF
break
print line,
# Notice comma to avoid automatic newline added by Python
f.close() # close the file
#!/usr/bin/env python
# Filename: pickling.py
import cPickle as p
#import pickle as p
shoplistfile='shoplist.data'
# the name of the file where we will store the object
shoplist=['apple','mango','carrot']
# Write to the file
f=file(shoplistfile,'w')
p.dump(shoplist,f) # dump the object to a file
f.close()
del shoplist # remove the shoplist
# Read back from the storage
f=file(shoplistfile)
storedlist=p.load(f)
print storedlist
#!/usr/bin/env python
# Filename: try_except.py
import sys
try:
s=raw_input('Enter something --> ')
except EOFError:
print '\nWhy did you do an EOF on me?'
sys.exit() # exit the program
except:
print '\nSome error/exception occurred.'
# here, we are not exiting the program
print 'Done'
#!/usr/bin/env python
# Filename: raising.py
class ShortInputException(Exception):
'''A user-defined exception class.'''
def __init__(self,length,atleast):
Exception.__init__(self)
self.length=length
self.atleast=atleast
try:
s=raw_input('Enter something --> ')
if len(s)<3:
raise ShortInputException(len(s),3)
# Other work can continue as usual here
except EOFError:
print '\nWhy did you do an EOF on me?'
except ShortInputException,x:
print 'ShortInputException: The input was of length %d, \
was expecting at least %d' %(x.length,x.atleast)
else:
print 'No exception was raised.'
#!/usr/bin/env python
# Filename: finally.py
import time
try:
f=file('poem.txt')
while True: # our usual file-reading idiom
line=f.readline()
if len(line)==0:
break
time.sleep(2)
print line,
finally:
f.close()
print 'Cleaning up...closed the file'
#!/usr/bin/env python
# Filename: cat.py
import sys
def readfile(filename):
'''Print a file to the standard output.'''
f=file(filename)
while True:
line=f.readline()
if len(line)==0:
break
print line, # notice comma
f.close()
# Script starts from here
if len(sys.argv)<2:
print 'No action specified.'
sys.exit()
if sys.argv[1].startswith('--'):
option=sys.argv[1][2:]
# fetch sys.argv[1] but without the first two characters
if option=='version':
print 'Version 1.2'
elif option=='help':
print '''\
This program prints files to the standard output.
Any number of files can be specified.
Options include:
--version : Prints the version number
--help : Display this help'''
else:
print 'Unknown option.'
sys.exit()
else:
for filename in sys.argv[1:]:
readfile(filename)
#!/usr/bin/env python
# Filename: list_comprehension.py
listone=[2,3,4]
listtwo=[2*i for i in listone if i>2]
print listtwo
#!/usr/bin/env python
# Filename: lambda.py
def make_repeater(n):
return lambda s: s*n
twice=make_repeater(2)
print twice('word')
print twice(5)