Python An Intro - Odp
Python An Intro - Odp
Arulalan.T
[email protected]
CentreforAtmosphericScience
IndianInstituteofTechnologyDelhi
PythonisaProgrammingLanguage
Therearesomany
ProgrammingLanguages.
WhyPython
Pythonissimpleandbeautiful
PythonisEasytoLearn
PythonisFreeOpenSourceSoftware
Can Do
TextHandling
Games
SystemAdministration
NLP
GUIprogramming
WebApplications
...
DatabaseApps
ScientificApplications
Hi s t o r y
GuidovanRossum
FatherofPython
1991
PerlJavaPythonRubyPHP
1987199119931995
What is
Python?
Python is...
QuickandEasy
IntrepretedScriptingLanguage
Variabledeclarationsareunnecessary
Variablesarenottyped
Syntaxissimpleandconsistent
Memorymanagementisautomatic
ObjectOrientedProgramming
Classes
Methods
Inheritance
Modules
etc.,
Examples!
printHelloWorld
NoSemicolons!
Indentation
Youhavetofollow
theIndentation
Correctly.
Otherwise,
Pythonwillbeat
you!
Discipline
Makes
Good
Variables
colored_index_cards
NoNeedtoDeclareVariableTypes!
PythonKnowsEverything!
value=10
printvalue
value=100.50
printvalue
value=ThisisString
printvalue*3
Input
name = raw_input(What
is Your name?)
Flow
Loop
foriinrange(1,5):
printi
else:
print'Theforloopisover'
number=23
running=True
whilerunning:
guess=int(raw_input('Enteraninteger:'))
ifguess==number:
print'Congratulations,youguessedit.'
running=False
elifguess<number:
print'No,itisalittlehigherthanthat.'
else:
print'No,itisalittlelowerthanthat.'
print'Done'
Array
List=Array
numbers=["zero","one","two","three",
"FOUR"]
List=Array
numbers=["zero","one","two","three",
"FOUR"]
numbers[0]
>>>zero
numbers[4]numbers[1]
>>>FOUR>>>FOUR
numbers[2]
>>>three
MultiDimensionList
numbers=[["zero","one"],["two","three",
"FOUR"]]
numbers[0]
>>>["zero","one"]
numbers[0][0]numbers[1][1]
>>>zero>>>FOUR
len(numbers)
>>>2
SortList
SortList
SortList
SortList
names = [ "Shrini", "Bala", "Suresh",
"Arul"]
names.sort()
>>> ["Arul", "Bala","Shrini","Suresh"]
names.reverse()
>>> ["Suresh","Shrini","Bala","Arul"]
MixedList
names = [ "Shrini", 10, "Arul", 75.54]
names[1]+10
>>> 20
names[2].upper()
>>> ARUL
MixedList
names = [ "Shrini", 10, "Arul", 75.54]
names[1]+10
>>> 20
names[2].upper()
>>> ARUL
AppendonList
numbers=[1,3,5,7]
numbers.append(9)
>>>[1,3,5,7,9]
Tuples
immutable
names=('Arul','Dhastha','Raj')
name.append('Selva')
Error:Cannotmodifythetuple
Tupleisimmutabletype
String
name='Arul'
name[0]
>>>'A'
myname='Arul'+'alan'
>>>'Arulalan'
split
name='Thisispythonstring'
name.split('')
>>>['This','is','python','string']
comma='Shrini,Arul,Suresh'
comma.split(',')
join
li=['a','b','c','d']
s=''
new=s.join(li)
>>>abcd
new.split('')
>>>['a','b','c','d']
'small'.upper()
>>>'SMALL'
'BIG'.lower()
>>>'big'
'mIxEd'.swapcase()
>>>'MiXwD'
Dictionary
menu = {
idly
dosai
coffee
ice_cream
100
}
menu[idly]
2.50
menu[100]
Hundred
:
:
:
:
:
2.50,
10.00,
5.00,
5.00,
Hundred
Function
defsayHello():
print'HelloWorld!'#blockbelongingoffn
#Endoffunction
sayHello()#callthefunction
defprintMax(a,b):
ifa>b:
printa,'ismaximum'
else:
printb,'ismaximum'
printMax(3,4)
UsinginbuiltModules
#!/usr/bin/python
#Filename:using_sys.py
importtime
print'Thesleepstarted'
time.sleep(3)
print'Thesleepfinished'
#!/usr/bin/python
importos
os.listdir('/home/arulalan')
os.walk('/home/arulalan')
MakingOurOwnModules
#!/usr/bin/python
#Filename:mymodule.py
defsayhi():
printHi,thisismymodulespeaking.
version='0.1'
#Endofmymodule.py
#!/usr/bin/python
#Filename:mymodule_demo.py
importmymodule
mymodule.sayhi()
print'Version',mymodule.version
#!/usr/bin/python
#Filename:mymodule_demo2.py
frommymoduleimportsayhi,version
#Alternative:
#frommymoduleimport*
sayhi()
print'Version',version
Class
Classes
classPerson:
pass#Anemptyblock
p=Person()
printp
Classes
classPerson:
defsayHi(self):
print'Hello,howareyou?'
p=Person()
p.sayHi()
Classes
classPerson:
def__init__(self,name):
#likecontstructor
self.name=name
defsayHi(self):
print'Hello,mynameis',self.name
p=Person('Arulalan.T')
p.sayHi()
Classes
Inheritance
Classes
classA:
def hello(self):
print'Iamsuperclass'
classB(A):
defbye(self):
print'Iamsubclass'
p=B()
p.hello()
p.bye()
Classes
classA:
Var=10
def __init__(self):
self.public=100
self._protected_='protected'
self.__private__='private'
ClassB(A):
pass
p=B()
FileHandling
FileWriting
poem='''Programmingisfun
Whentheworkisdone
ifyouwannamakeyourworkalsofun:
usePython!
'''
f=file('poem.txt','w')#openfor'w'riting
f.write(poem)#writetexttofile
f.close()
FileReading
f=file('poem.txt','r')
forlineinf.readlines():
printline
f.close()
DatabaseIntergration
importpsycopg2
conn=psycopg2.connect("dbname='pg_database'
user='dbuser'host='localhost'password='dbpass'")
cur=conn.cursor()
cur.execute("""SELECT*frompg_table""")
rows=cur.fetchall()
printrows
cur.close()
conn.close()
importpsycopg2
conn=psycopg2.connect("dbname='pg_database'
user='dbuser'host='localhost'password='dbpass'")
cur=conn.cursor()
cur.execute("'insertintopg_tablevalues(1,'python')"')
conn.commit()
cur.close()
conn.close()
THEEND
ofcode:)
Howtolearn?
PythonShell
InteractivePython
InstanceResponce
Learnasyoutype
bpython
ipython
teachyouveryeasily
Pythoncancommunicate
With
Other
Languages
C
+
Python
Java
+
Python
GUI
With
Python
Glade
+
Python
+
GTK
=
GUIAPP
GLADE
UsingGlade+Python
Web
Web
WebFrameWorkinPython