SlideShare ist ein Scribd-Unternehmen logo
1 von 21
Downloaden Sie, um offline zu lesen
Ta Basikˆ gia thn Python 
Mwus c A. MpountourÐdhc 
Tm ma Majhmatik¸n PanepisthmÐou Pˆtrac 
mboudour@upatras.gr 
Febrouˆrioc–Mˆrtioc 2013 
Mwus c A. MpountourÐdhc Ta Basikˆ gia thn Python
PÐnakac Perieqomènwn 
1 Egkatˆstash thc Python 
2 Ektèlesh Programmˆtwn thc Python 
3 ArijmoÐ 
4 Lèxeic (Strings) 
5 LÐstec 
6 Lexikˆ (Dictionaries) 
7 Tuples 
8 'Wra, HmeromhnÐa kai Hmerolìgia 
9 SugkrÐseic kai Tropopoi seic Tim¸n (Assignments) 
10 Brìqoi (Loops) kai Dhl¸seic (Statements) 
11 Sunart seic (Functions) 
12 Antikeimeno–Straf c (Object–Oriented) 
Programmatismìc 
Mwus c A. MpountourÐdhc Ta Basikˆ gia thn Python
Python 
H Python eÐnai mia ermhneutik  gl¸ssa, dhlad , 
ekteleÐtai qwrÐc na qreiˆzetai na perˆsei apì thn 
diadikasÐa thc sÔntaxhc. 
H epÐshmh Python diatÐjetai gia katèbasma (mazÐ 
me odhgÐec egkatˆstashc) gia ìla ta leitourgikˆ 
sust mata (Mac, Windows kai Linux) apì to 
python.org, allˆ mporeÐ to sˆðt autì na mhn eÐnai 
h kalÔterh epilog . 'Enac lìgoc eÐnai ìti, mazÐ me 
thn Python, jèloume na egkatast soume kai 
kˆpoiec ˆllec biblioj kec routin¸n episthmonikoÔ 
programmatismoÔ (ìpwc SciPy, Matplotlib, ipython 
klp.), oi opoÐec den diatÐjentai ekeÐ. 
Mia epÐshc kal  dianom  eÐnai thc Enthought, pou 
dÐnetai dwreˆn gia akadhmaðk  qr sh (kai 
diatÐjetai gia ìla ta leitourgikˆ sust mata). 
Shmeiwtèon ìti sta Linux, h Python eÐnai 
pro-egkatesthmènh. 
Mwus c A. MpountourÐdhc Ta Basikˆ gia thn Python
IdiaÐtera gia ta Windows sunistˆtai h dianom  
ActivePython, en¸ duo ˆllec kalèc epilogèc eÐnai h 
Python(x,y) kai h Anaconda CE (h opoÐa upˆrqei 
epÐshc kai gia Mac). 
Ed¸ upˆrqoun kˆpoiec odhgÐec gia thn diadikasÐa 
egkatˆstashc thc Python se Windows. 
SHMANTIKO: 'Oloi oi k¸dikec pou ja 
qrhsimopoi soume sto mˆjhma èqoun dokimasjeÐ 
pˆnw sthn èkdosh 2.7.3 thc Python ki aut  thn 
èkdosh prèpei na egkatast sete (antÐ thc pio 
teleutaÐac èkdoshc 3.x, gia thn opoÐa qreiˆzontai 
kˆpoiec elˆqistec tropopoi seic stouc k¸dikec 
pou ja qrhsimopoioÔme ed¸). 
Mwus c A. MpountourÐdhc Ta Basikˆ gia thn Python
Ektèlesh Programmˆtwn thc Python 
Ta progrˆmmata   skript (scripts) thc Python 
eÐnai sun jh arqeÐa keimènou. 
Kˆje prìgramma thc Python prèpei: 
na èqei thn katˆlhxh *.py, 
na eÐnai arqeÐo ektelèsimo kai 
na perièqei thn ex c pr¸th gramm : 
#!/ usr / bin / python 
Ta progrˆmmata thc Python mporoÔn na grafoÔn 
me opoiod pote keimenogrˆfo (text editor). 
Mwus c A. MpountourÐdhc Ta Basikˆ gia thn Python
H ektèlesh enìc progrˆmmatoc thc Python mporeÐ 
na gÐnei eÐte mèsa se èna termatikì (shell) 
grˆfontac: 
python file .py 
  
./ file .py 
efìson bèbaia briskìmaste ston katˆlogo ìpou 
fulˆssetai to arqeÐo. 
Mwus c A. MpountourÐdhc Ta Basikˆ gia thn Python
EÐnai ìmwc protimhtèa h ektèlesh twn 
programmˆtwn Python mèsa apì èna 
Oloklhrwmèno Peribˆllon Anˆptuxhc (Integrated 
Development Environment  , se suntomografÐa, 
IDE). 
MetaxÔ poll¸n, duo eÔqrhsta kai suqnˆ 
qrhsimopoioÔmena IDE gia thn Python eÐnai ta ex c: 
IDLE 
Spyder 
'Ena epiplèon prosìn twn IDE eÐnai ìti apoteloÔn 
eniaÐa peribˆllonta gia thn graf  kai thn 
ektèlesh programmˆtwn Python. 
Mwus c A. MpountourÐdhc Ta Basikˆ gia thn Python
ArijmoÐ 
>>> 2 + 3 
5 
>>> 5 - 8 
-3 
>>> 2*3 
6 
>>> 2**3 
8 
>>> 2/3 
0. 6666666666666666 
>>> 2//3 
0 
>>> 2.0/3 
0. 6666666666666666 
>>> 3 % 2 # 3 modulo 2 
1 
>>> x = 3 
>>> y = 5 
>>> y/x 
1. 6666666666666667 
>>> type (x) 
<type 'int '> 
>>> type (y/x) 
<type 'float '> 
Mwus c A. MpountourÐdhc Ta Basikˆ gia thn Python
Lèxeic (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 r 
Hobbit is good 
>>> r[6] 
' ' 
>>> r [:] 
'Hobbit is good ' 
>>> s1 = """ 
Triple quotes can be used to create 
multi - line strings , which is useful 
when you want to record a lot of test . 
""" 
>>> print s1 
Triple quotes can be used to create 
multi - line strings , which is useful 
when you want to record a lot of test . 
Mwus c A. MpountourÐdhc Ta Basikˆ gia thn Python
LÐstec 
>>> 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 '] 
Mwus c A. MpountourÐdhc Ta Basikˆ gia thn Python
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" % dict 
Value : {'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 dictionary 
Mwus c A. MpountourÐdhc Ta Basikˆ gia thn Python
Tuples (LÐstec me ametˆblhta stoiqeÐa) 
>>> 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 ! 
Mwus c A. MpountourÐdhc Ta Basikˆ gia thn Python
'Wra, HmeromhnÐa kai Hmerolìgia 
>>> import time 
>>> localtime = time . asctime ( time . localtime ( time . time ()) ) 
>>> print " Local current time :", localtime 
Local current time : Mon Feb 25 12:26:42 2013 
>>> import calendar 
>>> cal = calendar . month (2013 , 2) 
>>> print cal 
February 2013 
Mo Tu We Th Fr Sa Su 
1 2 3 
4 5 6 7 8 9 10 
11 12 13 14 15 16 17 
18 19 20 21 22 23 24 
25 26 27 28 
Mwus c A. MpountourÐdhc Ta Basikˆ gia thn Python
SugkrÐseic kai Tropopoi seic Tim¸n 
(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 <= 7 
(False , True , True ) 
# A simple decision 
>>> 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 
>>> a 
5 
# c += a is equivalent to c = c + a 
# and respectively with -=, *= , **= , 
# /= , %= 
>>> a += 4 
>>> a 
9 
>>> a -= 5 
>>> a 
4 
>>> a *= 3 
>>> a 
12 
>>> a **= 2 
>>> a 
144 
>>> a /= 10 
>>> a 
14 
>>> a %= 3 
>>> a 
2 
Mwus c A. MpountourÐdhc Ta Basikˆ gia thn Python
Brìqoi (Loops) kai Dhl¸seic (Statements) 
while loop 
>>> count = 0 
>>> while ( count < 5): 
print 'The count is:', count 
count = count + 1 
The count is: 0 
The count is: 1 
The count is: 2 
The count is: 3 
The count is: 4 
else used with while 
>>> count = 0 
>>> while ( count < 5): 
print count , " is less than 5" 
count = count + 1 
else : 
print count , " is equal to 5" 
0 is less than 5 
1 is less than 5 
2 is less than 5 
3 is less than 5 
4 is less than 5 
5 is equal to 5 
for loop 
>>> fruits = ['banana ', 'apple ', 
'mango '] 
>>> for fruit in fruits : 
print 'This is a:', fruit 
This is a fruit : banana 
This is a fruit : apple 
This is a fruit : mango 
else used with for 
>>> for num in range (10 ,20 ): 
for i in range (2, num ): 
if num %i == 0: 
j= num /i 
print '%d equals %d * %dbreak 
else : 
print num , 'is a prime number ' 
10 equals 2 * 5 
12 equals 2 * 6 
14 equals 2 * 7 
16 equals 2 * 8 
18 equals 2 * 9 
19 is a prime number 
Mwus c A. MpountourÐdhc Ta Basikˆ gia thn Python
Nested for loop 
>>> i = 2 
>>> while (i < 30 ): 
j = 2 
while (j <= (i/j )): 
if not (i%j): break 
j = j + 1 
if (j > i/j) : print i, 
" is prime " 
i = i + 1 
2 is prime 
3 is prime 
5 is prime 
7 is prime 
11 is prime 
13 is prime 
17 is prime 
19 is prime 
23 is prime 
29 is prime 
The if–else Conditional 
Statement 
>>> x = int ( raw_input (" Please enter 
an integer : ")) 
>>> if x % 2: 
print "x is odd " 
else : 
print "x is even " 
Mwus c A. MpountourÐdhc Ta Basikˆ gia thn Python
The range() function 
>>> 
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 
>>> range (5, 10) 
[5, 6, 7, 8, 9] 
>>> range (0, 10 , 3) 
[0, 3, 6, 9] 
>>> range (-10 , -100 , -30) 
[-10 , -40 , -70] 
To iterate over the indices of 
a sequence 
>>> a=[ 'Mary ','had ','a','little ','lamb '] 
>>> for i in range ( len (a )): 
... print i, a[i] 
... 
0 Mary 
1 had 
2 a 
3 little 
4 lamb 
The pass statement: 
It does nothing 
The break statement 
>>> for n in range (2, 7): 
... for x in range (2, n): 
... if n % x == 0: 
print n, 'equals ', x, 
'*', n/x 
break 
... else : 
... print n, 'is a prime number ' 
... 
2 is a prime number 
3 is a prime number 
4 equals 2 * 2 
5 is a prime number 
6 equals 2 * 3 
The continue statement 
>>> for num in range (2, 6): 
... if num % 2 == 0: 
print " Found an even number ", 
num 
continue 
... print " Found a number ", num 
Found an even number 2 
Found a number 3 
Found an even number 4 
Found a number 5 
Mwus c A. MpountourÐdhc Ta Basikˆ gia thn Python
Sunart seic (Functions) 
Seirˆ Fibonacci 
>>> def fib (n): 
# write Fibonacci series up to n 
... a, b = 0, 1 
... while a < n: 
... print a, 
... a, b = b, a+b 
... 
>>> fib ( 2000 ) # call it 
0 1 1 2 3 5 8 13 21 34 55 89 144 233 
377 610 987 1597 
Seirˆ Fibonacci wc lÐsta 
>>> def fib2 (n): 
... result = [] 
... a, b = 0, 1 
... while a < n: 
... result . append (a) 
... a, b = b, a+b 
... return result 
... 
>>> fib2 ( 100 ) # call it 
[0, 1, 1, 2, 3, 5, 8, 13 , 21 , 34 , 55 , 89] 
EukleÐdeia apìstash 
>>> def dist (X, Y): 
Z = [(x - y )** 2 for x, y in 
zip (X, Y)] 
return sum(Z)** 0.5 
>>> X = [1, 2, 3, 4] 
>>> Y = [10 , 9, 8, 7] 
>>> dist (X, Y) 
12. 806248474865697 
Suntelest c susqètishc Pearson 
>>> from itertools import imap 
>>> def pearsoncorrelation (x, y): 
n = len (x) 
sum_x = float ( sum (x)) 
sum_y = float ( sum (y)) 
sum_x_sq = sum( map ( lambda x: pow (x,2), 
x)) 
sum_y_sq = sum( map ( lambda x: pow (x,2), 
y)) 
psum = sum ( imap ( lambda x, y: x*y, x, 
y)) 
num = psum - ( sum_x * sum_y /n) 
den = pow (( sum_x_sq - pow (sum_x ,2)/n) 
* ( sum_y_sq - pow(sum_y ,2)/n),0.5) 
if den == 0: return 0 
return num / den 
>>> pearsoncorrelation (X, Y) 
-1.0 
Mwus c A. MpountourÐdhc Ta Basikˆ gia thn Python
Antikeimeno–Straf c (Object Oriented) Programmatismìc 
DhmiourgÐa Klˆsewn (Classes) 
>>> class Student : 
'Common base class for all students ' 
stuCount = 0 
def __init__ (self , name , year ): 
self . name = name 
self . year = year 
Student . stuCount += 1 
def displayCount ( self ): 
print " Total Students %d" 
% Student . stuCount 
def displayStudent ( self ): 
print " Name : ", self .name , ", 
Year : ", self . year 
>>> stu1 = Employee (" Zara ", 2008 ) 
>>> stu2 = Employee (" Mary ", 2009 ) 
Prosj kh–AfaÐresh Qarakthristik¸n (Attributes) 
>>> stu1 . grade = 7 
# Add an 'grade ' attribute . 
>>> stu1 . grade = 8 
# Modify 'grade ' attribute . 
>>> del stu1 . grade 
# Delete 'grade ' attribute . 
Built­In 
Class Attributes 
>>> print *. __doc__ 
>>> print *. __name__ 
>>> print *. __module__ 
>>> print *. __bases__ 
>>> print *. __dict__ 
Destroying Objects Class 
>>> def __del__ () 
Class Inheritance 
>>> class SubClassName ( ParentClass1 [, 
ParentClass2 , ... ]): 
'Optional class documentation string ' 
class_suite 
Mwus c A. MpountourÐdhc Ta Basikˆ gia thn Python
Parˆdeigma: Epanal yeic thc Tetragwnik c Apeikìnishc 
Tetragwnik  Apeikìnish xt+1 = 4xt(1  xt) 
class QuadMap : 
def __init__ (self , initial_state ): 
self .x = initial_state 
def update ( self ): 
 Apply the quadratic map to 
update the state . 
self .x = 4* self .x*(1- self .x) 
def generate_series (self , n): 
 
Generate and return a trajectory 
of length n, starting at the 
current state . 
 
trajectory = [] 
for i in range (n): 
trajectory . append ( self .x) 
self . update () 
return trajectory 
 q = QuadMap (0.2) 
 q.x 
0. 20000000000000001 
 q. update () 
# Equivalent to QuadMap . update (q) 
 q.x 
0. 64000000000000012 
 q. generate_series (5) 
# The * second * parameter (i.e., n) 
# in the method definition is bound to 5 
[0. 64000000000000012 , 
0. 92159999999999986 , 
0. 28901376000000045 , 
0. 82193922612265036 , 
0. 58542053873419597 ] 
 q.x = 0.4 # Reset the state to 0.4 
 q. generate_series (5) 
[0. 40000000000000002 , 
0. 95999999999999996 , 
0. 15360000000000013 , 
0. 52002816000000029 , 
0. 9983954912280576 ] 
Mwus c A. MpountourÐdhc Ta Basikˆ gia thn Python
Parˆdeigma: Timèc Parag¸gwn PoluwnÔmwn 
## Author : John Stachurski 
class Polynomial : 
def __init__ (self , coefficients ): 
 
Creates an instance of the Polynomial 
class representing p(x) = a_0 x^0 + ... 
+ a_N x^N, where a_i = coefficients [i]. 
 
self . coefficients = coefficients 
def evaluate (self , x): 
y = 0 
for i, a in 
enumerate ( self . coefficients ): 
y += a * x**i 
return y 
def differentiate ( self ): 
new_coefficients = [] 
for i, a in 
enumerate ( self . coefficients ): 
new_coefficients . append (i*a) 
# Remove the first element , 
# which is zero 
del new_coefficients [0] 
# And reset coefficients data to 
# new values 
self . coefficients = 
new_coefficients 
 data = [2, 1, 3] 
 p = Polynomial ( data ) 
# create instance of Polynomial 
 p. evaluate (1) 
6 
 p. coefficients 
[2, 1, 3] 
 p. differentiate () 
# Modifies coefficients of p 
 p. coefficients 
[1, 6] 
 p. evaluate (1) 
7 
Mwus c A. MpountourÐdhc Ta Basikˆ gia thn Python

Weitere ähnliche Inhalte

Was ist angesagt?

Pycon 2011 talk (may not be final, note)
Pycon 2011 talk (may not be final, note)Pycon 2011 talk (may not be final, note)
Pycon 2011 talk (may not be final, note)
c.titus.brown
 
PyCon 2011 talk - ngram assembly with Bloom filters
PyCon 2011 talk - ngram assembly with Bloom filtersPyCon 2011 talk - ngram assembly with Bloom filters
PyCon 2011 talk - ngram assembly with Bloom filters
c.titus.brown
 

Was ist angesagt? (20)

Input and Output
Input and OutputInput and Output
Input and Output
 
Let's golang
Let's golangLet's golang
Let's golang
 
Diving into byte code optimization in python
Diving into byte code optimization in python Diving into byte code optimization in python
Diving into byte code optimization in python
 
FPBrno 2018-05-22: Benchmarking in elixir
FPBrno 2018-05-22: Benchmarking in elixirFPBrno 2018-05-22: Benchmarking in elixir
FPBrno 2018-05-22: Benchmarking in elixir
 
Byterun, a Python bytecode interpreter - Allison Kaptur at NYCPython
Byterun, a Python bytecode interpreter - Allison Kaptur at NYCPythonByterun, a Python bytecode interpreter - Allison Kaptur at NYCPython
Byterun, a Python bytecode interpreter - Allison Kaptur at NYCPython
 
Pycon 2011 talk (may not be final, note)
Pycon 2011 talk (may not be final, note)Pycon 2011 talk (may not be final, note)
Pycon 2011 talk (may not be final, note)
 
Allison Kaptur: Bytes in the Machine: Inside the CPython interpreter, PyGotha...
Allison Kaptur: Bytes in the Machine: Inside the CPython interpreter, PyGotha...Allison Kaptur: Bytes in the Machine: Inside the CPython interpreter, PyGotha...
Allison Kaptur: Bytes in the Machine: Inside the CPython interpreter, PyGotha...
 
Goptuna Distributed Bayesian Optimization Framework at Go Conference 2019 Autumn
Goptuna Distributed Bayesian Optimization Framework at Go Conference 2019 AutumnGoptuna Distributed Bayesian Optimization Framework at Go Conference 2019 Autumn
Goptuna Distributed Bayesian Optimization Framework at Go Conference 2019 Autumn
 
Debugging: A Senior's Skill
Debugging: A Senior's SkillDebugging: A Senior's Skill
Debugging: A Senior's Skill
 
PyCon 2011 talk - ngram assembly with Bloom filters
PyCon 2011 talk - ngram assembly with Bloom filtersPyCon 2011 talk - ngram assembly with Bloom filters
PyCon 2011 talk - ngram assembly with Bloom filters
 
Slicing
SlicingSlicing
Slicing
 
Alias
AliasAlias
Alias
 
Go for the paranoid network programmer
Go for the paranoid network programmerGo for the paranoid network programmer
Go for the paranoid network programmer
 
Strings
StringsStrings
Strings
 
What FizzBuzz can teach us about design
What FizzBuzz can teach us about designWhat FizzBuzz can teach us about design
What FizzBuzz can teach us about design
 
Control Flow
Control FlowControl Flow
Control Flow
 
Introdução ao Retrofit
Introdução ao Retrofit Introdução ao Retrofit
Introdução ao Retrofit
 
A Beginners Guide to Weather & Climate Data, Margriet Groenendijk
A Beginners Guide to Weather & Climate Data, Margriet GroenendijkA Beginners Guide to Weather & Climate Data, Margriet Groenendijk
A Beginners Guide to Weather & Climate Data, Margriet Groenendijk
 
Python Tidbits
Python TidbitsPython Tidbits
Python Tidbits
 
Highlight Utility Styles
Highlight Utility StylesHighlight Utility Styles
Highlight Utility Styles
 

Andere mochten auch

Boudourides & Lenis, Distribution of Groups of Vertices Across Multilayer Net...
Boudourides & Lenis, Distribution of Groups of Vertices Across Multilayer Net...Boudourides & Lenis, Distribution of Groups of Vertices Across Multilayer Net...
Boudourides & Lenis, Distribution of Groups of Vertices Across Multilayer Net...
Moses Boudourides
 
Dye family room furniture selections
Dye family room furniture selectionsDye family room furniture selections
Dye family room furniture selections
Erica Peale
 

Andere mochten auch (19)

Topics of Complex Social Networks: Domination, Influence and Assortativity
Topics of Complex Social Networks: Domination, Influence and AssortativityTopics of Complex Social Networks: Domination, Influence and Assortativity
Topics of Complex Social Networks: Domination, Influence and Assortativity
 
Προγραμματισμός του ρομπότ
Προγραμματισμός του ρομπότΠρογραμματισμός του ρομπότ
Προγραμματισμός του ρομπότ
 
Introduction
IntroductionIntroduction
Introduction
 
Digital, Humanities, Latour and Networks. By Moses A. Boudourides
Digital, Humanities, Latour and Networks. By Moses A. BoudouridesDigital, Humanities, Latour and Networks. By Moses A. Boudourides
Digital, Humanities, Latour and Networks. By Moses A. Boudourides
 
άτομα μόρια-ιόντα (α΄λυκ)
άτομα μόρια-ιόντα (α΄λυκ)άτομα μόρια-ιόντα (α΄λυκ)
άτομα μόρια-ιόντα (α΄λυκ)
 
Peace of mind
Peace of mindPeace of mind
Peace of mind
 
Vivian Murciano Media Sales Director
Vivian Murciano Media Sales DirectorVivian Murciano Media Sales Director
Vivian Murciano Media Sales Director
 
Karthik
KarthikKarthik
Karthik
 
Transitions and Trajectories in Temporal Networks
Transitions and Trajectories in Temporal NetworksTransitions and Trajectories in Temporal Networks
Transitions and Trajectories in Temporal Networks
 
Fotografías
FotografíasFotografías
Fotografías
 
Goo Create: Import and Create
Goo Create: Import and CreateGoo Create: Import and Create
Goo Create: Import and Create
 
纯电动方程式赛车赞助企划书
纯电动方程式赛车赞助企划书纯电动方程式赛车赞助企划书
纯电动方程式赛车赞助企划书
 
Alternativas
AlternativasAlternativas
Alternativas
 
Physical activity
Physical  activityPhysical  activity
Physical activity
 
Boudourides & Lenis, Distribution of Groups of Vertices Across Multilayer Net...
Boudourides & Lenis, Distribution of Groups of Vertices Across Multilayer Net...Boudourides & Lenis, Distribution of Groups of Vertices Across Multilayer Net...
Boudourides & Lenis, Distribution of Groups of Vertices Across Multilayer Net...
 
Goo Create: Interface Overview
Goo Create: Interface OverviewGoo Create: Interface Overview
Goo Create: Interface Overview
 
Dye family room furniture selections
Dye family room furniture selectionsDye family room furniture selections
Dye family room furniture selections
 
Η Επιστήμη των Δικτύων: Μια Πολύ Σύντομη Εισαγωγική Παρουσίαση - 8 Οκτωβρίου ...
Η Επιστήμη των Δικτύων: Μια Πολύ Σύντομη Εισαγωγική Παρουσίαση - 8 Οκτωβρίου ...Η Επιστήμη των Δικτύων: Μια Πολύ Σύντομη Εισαγωγική Παρουσίαση - 8 Οκτωβρίου ...
Η Επιστήμη των Δικτύων: Μια Πολύ Σύντομη Εισαγωγική Παρουσίαση - 8 Οκτωβρίου ...
 
Stmt trisakati kel.1
Stmt trisakati kel.1Stmt trisakati kel.1
Stmt trisakati kel.1
 

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

Palestra sobre Collections com Python
Palestra sobre Collections com PythonPalestra sobre Collections com Python
Palestra sobre Collections com Python
pugpe
 
Python for High School Programmers
Python for High School ProgrammersPython for High School Programmers
Python for High School Programmers
Siva Arunachalam
 
Useful javascript
Useful javascriptUseful javascript
Useful javascript
Lei Kang
 
Python tutorial
Python tutorialPython tutorial
Python tutorial
Rajiv Risi
 
python chapter 1
python chapter 1python chapter 1
python chapter 1
Raghu nath
 
Python chapter 2
Python chapter 2Python chapter 2
Python chapter 2
Raghu nath
 
Python language data types
Python language data typesPython language data types
Python language data types
Harry Potter
 

Ähnlich wie Τα Πολύ Βασικά για την Python (20)

Python Workshop
Python  Workshop Python  Workshop
Python Workshop
 
Pre-Bootcamp introduction to Elixir
Pre-Bootcamp introduction to ElixirPre-Bootcamp introduction to Elixir
Pre-Bootcamp introduction to Elixir
 
Palestra sobre Collections com Python
Palestra sobre Collections com PythonPalestra sobre Collections com Python
Palestra sobre Collections com Python
 
Learn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesLearn 90% of Python in 90 Minutes
Learn 90% of Python in 90 Minutes
 
Python quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung FuPython quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung Fu
 
Python for High School Programmers
Python for High School ProgrammersPython for High School Programmers
Python for High School Programmers
 
Python 1
Python 1Python 1
Python 1
 
Elixir
ElixirElixir
Elixir
 
GE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python ProgrammingGE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python Programming
 
Useful javascript
Useful javascriptUseful javascript
Useful javascript
 
Python
PythonPython
Python
 
Python tutorial
Python tutorialPython tutorial
Python tutorial
 
Beautiful python - PyLadies
Beautiful python - PyLadiesBeautiful python - PyLadies
Beautiful python - PyLadies
 
pa-pe-pi-po-pure Python Text Processing
pa-pe-pi-po-pure Python Text Processingpa-pe-pi-po-pure Python Text Processing
pa-pe-pi-po-pure Python Text Processing
 
Python 101++: Let's Get Down to Business!
Python 101++: Let's Get Down to Business!Python 101++: Let's Get Down to Business!
Python 101++: Let's Get Down to Business!
 
notes.pdf
notes.pdfnotes.pdf
notes.pdf
 
Python tutorial
Python tutorialPython tutorial
Python tutorial
 
python chapter 1
python chapter 1python chapter 1
python chapter 1
 
Python chapter 2
Python chapter 2Python chapter 2
Python chapter 2
 
Python language data types
Python language data typesPython language data types
Python language data types
 

Mehr von Moses Boudourides

Boudourides et al., Transitions and Trajectories in Temporal Networks with Ov...
Boudourides et al., Transitions and Trajectories in Temporal Networks with Ov...Boudourides et al., Transitions and Trajectories in Temporal Networks with Ov...
Boudourides et al., Transitions and Trajectories in Temporal Networks with Ov...
Moses Boudourides
 
Πρότζεκτ για δίκτυα του LinkedIn με την Python
Πρότζεκτ για δίκτυα του LinkedIn με την PythonΠρότζεκτ για δίκτυα του LinkedIn με την Python
Πρότζεκτ για δίκτυα του LinkedIn με την Python
Moses Boudourides
 

Mehr von Moses Boudourides (17)

A bibliometric study on the literature of Open Science and Open Access. By Ts...
A bibliometric study on the literature of Open Science and Open Access. By Ts...A bibliometric study on the literature of Open Science and Open Access. By Ts...
A bibliometric study on the literature of Open Science and Open Access. By Ts...
 
Boudourides: Analysis of Bibliometric Data of Publications on “Computational ...
Boudourides: Analysis of Bibliometric Data of Publications on “Computational ...Boudourides: Analysis of Bibliometric Data of Publications on “Computational ...
Boudourides: Analysis of Bibliometric Data of Publications on “Computational ...
 
Closures and Attributes in Graphs: Shadows of (Dis)Assembled Networks. By Mos...
Closures and Attributes in Graphs: Shadows of (Dis)Assembled Networks. By Mos...Closures and Attributes in Graphs: Shadows of (Dis)Assembled Networks. By Mos...
Closures and Attributes in Graphs: Shadows of (Dis)Assembled Networks. By Mos...
 
Experiments of Friedkin–Johnsen Social Influence on Graphs
Experiments of Friedkin–Johnsen Social Influence on GraphsExperiments of Friedkin–Johnsen Social Influence on Graphs
Experiments of Friedkin–Johnsen Social Influence on Graphs
 
Δίκτυα Λογοτεχνίας: Μια Πρώτη Εισαγωγική Προσέγγιση
Δίκτυα Λογοτεχνίας: Μια Πρώτη Εισαγωγική ΠροσέγγισηΔίκτυα Λογοτεχνίας: Μια Πρώτη Εισαγωγική Προσέγγιση
Δίκτυα Λογοτεχνίας: Μια Πρώτη Εισαγωγική Προσέγγιση
 
Boudourides: Risk in Social Networks: Network Influence & Selection on Minori...
Boudourides: Risk in Social Networks: Network Influence & Selection on Minori...Boudourides: Risk in Social Networks: Network Influence & Selection on Minori...
Boudourides: Risk in Social Networks: Network Influence & Selection on Minori...
 
Multilayerity within multilayerity? On multilayer assortativity in social net...
Multilayerity within multilayerity? On multilayer assortativity in social net...Multilayerity within multilayerity? On multilayer assortativity in social net...
Multilayerity within multilayerity? On multilayer assortativity in social net...
 
Boudourides et al., Transitions and Trajectories in Temporal Networks with Ov...
Boudourides et al., Transitions and Trajectories in Temporal Networks with Ov...Boudourides et al., Transitions and Trajectories in Temporal Networks with Ov...
Boudourides et al., Transitions and Trajectories in Temporal Networks with Ov...
 
Short version of Dominating Sets, Multiple Egocentric Networks and Modularity...
Short version of Dominating Sets, Multiple Egocentric Networks and Modularity...Short version of Dominating Sets, Multiple Egocentric Networks and Modularity...
Short version of Dominating Sets, Multiple Egocentric Networks and Modularity...
 
The hidden rules and open secrets of corporate governance. Preliminary result...
The hidden rules and open secrets of corporate governance. Preliminary result...The hidden rules and open secrets of corporate governance. Preliminary result...
The hidden rules and open secrets of corporate governance. Preliminary result...
 
Dominating Sets, Multiple Egocentric Networks and Modularity Maximizing Clust...
Dominating Sets, Multiple Egocentric Networks and Modularity Maximizing Clust...Dominating Sets, Multiple Egocentric Networks and Modularity Maximizing Clust...
Dominating Sets, Multiple Egocentric Networks and Modularity Maximizing Clust...
 
Πανεπιστήμιο και Κοινωνία των Πολιτών: Στοιχεία & Περιπτώσεις Αποικιοποίησ...
Πανεπιστήμιο και Κοινωνία των Πολιτών: Στοιχεία & Περιπτώσεις Αποικιοποίησ...Πανεπιστήμιο και Κοινωνία των Πολιτών: Στοιχεία & Περιπτώσεις Αποικιοποίησ...
Πανεπιστήμιο και Κοινωνία των Πολιτών: Στοιχεία & Περιπτώσεις Αποικιοποίησ...
 
Διακριτά Μαθηματικά ΙI: Εισαγωγή στη Συνδυαστική. Του Μωυσή Μπουντουρίδη
Διακριτά Μαθηματικά ΙI: Εισαγωγή στη Συνδυαστική. Του Μωυσή ΜπουντουρίδηΔιακριτά Μαθηματικά ΙI: Εισαγωγή στη Συνδυαστική. Του Μωυσή Μπουντουρίδη
Διακριτά Μαθηματικά ΙI: Εισαγωγή στη Συνδυαστική. Του Μωυσή Μπουντουρίδη
 
Διακριτά Μαθηματικά Ι: Εισαγωγή στη Λογική. Του Μωυσή Μπουντουρίδη
Διακριτά Μαθηματικά Ι: Εισαγωγή στη Λογική. Του Μωυσή ΜπουντουρίδηΔιακριτά Μαθηματικά Ι: Εισαγωγή στη Λογική. Του Μωυσή Μπουντουρίδη
Διακριτά Μαθηματικά Ι: Εισαγωγή στη Λογική. Του Μωυσή Μπουντουρίδη
 
Extended Cyclic Cellular Automata: Emulating Social Influence. By Moses A. Bo...
Extended Cyclic Cellular Automata: Emulating Social Influence. By Moses A. Bo...Extended Cyclic Cellular Automata: Emulating Social Influence. By Moses A. Bo...
Extended Cyclic Cellular Automata: Emulating Social Influence. By Moses A. Bo...
 
Μαθαίνοντας την R σε μια ώρα
Μαθαίνοντας την R σε μια ώραΜαθαίνοντας την R σε μια ώρα
Μαθαίνοντας την R σε μια ώρα
 
Πρότζεκτ για δίκτυα του LinkedIn με την Python
Πρότζεκτ για δίκτυα του LinkedIn με την PythonΠρότζεκτ για δίκτυα του LinkedIn με την Python
Πρότζεκτ για δίκτυα του LinkedIn με την Python
 

Kürzlich hochgeladen

The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 

Kürzlich hochgeladen (20)

FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
Plant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxPlant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptx
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 

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

  • 1. Ta Basikˆ gia thn Python Mwus c A. MpountourÐdhc Tm ma Majhmatik¸n PanepisthmÐou Pˆtrac mboudour@upatras.gr Febrouˆrioc–Mˆrtioc 2013 Mwus c A. MpountourÐdhc Ta Basikˆ gia thn Python
  • 2. PÐnakac Perieqomènwn 1 Egkatˆstash thc Python 2 Ektèlesh Programmˆtwn thc Python 3 ArijmoÐ 4 Lèxeic (Strings) 5 LÐstec 6 Lexikˆ (Dictionaries) 7 Tuples 8 'Wra, HmeromhnÐa kai Hmerolìgia 9 SugkrÐseic kai Tropopoi seic Tim¸n (Assignments) 10 Brìqoi (Loops) kai Dhl¸seic (Statements) 11 Sunart seic (Functions) 12 Antikeimeno–Straf c (Object–Oriented) Programmatismìc Mwus c A. MpountourÐdhc Ta Basikˆ gia thn Python
  • 3. Python H Python eÐnai mia ermhneutik  gl¸ssa, dhlad , ekteleÐtai qwrÐc na qreiˆzetai na perˆsei apì thn diadikasÐa thc sÔntaxhc. H epÐshmh Python diatÐjetai gia katèbasma (mazÐ me odhgÐec egkatˆstashc) gia ìla ta leitourgikˆ sust mata (Mac, Windows kai Linux) apì to python.org, allˆ mporeÐ to sˆðt autì na mhn eÐnai h kalÔterh epilog . 'Enac lìgoc eÐnai ìti, mazÐ me thn Python, jèloume na egkatast soume kai kˆpoiec ˆllec biblioj kec routin¸n episthmonikoÔ programmatismoÔ (ìpwc SciPy, Matplotlib, ipython klp.), oi opoÐec den diatÐjentai ekeÐ. Mia epÐshc kal  dianom  eÐnai thc Enthought, pou dÐnetai dwreˆn gia akadhmaðk  qr sh (kai diatÐjetai gia ìla ta leitourgikˆ sust mata). Shmeiwtèon ìti sta Linux, h Python eÐnai pro-egkatesthmènh. Mwus c A. MpountourÐdhc Ta Basikˆ gia thn Python
  • 4. IdiaÐtera gia ta Windows sunistˆtai h dianom  ActivePython, en¸ duo ˆllec kalèc epilogèc eÐnai h Python(x,y) kai h Anaconda CE (h opoÐa upˆrqei epÐshc kai gia Mac). Ed¸ upˆrqoun kˆpoiec odhgÐec gia thn diadikasÐa egkatˆstashc thc Python se Windows. SHMANTIKO: 'Oloi oi k¸dikec pou ja qrhsimopoi soume sto mˆjhma èqoun dokimasjeÐ pˆnw sthn èkdosh 2.7.3 thc Python ki aut  thn èkdosh prèpei na egkatast sete (antÐ thc pio teleutaÐac èkdoshc 3.x, gia thn opoÐa qreiˆzontai kˆpoiec elˆqistec tropopoi seic stouc k¸dikec pou ja qrhsimopoioÔme ed¸). Mwus c A. MpountourÐdhc Ta Basikˆ gia thn Python
  • 5. Ektèlesh Programmˆtwn thc Python Ta progrˆmmata   skript (scripts) thc Python eÐnai sun jh arqeÐa keimènou. Kˆje prìgramma thc Python prèpei: na èqei thn katˆlhxh *.py, na eÐnai arqeÐo ektelèsimo kai na perièqei thn ex c pr¸th gramm : #!/ usr / bin / python Ta progrˆmmata thc Python mporoÔn na grafoÔn me opoiod pote keimenogrˆfo (text editor). Mwus c A. MpountourÐdhc Ta Basikˆ gia thn Python
  • 6. H ektèlesh enìc progrˆmmatoc thc Python mporeÐ na gÐnei eÐte mèsa se èna termatikì (shell) grˆfontac: python file .py   ./ file .py efìson bèbaia briskìmaste ston katˆlogo ìpou fulˆssetai to arqeÐo. Mwus c A. MpountourÐdhc Ta Basikˆ gia thn Python
  • 7. EÐnai ìmwc protimhtèa h ektèlesh twn programmˆtwn Python mèsa apì èna Oloklhrwmèno Peribˆllon Anˆptuxhc (Integrated Development Environment  , se suntomografÐa, IDE). MetaxÔ poll¸n, duo eÔqrhsta kai suqnˆ qrhsimopoioÔmena IDE gia thn Python eÐnai ta ex c: IDLE Spyder 'Ena epiplèon prosìn twn IDE eÐnai ìti apoteloÔn eniaÐa peribˆllonta gia thn graf  kai thn ektèlesh programmˆtwn Python. Mwus c A. MpountourÐdhc Ta Basikˆ gia thn Python
  • 8. ArijmoÐ >>> 2 + 3 5 >>> 5 - 8 -3 >>> 2*3 6 >>> 2**3 8 >>> 2/3 0. 6666666666666666 >>> 2//3 0 >>> 2.0/3 0. 6666666666666666 >>> 3 % 2 # 3 modulo 2 1 >>> x = 3 >>> y = 5 >>> y/x 1. 6666666666666667 >>> type (x) <type 'int '> >>> type (y/x) <type 'float '> Mwus c A. MpountourÐdhc Ta Basikˆ gia thn Python
  • 9. Lèxeic (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 r Hobbit is good >>> r[6] ' ' >>> r [:] 'Hobbit is good ' >>> s1 = """ Triple quotes can be used to create multi - line strings , which is useful when you want to record a lot of test . """ >>> print s1 Triple quotes can be used to create multi - line strings , which is useful when you want to record a lot of test . Mwus c A. MpountourÐdhc Ta Basikˆ gia thn Python
  • 10. LÐstec >>> 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 '] Mwus c A. MpountourÐdhc 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" % dict Value : {'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 dictionary Mwus c A. MpountourÐdhc Ta Basikˆ gia thn Python
  • 12. Tuples (LÐstec me ametˆblhta stoiqeÐa) >>> 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 ! Mwus c A. MpountourÐdhc Ta Basikˆ gia thn Python
  • 13. 'Wra, HmeromhnÐa kai Hmerolìgia >>> import time >>> localtime = time . asctime ( time . localtime ( time . time ()) ) >>> print " Local current time :", localtime Local current time : Mon Feb 25 12:26:42 2013 >>> import calendar >>> cal = calendar . month (2013 , 2) >>> print cal February 2013 Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 Mwus c A. MpountourÐdhc Ta Basikˆ gia thn Python
  • 14. SugkrÐseic kai Tropopoi seic Tim¸n (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 <= 7 (False , True , True ) # A simple decision >>> 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 >>> a 5 # c += a is equivalent to c = c + a # and respectively with -=, *= , **= , # /= , %= >>> a += 4 >>> a 9 >>> a -= 5 >>> a 4 >>> a *= 3 >>> a 12 >>> a **= 2 >>> a 144 >>> a /= 10 >>> a 14 >>> a %= 3 >>> a 2 Mwus c A. MpountourÐdhc Ta Basikˆ gia thn Python
  • 15. Brìqoi (Loops) kai Dhl¸seic (Statements) while loop >>> count = 0 >>> while ( count < 5): print 'The count is:', count count = count + 1 The count is: 0 The count is: 1 The count is: 2 The count is: 3 The count is: 4 else used with while >>> count = 0 >>> while ( count < 5): print count , " is less than 5" count = count + 1 else : print count , " is equal to 5" 0 is less than 5 1 is less than 5 2 is less than 5 3 is less than 5 4 is less than 5 5 is equal to 5 for loop >>> fruits = ['banana ', 'apple ', 'mango '] >>> for fruit in fruits : print 'This is a:', fruit This is a fruit : banana This is a fruit : apple This is a fruit : mango else used with for >>> for num in range (10 ,20 ): for i in range (2, num ): if num %i == 0: j= num /i print '%d equals %d * %dbreak else : print num , 'is a prime number ' 10 equals 2 * 5 12 equals 2 * 6 14 equals 2 * 7 16 equals 2 * 8 18 equals 2 * 9 19 is a prime number Mwus c A. MpountourÐdhc Ta Basikˆ gia thn Python
  • 16. Nested for loop >>> i = 2 >>> while (i < 30 ): j = 2 while (j <= (i/j )): if not (i%j): break j = j + 1 if (j > i/j) : print i, " is prime " i = i + 1 2 is prime 3 is prime 5 is prime 7 is prime 11 is prime 13 is prime 17 is prime 19 is prime 23 is prime 29 is prime The if–else Conditional Statement >>> x = int ( raw_input (" Please enter an integer : ")) >>> if x % 2: print "x is odd " else : print "x is even " Mwus c A. MpountourÐdhc Ta Basikˆ gia thn Python
  • 17. The range() function >>> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> range (5, 10) [5, 6, 7, 8, 9] >>> range (0, 10 , 3) [0, 3, 6, 9] >>> range (-10 , -100 , -30) [-10 , -40 , -70] To iterate over the indices of a sequence >>> a=[ 'Mary ','had ','a','little ','lamb '] >>> for i in range ( len (a )): ... print i, a[i] ... 0 Mary 1 had 2 a 3 little 4 lamb The pass statement: It does nothing The break statement >>> for n in range (2, 7): ... for x in range (2, n): ... if n % x == 0: print n, 'equals ', x, '*', n/x break ... else : ... print n, 'is a prime number ' ... 2 is a prime number 3 is a prime number 4 equals 2 * 2 5 is a prime number 6 equals 2 * 3 The continue statement >>> for num in range (2, 6): ... if num % 2 == 0: print " Found an even number ", num continue ... print " Found a number ", num Found an even number 2 Found a number 3 Found an even number 4 Found a number 5 Mwus c A. MpountourÐdhc Ta Basikˆ gia thn Python
  • 18. Sunart seic (Functions) Seirˆ Fibonacci >>> def fib (n): # write Fibonacci series up to n ... a, b = 0, 1 ... while a < n: ... print a, ... a, b = b, a+b ... >>> fib ( 2000 ) # call it 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 Seirˆ Fibonacci wc lÐsta >>> def fib2 (n): ... result = [] ... a, b = 0, 1 ... while a < n: ... result . append (a) ... a, b = b, a+b ... return result ... >>> fib2 ( 100 ) # call it [0, 1, 1, 2, 3, 5, 8, 13 , 21 , 34 , 55 , 89] EukleÐdeia apìstash >>> def dist (X, Y): Z = [(x - y )** 2 for x, y in zip (X, Y)] return sum(Z)** 0.5 >>> X = [1, 2, 3, 4] >>> Y = [10 , 9, 8, 7] >>> dist (X, Y) 12. 806248474865697 Suntelest c susqètishc Pearson >>> from itertools import imap >>> def pearsoncorrelation (x, y): n = len (x) sum_x = float ( sum (x)) sum_y = float ( sum (y)) sum_x_sq = sum( map ( lambda x: pow (x,2), x)) sum_y_sq = sum( map ( lambda x: pow (x,2), y)) psum = sum ( imap ( lambda x, y: x*y, x, y)) num = psum - ( sum_x * sum_y /n) den = pow (( sum_x_sq - pow (sum_x ,2)/n) * ( sum_y_sq - pow(sum_y ,2)/n),0.5) if den == 0: return 0 return num / den >>> pearsoncorrelation (X, Y) -1.0 Mwus c A. MpountourÐdhc Ta Basikˆ gia thn Python
  • 19. Antikeimeno–Straf c (Object Oriented) Programmatismìc DhmiourgÐa Klˆsewn (Classes) >>> class Student : 'Common base class for all students ' stuCount = 0 def __init__ (self , name , year ): self . name = name self . year = year Student . stuCount += 1 def displayCount ( self ): print " Total Students %d" % Student . stuCount def displayStudent ( self ): print " Name : ", self .name , ", Year : ", self . year >>> stu1 = Employee (" Zara ", 2008 ) >>> stu2 = Employee (" Mary ", 2009 ) Prosj kh–AfaÐresh Qarakthristik¸n (Attributes) >>> stu1 . grade = 7 # Add an 'grade ' attribute . >>> stu1 . grade = 8 # Modify 'grade ' attribute . >>> del stu1 . grade # Delete 'grade ' attribute . Built­In Class Attributes >>> print *. __doc__ >>> print *. __name__ >>> print *. __module__ >>> print *. __bases__ >>> print *. __dict__ Destroying Objects Class >>> def __del__ () Class Inheritance >>> class SubClassName ( ParentClass1 [, ParentClass2 , ... ]): 'Optional class documentation string ' class_suite Mwus c A. MpountourÐdhc Ta Basikˆ gia thn Python
  • 20. Parˆdeigma: Epanal yeic thc Tetragwnik c Apeikìnishc Tetragwnik  Apeikìnish xt+1 = 4xt(1 xt) class QuadMap : def __init__ (self , initial_state ): self .x = initial_state def update ( self ): Apply the quadratic map to update the state . self .x = 4* self .x*(1- self .x) def generate_series (self , n): Generate and return a trajectory of length n, starting at the current state . trajectory = [] for i in range (n): trajectory . append ( self .x) self . update () return trajectory q = QuadMap (0.2) q.x 0. 20000000000000001 q. update () # Equivalent to QuadMap . update (q) q.x 0. 64000000000000012 q. generate_series (5) # The * second * parameter (i.e., n) # in the method definition is bound to 5 [0. 64000000000000012 , 0. 92159999999999986 , 0. 28901376000000045 , 0. 82193922612265036 , 0. 58542053873419597 ] q.x = 0.4 # Reset the state to 0.4 q. generate_series (5) [0. 40000000000000002 , 0. 95999999999999996 , 0. 15360000000000013 , 0. 52002816000000029 , 0. 9983954912280576 ] Mwus c A. MpountourÐdhc Ta Basikˆ gia thn Python
  • 21. Parˆdeigma: Timèc Parag¸gwn PoluwnÔmwn ## Author : John Stachurski class Polynomial : def __init__ (self , coefficients ): Creates an instance of the Polynomial class representing p(x) = a_0 x^0 + ... + a_N x^N, where a_i = coefficients [i]. self . coefficients = coefficients def evaluate (self , x): y = 0 for i, a in enumerate ( self . coefficients ): y += a * x**i return y def differentiate ( self ): new_coefficients = [] for i, a in enumerate ( self . coefficients ): new_coefficients . append (i*a) # Remove the first element , # which is zero del new_coefficients [0] # And reset coefficients data to # new values self . coefficients = new_coefficients data = [2, 1, 3] p = Polynomial ( data ) # create instance of Polynomial p. evaluate (1) 6 p. coefficients [2, 1, 3] p. differentiate () # Modifies coefficients of p p. coefficients [1, 6] p. evaluate (1) 7 Mwus c A. MpountourÐdhc Ta Basikˆ gia thn Python