Programming)“paradigms”) - SNE/OS3 Homepage …)Python,)and)Ruby) • “Perl is worse than...

87
Programming “paradigms” Machine code Impera4ve programming (Procedural language) a list or set of instruc4ons telling a computer what to do step by step C, Go, Fortran, Pascal, and BASIC. Declara4ve programming expresses the logic of a computa4on without describing its control flow database query languages (e.g., SQL, XQuery), regular expressions, logic programming, func4onal programming, and configura4on management systems. Objectoriented programming data, and methods of manipula4ng the data, are kept as a single unit called an object.

Transcript of Programming)“paradigms”) - SNE/OS3 Homepage …)Python,)and)Ruby) • “Perl is worse than...

Programming  “paradigms”  •  Machine  code  •  Impera4ve  programming  (Procedural  language)  

–   a  list  or  set  of  instruc4ons  telling  a  computer  what  to  do  step  by  step  à  C,  Go,  Fortran,  Pascal,  and  BASIC.  

•  Declara4ve  programming  –  expresses  the  logic  of  a  computa4on  without  describing  its  control  flow  àdatabase  query  languages  (e.g.,  SQL,  XQuery),  regular  expressions,  logic  programming,  func4onal  programming,  and  configura4on  management  systems.  

•  Object-­‐oriented  programming  –  data,  and  methods  of  manipula4ng  the  data,  are  kept  as  a  single  unit  called  an  object.  

Python  

ESA  2014/2015  Adam  Belloum  

[email protected]      

Material  Prepared  by  Eelco  Schatborn    

Overview  of  the  various  programming  paradigms  according  to  Peter  Van  Roy  

ES:  Python  

•  Today:  1.  Python  introduc4on  2.  Basic  Python:  types,  variables,  statements,  Func4ons  3.  Regular  expression  4.  File  and  I/O  5.  Modules  6.  Packages  7.  Object  Oriented  python  8.  Documenta4on  

We  use  to  study:  Perl,  Python,  and  Ruby    

•  who  is  who?  Match  the  right  language  to  the  right  photo?  

Perl  Python     ruby  1987  1991   1995;    

Yukihiro  Matsumoto  Guido  van  Rossum   Larry  Wall  

hip://www.4obe.com/index.php/content/paperinfo/tpci/index.html  

Perl,  Python,  and  Ruby  •  “Perl is worse than Python because people

wanted it worse.” Larry Wall, 14 Oct 1998 •  “if you look at from 10 KM above,

perl, python, and ruby are the same …”  guido van rossum , pycon-2012

•  “…  From  the  viewpoint  of  what  you  can  do,  therefore,  languages  do  differ  -­‐  but  the  differences  are  limited.  For  example,  Python  and  Ruby  provide  almost  the  same  power  to  the  programmer”. Yukihiro Matsumoto

Why  I  Love  Python                        ©2001    www.BruceEckel.com  

Introduc4on  

•  Wriien  by  Guido  van  Rossum  •  Started  work  in  1990  •  First  release  in  1991  •  Minor  number  release  every  6  months  •  Named  aner  Monty  Python  

     Troll:  “Perl  is  executable  line  noise.  Python  is  executable  pseudo-­‐code.”  

What  is  Python  

•  a  general-­‐purpose  high-­‐level  programming  language  whose  design  philosophy  emphasizes  code  readability.    

•  Python  aims  to  combine  "remarkable  power  with  very  clear  syntax”,  and  its  standard  library  is  large  and  comprehensive.    

•  Its  use  of  indenta4on  for  block  delimiters  is  unusual  among  popular  programming  languages.  

hip://en.wikipedia.org/wiki/Python_%28programming_language%29  

 News  about  Python      •  Keynote:  Guido  Van  Rossum  given  at    pycon-­‐2012  

(Same  talk  was  given  at  the  UvA  in  July  2012)  –  Trolls:  a  ques4on  that  isn’t  meant  as  a  ques4on,  but  to  heckle  •  “Python  Sucks.  Ruby  Rules”  •  “When  will  you  admit  Python  3  is  a  mistake?”  •  “Since  PyPy  is  so  much  faster  than  CPython,  why  not  abandon  CPython”  

•  Etc.  

Notes:  hips://andrew-­‐schoen-­‐pycon-­‐2012-­‐notes.readthedocs.org/en/latest/sunday/keynote.html    

Video:  hip://ontwik.com/python/pycon-­‐2012-­‐keynote-­‐guido-­‐van-­‐rossum/    

10  Reasons  to  Learn  the  Python  Programming  Language  

1.  Reduced  Cluier  2.  It’s  not  backward-­‐compa5ble  in  exchange  for  pain  3.  It  doesn’t  value  performance  over  your  produc5vity  4.  I  don’t  wait  forever  for  a  full  implementa5on  of  the  

language  5.  Marke4ng  people  are  not  involved  6.  You  don’t  have  to  type  so  much  7.  your  guesses  are    usually  right  8.  Python  lets  you  focus  on  concepts  9.  …  

Why  I  Love  Python                        ©2001    www.BruceEckel.com  

Documenta4on  :  Python  (where  to  go  beyond  the  slides  to  learn  …)  

hip://python.org/about/gevngstarted/     $  pydoc  -­‐g  

•  PyPI  -­‐  the  Python  Package  Index  

•   SIG  for  Python  Resource  Cataloguing  

Documenta4on  :  Pydoc  Commandline    

$ pydoc sys!!

Web  browser:    •  pydoc  start  an  HTTP  server  on  the  

local  machine  that  will  serve  documenta4on  to  visi4ng  Web  browsers.    

# start a HTTP server on ! #port 1234! $ pydoc-p 1234 !! ! # start the server and ! #additionally bring up a small! $ pydoc -g !

!

   

Simple  Python  

A  simple  program  to  start  with:        #!/usr/bin/python principal = 1000 # initial amount rate = 0.05 # interest rate numyears = 5 # number of years year = 1 while year <= numyears: principal = principal*(1+rate) print year, principal year += 1  

The  Python  Interpreter  •  Normal  method  for  scrip4ng  using    

#!/usr/bin/python

•  python  is  also  an  interac4ve  interpreter  you  can  interpret  single  lines  of  code  good  for  simple  checking  and  debugging  

$ python mypythonprogram.py!

$ python![GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin!

Type "help", "copyright", "credits" or "license" for more information.!

>>> !

ES:  Python  

•  Today:  1.  Python  introduc4on  2.  Basic  Python:  types,  variables,  statements,  Func4ons  3.  Regular  expression  4.  File  and  I/O  5.  Modules    6.  Packages  7.  Object  Oriented  Python  8.  Documenta4on  

Variables  

•  Python  is  a  dynamically  typed  language:    –  Varibles  can  represent  values  of  different  types  during  the  execu4on  of  the  program.  

•  Names  or  iden4fiers    – must  begin  with  a  non-­‐numeric  character  or  underscore    –  but  may  contain  both  numeric  and  non-­‐numeric  characters  

Troll  about  dynamic  type  “I  don’t  want  my  app  to  fail  with  an  A=ributeError  a?er  running  for  4  hours”  

Dynamic  types  (Weak  typing)  

 •  weakly  typed  programming  languages  are  those  that  support  implicit  type  conversion  

•  Argument  for    –   requires  less  effort  from  the  programmer,  because  the  interpreter  implicitly  performs  certain  conversions  

•  Argument  against  –   dynamic  typing:  “errors  won’t  be  found”  

Troll  about  dynamic  type  “You  write  what  you  want  to  do,  let  Python  worry  about  how”  

Variables:  Numbers  (1)  simple  numbers  the  same  as  with  perl:  •  decimal:  12, -17, 255, … •  octal,  start  with  0: 015, -023, 0777, … •  hexadecimal,  start  with  0x: 0xc, -0x11, 0xff,…

floa4ng  point  numbers:  •  ”one  and  a  quarter":  1.25  But  also  imaginary  numbers:  •  wriien  as  'numberj',    for  example:  1.23j

Variables:  Numbers  (2)  

•  Complex  numbers,  using  imaginary  numbers:  –  wriien  as:    num1 + num2j,    –  or  can  be  created  with:    complex(real, imag)  func4on.  

         (1.0j * 1J) è (-1+0j)

Variables:  Strings  (1)  

•  To  create  string  literals,  enclose  them  in  single,  double  or  triple  quotes.  

Examples:  'Hello World' "Python is groovy"

"""Sino si Pepito Biglangliko?"""

•  The  same  type  of  quote  used  to  start  the  string  must  be  used  to  terminate  it.  

Variables:  String  (2)  

•  Escape  sequences  represent  special  characters:  \n, \t, . . .

•  Both  in  double  quoted  (")  and  single  quoted  (')  strings  

•  For  verba5m  strings  use  raw  strings  using  r'.  .  .  '  >>> print "Hi there! \n \t It's me.\n" Hi there!

It's me.

>>> print r'And me \n \t as well!' And me \n \t as well!

Variables:  Strings  (3)  •  Triple-­‐quoted  strings  using  either  """or  ‘’’  capture  all  the  

text  that  appears  before  the  termina4ng  triple  quote.  

–  Single  and  double  quoted  strings  must  be  on  one  logical  line.  –  Triple-­‐quoted  strings  are  useful  when  contents  of  the  string  span  

mul5ple  lines  of  text.    

–  For  example:  >>> print """ … Usage: thingy [OPTIONS] … -h Display this usage message … -H hostname Hostname to connect to …"""

•  String  literals  can  span  mul5ple  lines  using  a  closing  backslash  ('\')  

•  The  backslash  is  for  syntax  purposes  only,  it  is  not  included  in  the  output  

>>> print "Hi \ … there! \n\ … \t It's me.\n”  

prints:  Hi there! It's me.

Variables:  Strings  (4)  

Variables:  Strings  (5)  •  Strings  are  indexed  like  lists,  star4ng  at  0  •  You  can  use  them  using  the  index  operator  '[i]'  

>>> a = "Hello World" >>> b = a[4] >>> b o

•  Substrings  can  be  used  by  slicing:  `[i:j]’  >>> a[0:6] "Hello " >>> d = a[7:] "World" >>> e = a[3:8] "lo Wo"

Variables:  Strings  (6)  

 Other  data  types  can  be  converted  into  a  string  using  either  str()  or  repr()  func4ons  or  backquotes  (`),  which  are  a  shortcut  nota4on  for  repr().  

Examples

>>> x = 5.2 >>> s = "The value of x is " + str(x) >>> s The value of x is 5.2

>>> s = "The value of y is " + repr(y) >>> s = "The value of y is " + `y`

Operators:  numbers    

•  The  following  operators  for  numbers  apply:            +, -, *, /, //, % …

•  Binary  operators:  C-­‐style  shining  &  masking   1<<16, x&0xff, x|1, ~x, x^y •  Integer  division  truncates    

•  1/2  -­‐>  0  #  1./2.  -­‐>  0.5,  float(1)/2  -­‐>  0.5  \\          >>> width = 20 >>> height = 5*9

>>> width * height 900

Operators:  Strings  

•  Strings  can  be  concatenated  using  a  '+'  •  But  also  by  wri4ng  them  adjacent  to  each  other:  

Examples    >>> print "Hello" + 'Python' HelloPython >>> print "Python " "says" ' Hello!'

Python says Hello!

Play  around  1  

•  Write  a  short  python  prog,  which  when  you  enter  our  name  it  prints  :  Hi  !  <your  name>  .  

•  Hint:  use  raw_input()  to  get  the  input  

>>> name = raw_input('What is your name?\n')

>>> What is your name? OS3

>>> print 'Hi, ' + name + '.' Hi, OS3.

More  Variables:  Lists  (1)  •  lists  and  tuples  are  sequences  of  arbitrary  objects  You  

can  create  a  list  as  follows:  >>> names = [ "Eric", "Trixie", "Coley" ]

     They  too  are  indexed:  >>> a = names[2] a is now "Coley" >>> names[0] = ”Jan" >>> names[0] Jan

•  append  a  new  member  to  the  end  of  a  list  using  append()  >>> names.append("Khamir") >>> names [ "Eric", "Trixie", "Coley", "Khamir" ]

Variables:  Lists  (2)  •  You  can  extract  or  reassign  a  por5on  of  a  list  by  using  the  slicing  

operator.    Examples    

>>> names = ["pusakat","Trixie","Coley","Khamir"] >>>names[0:2]

["pusakat", "Trixie”] >>> names[2:]

["Coley", "Khamir" ]

     •  Use  the  plus  ('+')  operator  to  concatenate  lists.    

>>> a = [1,2,3] + [4,5] >>> a [1,2,3,4,5]

Variables:  Lists  (3)  •  Lists  can  contain  any  kind  of  Python  object  including  

other  lists.  

Example:  >>> a = [1,"Dave”,3,["Mark”,9,[100, 101]],10]

 

•  Nested  lists  are  accessed  as  follows:  >>> a[1] "Dave" >>> a[3] ['Mark', 9, [100, 101]] >>> a[3][2][1] 101

 

[   [   [   [  

Variables:  Tuples  

•  Tuples  are  a  lot  like  lists  –  Tuples  support  most  of  the  same  func4ons  as  a  list  –  They  are  however  immutable  aner  crea4on  –  Used  to  return  mul5ple  values  from  a  func4on  

•  You  can  create  tuples  by  enclosing  a  group  of  values  in  parentheses  ('(.  .  .  )')  or  with  a  comma-­‐separated  list.  

>>> a = (1,4,5,-9,10,'hello!’) >>> b = (7,) # this is a singleton >>> c = a, b >>> c ((1,4,5,-9,10,'hello!’),(7,))

Variables:  Dic4onaries  (1)  •  A  dic5onary  is  an  associa5ve  array  or  hash  table  that  

contains  objects  indexed  by  keys.  •  Only  immutable  objects  can  be  used  as  a  key,  like  

strings,  numbers,  tuples,  etcetera.  •  You  create  a  dic4onary  by  enclosing  values  in  curly  

braces  ('{.  .  .  }'):  >>>>    a = { … "username" : "xenos", … "home" : "/home/xenos", … "uid" :500 … } >>> a ["uid"] 500

Variables:  Dic4onaries  (2)  •  Access  any  value  using  it's  key:  

 >>>  a["username"] "xenos" >>> a["home"] "/home/xenos”

•  To  insert  or  modify  objects,  you  assign  a  value  to  a  key-­‐indexed  name.  

 a["username"] = "trixie" a["home"] = "/home/trixie" a["shell"] = "/usr/bin/tcsh”

Variables:  Dic4onaries  (3)  

Dic4onary  membership  is  tested  with  the  has_key()  method:  if a.has_key("username"): username = a["username"]

else: username = "unknown user"

This  can  also  be  performed  more  compactly  this  way.  username = a.get("username", "unknown”) user")

 Variables:  Dic4onaries  (4)  

•  To  obtain  a  list  of  dic4onary  keys,  use  the  keys()  method.  

 k = a.keys() k = ["username", "home", "uid", "shell" ]

•  Use  the  del  statement  to  remove  an  element  of  a  dic4onary.  

 del a["username"]

Reference  Seman4cs  

•  Assignment  manipulates  references  •  x  =  y  does  not  make  a  copy  of  y  •  x  =  y  makes  x  reference  the  object  y  references  

•  Very  useful;  but  beware!  •  Example:  

>>>  a  =  [1,  2,  3]  >>>  b  =  a  >>>  a.append(4)  >>>  print  b  [1,  2,  3,  4]  

a  

1   2   3  

b  

a  

1   2   3  

b  

4  

a  =  [1,  2,  3]  

a.append(4)  

b  =  a  

a   1   2   3  

Slide  39        ©2001,  2002  Guido  van  Rossum  

a  

1  

b  

a  

1  b  

a  =  1  

a  =  a+1  

b  =  a  

a   1  

2  

Changing  an  Integer  

old  reference  deleted  by  assignment  (a=...)  

new  int  object  created  by  add  operator  (1+1)  

Slide  40        ©2001,  2002  Guido  van  Rossum  

ES:  Python  

•  Today:  1.   Python  introduc4on  2.  Basic  Python:  types,  variables,  statements,  func4ons  3.  Regular  expression  4.  File  and  I/O  5.  Modules    6.  Packages  7.  Object  Oriented  Python  8.  Documenta4on  

Flow  control  

•  A  block  of  code  contains  a  list  of  statements.  •  Code  blocks  are  denoted  by  using  indenta5on  •  Flow  control  can  be  exerted  using  looping  or  condi4onal  Statements.  

Looping  Statements  (1)  

•  Iterates  over  the  members  of  a  sequence,  such  as  a  string,  list  or  tuple.  

>>>for i in ( 1, 2, 3, 4, 5, 6, 7, 8, 9 ): … print "2 to the power %d is %d” % (i, 2**i)

•  Using  the  range()  func4on  you  can  also  give  a  range:  >>> for i in range(1,10):

… print "2 to the power %d is %d” % (i, 2**i)

Looping  Statements  (2)  

•  The  for  statement  can  iterate  over  any  sequence  type  and  isn't  limited  to  sequences  of  integers.  >>>  a = "Hello World” # Print out the characters in a >>> for c in a:

… print c

>>> b = ["Eric", "Trixie", "Coley", "Khamir”]

# Print out the members of a list

>>> for name in b: … print name

Looping  Statements  (3)  

# a = [0,1,2,3,4] # b = [1,2,3,4,5,6,7]

# c = [0,3,6,9,12] # d = [8,7,6,5,4,3,2]

•  The  range(i,  j)  func4on  constructs  a  list  of  integers  with  values  from  i  to  j  à  1.  

•  If  the  star4ng  value  is  omiied,  it's  assumed  to  be  zero.  

•  An  op4onal  stride  or  step  size  can  be  given  as  a  third  •  argument.  

a = range(5)

b = range(1,8) c = range(0,14,3)

d = range(8,1,-1)-1)

Play  around  2  

•  Write  a  short  python  prog,  which  iterate  through  a  list  and  print  the  itera4on  

•  Hint:  use  enumerate()  to  iterate  through  the  list  

my_list = ['john', 'pat', 'gary', 'michael']

for i, name in enumerate(my_list):

print "iteration %i is %s" % (i, name))

Build-­‐in  Func4ons  

Play  Around  3  

•  Write  a  short  prog  in  python,  which  prints    amount  of  money  you  have  to  pay  for  a  given  purchase    let  say:  1  kg  (apples  à1.40  euro/kg),  3  kg  (banana    à1.20  euro/kg)  

•  Hint:  use  dic4onary,     prices = {'apple': 1.40, 'banana': 1.20} my_purchase = { 'apple': 1, 'banana': 6} grocery_bill = sum( prices[fruit] * my_purchase[fruit] \ for fruit in my_purchase) Print 'I owe the grocer $%.2f' % grocery_bill :

Condi4onal  Statements  (1)  

The  if  statement:    if test: ... elif test: ... else:

...

•  The  usual  comparison  operators  for  tes4ng:  <, >, ==, !=, <=, >=

•  They  work  on  most  Python  objects

The  while  statement:  while test:

...

Condi4onal  Statements  (2)  •  if  statement  example:  

if a == 5: print "It's five!" elif a == 6: print "It's six!" else: print "It's something else.”  

•  while  statement  example:  a = 0 while a < 3: a = a +1 print "Counting up to 3..."

Play  Around  4  •  Write  a  short  prog  in  python  which  uses  the  local  4me  to  print  

something  (  your  ac4vi4es  during  the  day).  

•  Hint:  import  4me,  4me.local4me(),    to  get  the  hours  my4me.tm_hour  

import time now = time.localtime() hour = now.tm_hour if hour < 8: print 'sleeping' elif hour < 9: print 'commuting' elif hour < 17: print 'working' elif hour < 18: print 'commuting' elif hour < 20: print 'eating' elif hour < 22: print 'resting' else: print 'sleeping'

ES:  Python  

•  Today:  1.  Python  introduc4on  2.  Basic  Python:  types,  variables,  statements,  Func4ons  3.  Regular  expression  4.  File  and  I/O  5.  Packages  6.  Object  Oriented  Python  7.  Documenta4on  

Func4ons  (1)  

•  func4ons  can  be  defined  using  def  def fibo(n): # calculate fibonacci up to n ...  

•  arguments  can  have  default  values  through  assignment  in  the  defini4on  def fibo(n=100): # n has default value 100

...  

Func4ons  (2)  

def  name(arg1,  arg2,  ...):          """documentaHon"""  #  op4onal  doc  string          statements    return  expression                #  from  func4on  

Func4on  (3)  

•  Return  values  without  a  return  value  a  func4on  returns  None        

•  Example  def fibo(n): # return Fibonacci series up to n result = []

a, b = 0, 1

while b < n: result.append(b) # see below

a, b = b, a+b

return resultturn result

Func4on  (4)  

•  Usage  –  calling  the  example  func4on  without  an  argument      >>> fibo() # call it [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

 –  calling  the  example  func4on  with  an  argument     >>> fibo(50) # call it again [1, 1, 2, 3, 5, 8, 13, 21, 34]

Play  Around  5  

•  Write  a  short  prog  in  python  which  has  a  func4on  with  greets  the  name  given  as  arguments  

def greet(name): print 'hello', name

greet('Jack')

>>> hello, Jack

ES:  Python  

•  Today:  1.   Python  introduc4on  2.  Basic  Python:  types,  variables,  statements,  func4ons  3.  Regular  expression  4.  File  and  I/O  5.  Modules    6.  Packages  7.  Object  Oriented  Python  8.  Documenta4on  

Regular  Expressions  

•  Import  the  re  package  to  use  regular  expressions  •  A  number  of  func4ons  are  available  in  re  package:  

match()

search()

split() sub()

. . .

•  For  more  informa4on  see  the  documenta4on  $  pydoc  re  

 

Play  Around  6  •  If  we    want  to  write  a  prog  in  python,  which  match  a  regexp  to  

validate  a  list  of  phone  number:   import re for test_string in ['555-1212', 'ILLEGAL’]:

if re.match(r'^\d{3}-\d{4}$', test_string): print test_string,'is a valid phone number'

else: print test_string, 'rejected'    

Play  Around  7   >>> import re >>>  m  =  re.match(r"(\w+)  (\w+)",  "Isaac  Newton,  physicist")  >>>  m.group(0)              #  The  en4re  match  'Isaac  Newton'  >>>  m.group(1)              #  The  first  parenthesized  subgroup.  'Isaac'  >>>  m.group(2)              #  The  second  parenthesized  subgroup.  'Newton'  >>>  m.group(1,  2)        #  Mul4ple  arguments  give  us  a  tuple.  ('Isaac’,    ‘Newton’)  

ES:  Python  

•  Today:  1.   Python  introduc4on  2.  Basic  Python:  types,  variables,  statements,  func4ons  3.  Regular  expression  4.  File  and  I/O  5.  Modules    6.  Packages  7.  Object  Oriented  Python  8.  Documenta4on  

Reading Files

name = open("filename") –  opens the given file for reading, and returns a file object

name.read() - file's entire contents as a string

>>> f = open("hours.txt") >>> f.read() '123 Susan 12.5 8.1 7.6 3.2\n 456 Brad 4.0 11.6 6.5 2.7 12\n 789 Jenn 8.0 8.0 8.0 8.0 7.5\n'

hip://www.cs.washington.edu/educa4on/courses/cse143/12wi/python.shtml  

Line-based File Processing

name.readline() - next line from file as a string

–  Returns an empty string if there are no more lines in the file

name.readlines() - file's contents as a list of lines

>>> f = open("hours.txt") >>> f.readline() '123 Susan 12.5 8.1 7.6 3.2\n'

>>> f = open("hours.txt") >>> f.readlines() ['123 Susan 12.5 8.1 7.6 3.2\n', '456 Brad 4.0 11.6 6.5 2.7 12\n', '789 Jenn 8.0 8.0 8.0 8.0 7.5\n']

Writing Files name = open("filename", "w") # write name = open("filename", "a") # append

–  opens file for write (deletes any previous contents) , or –  opens file for append (new data is placed after previous data)

name.write(str) - writes the given string to the file name.close() - closes file once writing is done

>>> out = open("output.txt", "w") >>> out.write("Hello, world!\n") >>> out.write("How are you?") >>> out.close()

>>> open("output.txt").read() 'Hello, world!\nHow are you?'

hip://www.cs.washington.edu/educa4on/courses/cse143/12wi/python.shtml  

Line-based Input Template

•  A file object can be the target of a for ... in loop

•  A template for reading files in Python:

for line in open("filename"): statements

>>> for line in open("hours.txt"): ... print(line.strip()) # strip() removes \n 123 Susan 12.5 8.1 7.6 3.2 456 Brad 4.0 11.6 6.5 2.7 12 789 Jenn 8.0 8.0 8.0 8.0 7.5

hip://www.cs.washington.edu/educa4on/courses/cse143/12wi/python.shtml  

Play  Around  8    •  Write  a  short  prog  in  python,  which  open  all  files  in  you  current  directory  

and  prints  the  content  

•  Hint:  use  glob  module,    –  open  (filename)  to  open  a  file      –  glob.glob('*.py’)  Unix  style  pathname  expansion    –     

import glob # glob supports Unix style pathname extensions python_files = glob.glob('*.py') for fn in sorted(python_files):

print ' ------', fn for line in open(fn): print ' ' + line.rstrip()

print

Play  Around  6  •  Write  a  short  prog  in  python  which  sum  up  integers  in  

the  command  line    •  Hint:  important  sys  module,  try:  …  except  ValueError:    

import sys

try: total = sum(int(arg) for arg in sys.argv[1:]) print 'sum =', total

except ValueError: print 'Please supply integer arguments'

ES:  Python  

•  Today:  1.   Python  introduc4on  2.  Basic  Python:  types,  variables,  statements,  func4ons  3.  Regular  expression  4.  File  and  I/O  5.  Modules    6.  Packages  7.  Object  Oriented  python  8.  Documenta4on  

Modules  (1)  

•  A  module  is  a  file  containing  Python  defini5ons  and  statements.  

•  The  file  name  is  the  module  name  with  the  sux  .py  appended.  

•  Within  a  module,  the  module's  name  (as  a  string)  is  available  as  the  value  of  the  global  variable    

__name__  

Modules  (2)  

•  Example  module  fibo.py  

# Fibonacci numbers module

def fibo(n): # write Fibonacci # series up to n a, b = 0, 1

while b < n: print b a, b = b, a + b

Modules  (3)  •  Import  the  module  with  the  following  command:  

 >>> import fibo •  The  func4ons  are  not  included  directly  •  Using  the  module  name  you  can  access  the  func4ons:  

    >>> import fibo >>> fibo.fibo(1000) 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 >>> fibo.__name__ 'fibo'

Modules  (4)  

•  If  you  intend  to  use  a  func4on  onen  you  can  assign  it  to  a  local  name:  

 >>> fib = fibo.fibo >>> fib(500) 1 1 2 3 5 8 13 21 34 55 89 144 233 377

Modules  (5)  •  The  built-­‐in  func4on  dir()  can  be  used  to  find  out  which  

names  a  module  defines.  It  returns  a  sorted  list  of  strings:   >>> import fibo >>> dir(fibo) ['__builtins__', '__doc__', '__file__', '__name__', '__package__', , 'fibo']

•  It  lists  all  types  of  names:  variables,  modules,  func5ons,  etc.  

•  Without  arguments,  dir()  lists  the  names  you  have  defined  currently  

ES:  Python  

•  Today:  1.   Python  introduc4on  2.  Basic  Python:  types,  variables,  statements,  func4ons  3.  Regular  expression  4.  File  and  I/O  5.  Modules    6.  Packages  7.  Object  Oriented  Python  8.  Documenta4on  

Packages  (1)  

•  Packages  are  a  way  of  structuring  Python's  module  •  namespace  by  using  doNed  module  names".  •  They  hide  module  names  from  other  packages  •  They  are  made  up  of  modules    

Packages  (2)  •  An  example  Package:  

Sound/ Top-level package __init__.py Initialization formats/ file format conversions/ __init__.py wavread.py ... ...

•  __init__.py  files  are  required  to  make  Python  treat  the  directories  as  containing  package  

•  __init__.py can  just  be  an  empty  file,  but  it  can  also  execute  ini4aliza4on  code  for  the  package.  

Packages  (3)  •  Import  individual  modules  from  the  package:  

import sound.effects.echo –  Any  func5ons  in  a  package  must  s4ll  be  referenced  by  their  fully  qualified  name   sound.effects.echo.echofilter( ... )

•  An  alterna4ve  way  of  impor4ng  the  submodule  is:  from sound.effects import echo –  This  also  loads  the  submodule  echo,  and  makes  it  available  without  its  package  prex  

(Sound.Effects).  

echo.echofilter( ... )

•  Import  all  modules  from  the  package:  from sound.effects import *

ES:  Python  

•  Today:  1.   Python  introduc4on  2.  Basic  Python:  types,  variables,  statements,  func4ons  3.  Regular  expression  4.  File  and  I/O  5.  Modules    6.  Packages  7.  Object  Oriented  Python  8.  Documenta4on  

Class  •  Declare  a  class  by:          class  <classname>:  

–  class  defini5ons  introduce  new  a  namespace,  with  its  OWN  scope  –  all  defini4ons  within  a  class  defini4on  are  in  that  new  scope  

•  Use  a  class:                                    from  <classname>  import  *  

–  client  programs  must  import  the  classes  they  use  –  client  programs  used  the  file  name  (lowercase),  not  class  name  

•  classes  can  be  instan5ated  into  instance  objects  

           from myclass import *!

 x = MyClass() # It creates a new instance of the class and assigns this !! ! ! ! ! # object to the local variable x,!! ! ! ! ! # which now represents an instance object.!! ! ! ! ! !!! ! ! ! ! ! ! ! ! ! !  

Class  Method  (Method  Objects)  

•  The  first  argument  of  any  func4on  within  a  class  is  an  object  reference  to  a  class  instance  

   class MyClass: i = 12345 def Hellofuntion(self): return 'hello world’

•  A  class  constructor  is  a  special  method  named    def __init__(self [, param1, ..., param_n]): …

Class  Method  (Method  Objects)  

•  Class  Methods  –  The  first  argument  is  always  the  object  itself       def <methodname>(self, parm1, param2): self.param1 = … self.param2 = … …  

•  Method  objects  are  instan5a5ons  of  func5ons  in  a  class.  

–  the  call  method  object    through  the  instance  object  x.f()

hips://docs.python.org/2/faq/design.html#why-­‐must-­‐self-­‐be-­‐used-­‐explicitly-­‐in-­‐method-­‐defini4ons-­‐and-­‐calls  

Class  instance  (instance  object)  •  You  can  create/delete  aNributes  from  an  instance  object  (not  

from  a  class  object)  –  create  by  assignment  –  delete  by  using  del.  

 x.counter = 1 # creates a new attribute of!! ! ! ! ! ! ! ! # the instance object x

while x.counter < 10:

x.counter *= 2 print x.counter

del x.counter # delete attribute from the !!! !! !! !! # instance object x

Example  of  class  class BankAccount(object):

def __init__(self, initial_balance=0): self.balance = initial_balance

def deposit(self, amount): self.balance += amount

def withdraw(self, amount): self.balance -= amount

def overdrawn(self): return self.balance < 0

my_account = BankAccount(15) my_account.withdraw(5) print my_account.balance

hip://wiki.python.org/moin/SimplePrograms  

Printing Objects

•  By default, Python doesn't know how to print an object:

•  We'd like to be able to print a Point object and have its state shown as the output.

>>> p = Point(5, -2) >>> print p <Point instance at 0x00A8A850>

hip://www.cs.washington.edu/educa4on/courses/cse143/12wi/python.shtml  

Printable Objects: __str__

def __str__(self): return string

–  converts an object into a string (like Java toString) –  invoked automatically when str or print is called def __str__(self): return "(" + str(self.x) + ", " + str(self.y) + ")"

>>> p = Point(5, -2) >>> print p (5, -2) >>> print "The point is " + str(p) + "!" The point is (5, -2)!

hip://www.cs.washington.edu/educa4on/courses/cse143/12wi/python.shtml  

Documenta4on  

 •  Use  the  web,  there  are  a  lot  of  websites  on  python  •  Check  www.python.org  for  help.  •  Use  the  pydoc  tool,  python  manual  pages  etcetera.  

Material  for  these  slides  was  taken  from  hip://www.python.org/doc  hip://www.cs.washington.edu/educa4on/courses/cse143/12wi/python.shtml