Τα Πολύ Βασικά για την Python

download Τα Πολύ Βασικά για την Python

of 21

  • date post

    27-Jun-2015
  • Category

    Education

  • view

    140
  • download

    0

Embed Size (px)

description

Τα Πολύ Βασικά για την Python

Transcript of Τα Πολύ Βασικά για την Python

  • 1. Ta Basik gia thn PythonMwusc A. MpountourdhcTmma Majhmatikn Panepisthmou Ptracmboudour@upatras.grFebrouriocMrtioc 2013Mwusc A. Mpountourdhc Ta Basik gia thn Python

2. Pnakac Perieqomnwn1 Egkatstash thc Python2 Ektlesh Programmtwn thc Python3 Arijmo4 Lxeic (Strings)5 Lstec6 Lexik (Dictionaries)7 Tuples8 'Wra, Hmeromhna kai Hmerolgia9 Sugkrseic kai Tropopoiseic Timn (Assignments)10 Brqoi (Loops) kai Dhlseic (Statements)11 Sunartseic (Functions)12 AntikeimenoStrafc (ObjectOriented)ProgrammatismcMwusc A. Mpountourdhc Ta Basik gia thn Python 3. PythonH Python enai mia ermhneutik glssa, dhlad,ekteletai qwrc na qreizetai na persei ap thndiadikasa thc sntaxhc.H epshmh Python diatjetai gia katbasma (mazme odhgec egkatstashc) gia la ta leitourgiksustmata (Mac, Windows kai Linux) ap topython.org, all mpore to st aut na mhn enaih kalterh epilog. 'Enac lgoc enai ti, maz methn Python, jloume na egkatastsoume kaikpoiec llec bibliojkec routinn episthmonikoprogrammatismo (pwc SciPy, Matplotlib, ipythonklp.), oi opoec den diatjentai eke.Mia epshc kal dianom enai thc Enthought, poudnetai dwren gia akadhmak qrsh (kaidiatjetai gia la ta leitourgik sustmata).Shmeiwton ti sta Linux, h Python enaipro-egkatesthmnh.Mwusc A. Mpountourdhc Ta Basik gia thn Python 4. Idiatera gia ta Windows sunisttai h dianomActivePython, en duo llec kalc epilogc enai hPython(x,y) kai h Anaconda CE (h opoa uprqeiepshc kai gia Mac).Ed uprqoun kpoiec odhgec gia thn diadikasaegkatstashc thc Python se Windows.SHMANTIKO: 'Oloi oi kdikec pou jaqrhsimopoisoume sto mjhma qoun dokimasjepnw sthn kdosh 2.7.3 thc Python ki aut thnkdosh prpei na egkatastsete (ant thc pioteleutaac kdoshc 3.x, gia thn opoa qreizontaikpoiec elqistec tropopoiseic stouc kdikecpou ja qrhsimopoiome ed).Mwusc A. Mpountourdhc Ta Basik gia thn Python 5. Ektlesh Programmtwn thc PythonTa progrmmata skript (scripts) thc Pythonenai sunjh arqea keimnou.Kje prgramma thc Python prpei:na qei thn katlhxh *.py,na enai arqeo ektelsimo kaina periqei thn exc prth gramm:#!/ usr / bin / pythonTa progrmmata thc Python mporon na grafonme opoiodpote keimenogrfo (text editor).Mwusc A. Mpountourdhc Ta Basik gia thn Python 6. H ektlesh enc progrmmatoc thc Python mporena gnei ete msa se na termatik (shell)grfontac:python file .py./ file .pyefson bbaia briskmaste ston katlogo poufulssetai to arqeo.Mwusc A. Mpountourdhc Ta Basik gia thn Python 7. Enai mwc protimhta h ektlesh twnprogrammtwn Python msa ap naOloklhrwmno Peribllon Anptuxhc (IntegratedDevelopment Environment , se suntomografa,IDE).Metax polln, duo eqrhsta kai suqnqrhsimopoiomena IDE gia thn Python enai ta exc:IDLESpyder'Ena epiplon prosn twn IDE enai ti apoteloneniaa peribllonta gia thn graf kai thnektlesh programmtwn Python.Mwusc A. Mpountourdhc Ta Basik gia thn Python 8. Arijmo>>> 2 + 35>>> 5 - 8-3>>> 2*36>>> 2**38>>> 2/30. 6666666666666666>>> 2//30>>> 2.0/30. 6666666666666666>>> 3 % 2 # 3 modulo 21>>> x = 3>>> y = 5>>> y/x1. 6666666666666667>>> type (x)>>> type (y/x)Mwusc A. Mpountourdhc Ta Basik gia thn Python 9. Lxeic (Strings)>>> s = " hobbit ">>> s. count ("i")1>>> s. count ("b")2>>> s. startswith (" home ")False>>> s. startswith (" hob ")True>>> s. endswith ("t")True>>> s. upper ()'HOBBIT '>>> r = s. replace ("bb","b")>>> r. replace ("o","a")'habit '>>> s[0]'h'>>> s[3]'b'>>> s[10]IndexError : string index out of range>>> s[1], s[3], s[5]('o', 'b', 't')>>> s[0:4]'hobb '>>> s[:4]'hobb '>>> s[2:]'bbit '>>> s[3:]'bit '>>> s = " hobbit ">>> s[-1]'t'>>> s[-2]'i'>>> s[-3:]'bit '>>> s * 3' hobbithobbithobbit '>>> t = s. replace ("t","t ")>>> t * 3'hobbit hobbit hobbit '>>> t = " is good ">>> r = (s+t). replace ("h","H")>>> print rHobbit is good>>> r[6]' '>>> r [:]'Hobbit is good '>>> s1 = """Triple quotes can be used to createmulti - line strings , which is usefulwhen you want to record a lot of test .""">>> print s1Triple quotes can be used to createmulti - line strings , which is usefulwhen you want to record a lot of test .Mwusc A. Mpountourdhc Ta Basik gia thn Python 10. Lstec>>> X = [3, 5, 7]>>> sum (X)15>>> max (X), min (X)(7, 3)>>> X[0] = " book ">>> X['book ', 5, 7]>>> del X[2]>>> X['book ', 5]>>> del X[1]>>> Y = X + [" pen ", " table "]>>> Y['book ', 'pen ', 'table ']>>> Z = Y * 2>>> Z['book ', 'pen ', 'table ', 'book ', 'pen ','table ']>>> Z[1:4]['pen ', 'table ', 'book ']>>> U = ["a","b","c","d"]>>> V = ["b1","b2","b3"]>>> U1 = ["a",V,"c","d"] # nested list>>> U1['a', ['b1 ', 'b2 ', 'b3 '], 'c', 'd']>>> U[0] = "z">>> U[2] = "q">>> U. sort () # sorting>>> U['b', 'd', 'q', 'z']>>> s = " book and pen on table ">>> T = s. split (" ")>>> T['book ', 'and ', 'pen ', 'on ', 'table ']>>> del T[1], T[2] # Attention !!!>>> T['book ', 'pen ', 'table ']Mwusc A. Mpountourdhc Ta Basik gia thn Python 11. Lexik (Dictionaries)>>> dict = {"to go": "a verb ", " apple ": "a noun ", " green ": "an adjective "}>>> dict{'green ': 'an adjective ', 'apple ': 'a noun ', 'to go ': 'a verb '}>>> dict [" apple "]'a noun '>>> dict [" apple "] = " not an adverb ">>> dict{'green ': 'an adjective ', 'apple ': 'not an adverb ', 'to go ': 'a verb '}>>> dict [" apple "] = " not an adverb ">>> dict{'green ': 'an adjective ', 'apple ': 'not an adverb ', 'to go ': 'a verb '}>>> dict [" apple "] = "a noun ">>> dict . values ()['an adjective ', 'a noun ', 'a verb ']>>> dict . keys ()['green ', 'apple ', 'to go ']>>> dict = {'Name ': 'Zara ', 'Age ': 7, 'Class ': 'First '}>>> dict{'Age ': 7, 'Name ': 'Zara ', 'Class ': 'First '}>>> dict ['Age '] = 8>>> dict ['School '] = " DPS School ">>> dict{'School ': 'DPS School ', 'Age ': 8, 'Name ': 'Zara ', 'Class ': 'First '}# Another way to update entries>>> dict2 = {'School ': "DPS School "}>>> dict . update ( dict2 )>>> print " Value : %s" % dictValue : {'School ': 'DPS School ', 'Age ': 7, 'Name ': 'Zara ', 'Class ': 'First '}# Deleting dictionary elements>>> del dict ['Name '] # remove entry with key 'Name '>>> dict . clear () # remove all entries in dict>>> del dict # delete entire dictionaryMwusc A. Mpountourdhc Ta Basik gia thn Python 12. Tuples (Lstec me ametblhta stoiqea)>>> tupl = ('physics ', 'chemistry ', 1997 , 2000 )>>> tup2 = (1, 2, 3, 4, 5)>>> tup3 = "a", "b", "c", "d">>> tup4 = () # The stuty tuple>>> tup5 = (50 ,) # To write a tuple containing a single value>>> print " tup1 [0]: ", tup1 [0]tup1 [0]: physics>>> print " tup2 [1:5]: ", tup2 [1:5]tup2 [1:5]: (2, 3, 4, 5)>>> tup6 = tup1 + tup2 # Updating tuples>>> print tup6('physics ', 'chemistry ', 1997 , 2000 , 1, 2, 3, 4, 5)>>> del tup1 # Deleting a tuple# Notice that replacement tupl [0] = "a" does not work in tuples !Mwusc A. Mpountourdhc Ta Basik gia thn Python 13. 'Wra, Hmeromhna kai Hmerolgia>>> import time>>> localtime = time . asctime ( time . localtime ( time . time ()) )>>> print " Local current time :", localtimeLocal current time : Mon Feb 25 12:26:42 2013>>> import calendar>>> cal = calendar . month (2013 , 2)>>> print calFebruary 2013Mo Tu We Th Fr Sa Su1 2 34 5 6 7 8 9 1011 12 13 14 15 16 1718 19 20 21 22 23 2425 26 27 28Mwusc A. Mpountourdhc Ta Basik gia thn Python 14. Sugkrseic kai Tropopoiseic Timn(Assignments)# a == b checks whether a = b is True# or False>>> 6 == 7, 6 == 6(False , True )# a != b checks whether a = b is False# or True# is similar to !=>>> 6 != 7, 6 != 6, 3 5(True , False , True )>>> 6 > 7, 6 > 6, 6 < 7(False , False , True )>>> 6 >= 7, 6 >= 6, 6 >> a = 100>>>if (a == 100 ): print " Value of a is 100"Value of a is 100>>>if (a != 200 ): print " Value of a is not 200 "Value of a is not 200# c = a + b will assigne value of a + b# into c>>> a = 2 + 3>>> a5# c += a is equivalent to c = c + a# and respectively with -=, *= , **= ,# /= , %=>>> a += 4>>> a9>>> a -= 5>>> a4>>> a *= 3>>> a12>>> a **= 2>>> a144>>> a /= 10>>> a14>>> a %= 3>>> a2Mwusc A. Mpountourdhc Ta Basik gia thn Python 15. Brqoi (Loops) kai Dhlseic (Statements)while loop>>> count = 0>>> while ( count < 5):print 'The count is:', countcount = count + 1The count is: 0The count is: 1The count is: 2The count is: 3The count is: 4else used with while>>> count = 0>>> while ( count < 5):print count , " is less than 5"count = count + 1else :print count , " is equal to 5"0 is less than 51 is less than 52 is less than 53 is less than 54 is less than 55 is equal to 5for loop>>> fruits = ['banana ', 'apple ','mango ']>>> for fruit in fruits :print 'This is a:', fruitThis is a fruit : bananaThis is a fruit : appleThis is a fruit : mangoelse used with for>>> for num in range (10 ,20 ):for i in range (2, num ):if num %i == 0:j= num /iprint '%d equals %d * %dbreakelse :print num , 'is a prime number '10 equals 2 * 512 equals 2 * 614 equals 2 * 716 equals 2 * 818 equals 2 * 919 is a prime numberMwusc A. Mpountourdhc Ta Basik gia thn Python 16. Nested for