Python an-intro-python-month-2013

Download Python an-intro-python-month-2013

Post on 14-Jun-2015

4.228 views

Category:

Technology

0 download

Embed Size (px)

TRANSCRIPT

<ul><li> 1. PythonAnIntroduction Arulalan.T arulalant@gmail.com CentreforAtmosphericScience IndianInstituteofTechnologyDelhi </li></ul> <p> 2. PythonisaProgrammingLanguage 3. Therearesomany ProgrammingLanguages. WhyPython? 4. Pythonissimpleandbeautiful 5. PythonisEasytoLearn 6. PythonisFreeOpenSourceSoftware 7. Can Do TextHandling SystemAdministration GUIprogramming WebApplications DatabaseApps ScientificApplications Games NLP ... 8. Hi s t o r y 9. GuidovanRossum FatherofPython 1991 10. PerlJavaPythonRubyPHP 1987199119931995 11. What is Python? 12. Python is... A dynamic,open source programming language with a focus on simplicity and productivity. It has an elegant syntax that is natural to read and easy to write. 13. QuickandEasy IntrepretedScriptingLanguage Variabledeclarationsareunnecessary Variablesarenottyped Syntaxissimpleandconsistent Memorymanagementisautomatic 14. ObjectOrientedProgramming Classes Methods Inheritance Modules etc., 15. Examples! 16. printHelloWorld 17. NoSemicolons! 18. Variables colored_index_cards 19. NoNeedtoDeclareVariableTypes! PythonKnowsEverything! 20. value=10 printvalue value=100.50 printvalue value=ThisisString printvalue*3#Oh! 21. Input 22. name = raw_input(What is Your name?) print "Hello" , name , "Welcome" 23. Indentation 24. Youhavetofollow theIndentation Correctly. Otherwise, Pythonwillbeat you! 25. Discipline Makes Good 26. Flow 27. if score &gt;= 5000 : print You win! elif score &gt;zero numbers[4]numbers[1] &gt;&gt;&gt;FOUR&gt;&gt;&gt;FOUR numbers[2] &gt;&gt;&gt;three 40. MultiDimensionList numbers=[["zero","one"],["two","three", "FOUR"]] numbers[0] &gt;&gt;&gt;["zero","one"] numbers[0][0]numbers[1][1] &gt;&gt;&gt;zero&gt;&gt;&gt;FOUR len(numbers) &gt;&gt;&gt;2 41. SortList primes = [ 11, 5, 7, 2, 13, 3 ] 42. SortList primes = [ 11, 5, 7, 2, 13, 3 ] primes.sort() 43. SortList primes = [ 11, 5, 7, 2, 13, 3 ] primes.sort() &gt;&gt;&gt; [2, 3, 5, 7, 11, 13] 44. SortList names = [ "Shrini", "Bala", "Suresh", "Arul"] names.sort() &gt;&gt;&gt; ["Arul", "Bala","Shrini","Suresh"] names.reverse() &gt;&gt;&gt; ["Suresh","Shrini","Bala","Arul"] 45. MixedList names = [ "Shrini", 10, "Arul", 75.54] names[1]+10 &gt;&gt;&gt; 20 names[2].upper() &gt;&gt;&gt; ARUL 46. AppendonList numbers=[1,3,5,7] numbers.append(9) &gt;&gt;&gt;[1,3,5,7,9] 47. Tuples immutable 48. names=('Arul','Dhastha','Raj') name.append('Selva') Error:Cannotmodifythetuple Tupleisimmutabletype 49. String 50. name='Arul' name[0] &gt;&gt;&gt;'A' myname='Arul'+'alan' &gt;&gt;&gt;'Arulalan' 51. name='Thisispythonstring' name.split('') &gt;&gt;&gt;['This','is','python','string'] comma='Shrini,Arul,Suresh' comma.split(',') &gt;&gt;&gt;['Shrini','Arul','Suresh'] split 52. li=['a','b','c','d'] new=''.join(li) &gt;&gt;&gt;'abcd' new.split('') &gt;&gt;&gt;['a','b','c','d'] join 53. 'small'.upper() &gt;&gt;&gt;'SMALL' 'BIG'.lower() &gt;&gt;&gt;'big' 'mIxEd'.swapcase() &gt;&gt;&gt;'MiXwD' 54. Dictionary 55. menu = { idly : 2.50, dosai : 10.00, coffee : 5.00, ice_cream : 5.00, 100 : Hundred } &gt;&gt;&gt; menu[idly] 2.50 &gt;&gt;&gt; menu[100] Hundred &gt;&gt;&gt; menu.get(tea, None) None 56. uwind = { latitude : (-90, 90), longitude : (0, 360), level : 850, time : 2013-07-17, units : None } uwind.keys() uwind.values() for key, value in uwind.iteritems(): print key, ' = ', value 57. Q)Sotellmenow, 'whatistheuseofdictionary?' 58. Q)Sotellmenow, 'whatistheuseofdictionary?' Doyouknowdictionarycantakeevena functionasvalueinit. 59. Function 60. defsayHello(): print'HelloWorld!'#blockbelongingoffn #Endoffunction sayHello()#callthefunction 61. defprintMax(a,b): ifa&gt;b: printa,'ismaximum' else: printb,'ismaximum' printMax(3,4) 62. defgetMax(a,b): ifa&gt;b: returna printIwillnotbeprinted #endofifa&gt;b: returnb #endofdefgetMax(a,b): mymax=getMax(3,4) printmymax 63. Q)Writeafunctiontoprintthepassed argumentnumberisevenorodd... 64. Q)Writeafunctiontoprintthepassedargumentnumber isevenorodd... defprintEvenOrOdd(no): printThepassedno,no, ifno%2==0:#condition printiseven else: printisodd printEvenOrOdd(10) 65. UsinginbuiltModules 66. #!/usr/bin/python #Filename:using_sys.py importtime print'Thesleepstarted' time.sleep(3) print'Thesleepfinished' 67. #!/usr/bin/python importos os.listdir('/home/arulalan') os.mkdir('/home/arulalan/Fun') printdir(os) 68. MakingOurOwnModules 69. #!/usr/bin/python #Filename:mymodule.py defsayhi(): printHi,thisismymodulespeaking. version='0.1' #Endofmymodule.py 70. #!/usr/bin/python #Filename:mymodule_demo.py importmymodule mymodule.sayhi() print'Version',mymodule.version 71. #!/usr/bin/python #Filename:mymodule_demo2.py frommymoduleimportsayhi,version #Alternative: #frommymoduleimport* sayhi() print'Version',version 72. Class 73. classPerson: pass#Anemptyblock p=Person() printp Classes 74. classPerson: defsayHi(self): print'Hello,howareyou?' p=Person() p.sayHi() Classes 75. classPerson: def__init__(self,name): #likecontstructor self.name=name defsayHi(self): print'Hello,mynameis',self.name p=Person('Arulalan.T') p.sayHi() Classes 76. Inheritance Classes 77. classA: def hello(self): print'Iamsuperclass' classB(A): defbye(self): print'Iamsubclass' p=B() p.hello() p.bye() Classes 78. classA: var=10 def __init__(self): self.public=100 self._protected_='protected' self.__private__='private' ClassB(A): pass p=B() p.__protected__ Classes 79. FileHandling 80. FileWriting 81. poem='''Programmingisfun Whentheworkisdone ifyouwannamakeyourworkalsofun: usePython! ''' f=file('poem.txt','w')#openfor'w'riting f.write(poem)#writetexttofile f.close() 82. Q)HowcanwewriteCSVfiles? f=open('nos.csv','w')#openfor'w'riting fornoinrange(10): f.write(str(no)+','+str(no*no)+'n') f.close() 83. FileReading 84. f=file('poem.txt','r') forlineinf.readlines(): printline f.close() 85. DatabaseIntergration 86. 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() 87. 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() 88. THEEND ofcode:) 89. Howtolearn? 90. PythonShell InteractivePython InstanceResponce Learnasyoutype 91. bpython ipython } teachyouveryeasily 92. http://www.pythontutor.com OnlinePythonEditor&amp;ExecutionVisualizer 93. Pythoncancommunicate With Other Languages 94. C + Python 95. Java + Python 96. GUI With Python 97. Glade + Python + GTK = GUIAPP 98. GLADE 99. UsingGlade+Python 100. Web Web 101. WebFrameWorkinPython 102. importpygame p=pygame.init() #pobjecthassomanymethodstocreateyourownpygame 103. Whyareyoustillplaying videogames,whenyou cancreateyourown! Whynot3Dgames! 104. MatPlotLib2D/3DScientificVisualization Library 105. WhoareallusingPython? and many more... </p>