csccit2011 University of Tabriz by Omid Mogharian omid.mogharian@gmail.com
outline •  •  •  •  •  •  What is python? Why python? Introduction to python Python programming: Tips & Tricks More on python Scienti"c module
What is python? •  Python is a Interpreted, Interactive, Portable, Functional / Object-Oriented programing language. •  Invented by “Guido Van Rossum” in 1991. •  free and open source develop by “python software foundation”, available at www.python.org •  "nal release: Python 2.7.2 , python 3.2.2
Why python? •  •  •  •  •  •  Multi purpose design (web, os. application ,scienti"c, …) Cross platform (wide portability) Both Functional & O.O programming Rapid in Prototyping, strong in enterprise system Integrate with other languages (c/c++, java, fortran, …) Dynamic, Extensible, readable.
Why python? •  •  •  •  •  •  Many library and module Easy to use (simple & familiar syntax ,few restrictions & rules) Automatic memory management (Garbage Collector) Good element (Dictionary, List, … ) Good built-in algorithms (hashing , sorting , …) Many companies & institutions around the world use python (Google, Yahoo, NASA, YouTube, FriendFeed , …)
Introduction to python •  Start with python –  Set up •  Linux , mac os X. and most operating systems have Python •  For windows, download python installer and run it. –  Run •  Use interactive mode by type “python” in Terminal •  “python ["lename].py” run python code "les –  lDE •  Every text editor with a little understanding of code : notepad++,Gedit, jedit, … •  IDLE python editor releasing by “python.org” •  KOMODO is a good one!
Introduction to python •  Strings –  Concatenation “Hello” + “World” -> “HelloWorld” –  Repetition “Tabrizu” * 3 -> “TabrizuTabrizuTabrizu” –  Indexing “Tabrizu”[2] ->“b” , “Tabrizu”[-2] -> “z” –  Slicing “Tabrizu”[1:4] -> “abri” –  Size len(“Tabrizu”)-> 7 –  Comparison “Tabrizu” > “tabrizu” -> fasle –  Search “u” in “Tabrizu” -> true
Introduction to python •  Lists –  e.g. aList = [631, “python”, [331, “tb”]] –  Like indexable arrays, not like linked list –  Same operators as for strings –  More operations append(), insert(), pop(), reverse() and sort() •  Sets –  e.g. aSet=set([‘tabrizu’,’ploytechnic’,’tehran’]) –  add(x), remove(x), discard(x), pop(), clear(), issubset(), issuperset(), … –  Union ‘|’, intersection ‘&’, di#erence ‘#’
Introduction to python •  Tuples   –  e.g. aTuple = (631, “python”, (611, “SA”)) –  Unlike  lists  and  like  strings  &  set  tuples  are  immutable   •  Dic6onaries     –  e.g. adict= {“tabriz”:”python”,”tehran”:”Java”} –  Lookup    adict[“tabriz”] -> ”python”   –  Insert    adict[“value”] = 100   –  Delete    del adict[“value”] –  Presencie    adict.has_key(“tehran”) -> True –  Itera6ons    keys(), values(), items()
Introduction to python •  Variables –  No need to declare, Not typed but need to initialize –  Almost everything can be assigned to a variable (functions, modules, classes) –  All variable are reference (a=b means a & b refer to same object) •  Flow of Control –  if condition : statements (elif condition : statements) [else : statements] –  while condition : statements [else : statements] –  for var in sequence : statements [else : statements] –  Break & Continue
Introduction to python •  Functions –  def FunctionName(arg1, arg2, ...): Statements	return (expression) •  Classes –  class ClassName(BaseClass1, BaseClass2...) :	Statements –  x = ClassName() creates a new instance
Introduction to python •  A simple example
Introduction to python
Introduction to python > this is a static function!
Introduction to python > yes!
Introduction to python > omid!
Introduction to python > AttributeError: cls instance has no attribute 'name’!
Introduction to python > len of prob is 1 and this is a external function!
Introduction to python > this is overwrite function!
Introduction to python > <__main__.cls instance at 0x10aeac440>!
Introduction to python •  Modules –  Usage:  e.g.    import  datetime –  Partial usage: e.g. from datetime import time –  bult-in , installed and beside of code .py "les modules •  example > Python test.py jim! > Hello jim!
Tips & Tricks None and empty cheaking   my_object = 'Test' # True example! # my_object = '' or my_object = None # False example! if len(my_object) > 0:! !print 'my_object is not empty'! ! if len(my_object): # 0 will evaluate to False! print 'my_object is not empty’! if my_object != '':! print 'my_object is not empty’! ! if my_object: # an empty string will evaluate to False! print 'my_object is not empty'
Tips & Tricks Divition and $oat numbers   5/2 5.0/2 float(5)/2 5//2 ! # # # # Returns Returns Returns Returns 2! 2.5! 2.5! 2! from __future__ import division! 5/2 # Returns 2.5! 5.0/2 # Returns 2.5! float(5)/2 # Returns 2.5! 5//2 # Returns 2
Tips & Tricks In one line!   list= [’tabriz', ’tehran', ’shiraz']! print 'The three are: %s.' % ', '.join(list)! # print the tree are tabriz, tehran, shiraz! ! validation= True if list else 'Test is False'! # validation is True! ! ! ! ! !
Tips & Tricks lambda   def add(a,b): return a+b! add2 = lambda a,b: a+b squares = map(lambda a: a*a, [1,2,3,4])! Squares = a*a for a in [1,2,3,4]! squares is now [1,4,9,16]
Tips & Tricks Lambda & one line for   numbers = [1,2,3,4,5]! numbers_under_4 = filter(lambda x: x < 4, numbers)! numbers_under_4 = [number for number in numbers if number < 4]! # numbers_under_4 = [1,2,3]! ! squares = map(lambda x: x*x, filter(lambda x: x < 4, numbers))! squares = [number*number for number in numbers if number < 4]! # square is now [1,4,9]
Tips & Tricks one line for Vs nested for   print [(x, y, x * y) for x in (0,1,2,3) for y in (0,1,2,3) if x < y]! # prints [(0, 1, 0), (0, 2, 0), (0, 3, 0), (1, 2, 2), (1, 3, 3), (2, 3, 6)]! ! for x in (0,1,2,3):! for y in (0,1,2,3):! if x < y:! print (x, y, x*y),! # prints (0, 1, 0) (0, 2, 0) (0, 3, 0) (1, 2, 2) (1, 3, 3) (2, 3, 6)! !
Tips & Tricks Lambda …   numbers = [1,2,3,4,5]! ! result = reduce(lambda a,b: a*b, numbers)! ! result = 1! for number in numbers:! !result *= number! ! # result is now 120
Tips & Tricks ….   ! ! strings = ['a', 'b', 'c', 'd', 'e’]! for index, string in enumerate(strings):! print index, string,! # prints '0 a 1 b 2 c 3 d 4 e’! ! numbers = [1,10,100,1000,10000]! if any(number < 10 for number in numbers):! print 'Success’! # Output: 'Success!'
Tips & Tricks ….   ! ! if all(number < 10 for number in numbers):! print 'Success!’! # Output: (nothing)! ! ! test = True! result = ['Test is False','Test is True'][test]! # result is now 'Test is True’!
Tips & Tricks Default value   ! def function(item, stuff = []):! stuff.append(item)! print stuff! ! function(1)! # prints '[1]’! function(2)! # prints '[1,2]' !!!! ! ! !
Tips & Tricks Arbitrary  Numbers  of  Arguments   ! ! ! def do_something_else(a, b, c, *args, **kwargs):! print a, b, c, args, kwargs! ! ! do_something_else(1,2,3,4,5,6,7,8,9, timeout=1.5)! # prints '1, 2, 3, (4, 5, 6, 7, 8, 9), {"timeout": 1.5}'!
Tips & Tricks Decorator   def decorator1(func):! return lambda: func() + 1! def decorator2(func):! def print_func():! print func()! return print_func! ! @decorator2! @decorator1! def function():! return 41! function()! ! function = decorator2(decorator1(function))! # prints '42'
Tips & Tricks ! Dict  /  Object   ! class mydict(dict):! def __getattr__(self, attr):! if super(mydict,self).has_key(attr):! return super(mydict,self).__getitem__(attr)! ! def __setattr__(self,attr,value):! super(mydict,self).__setattr__(attr,value)! ! adict= {‘apple’:1 ,’banana’:2 , ‘peach’:3}! mdict=mydict(adict)! mdict.orange=10! print mdict.apple, mdict.orange , mdict[‘banana’] , mdict! # prints '1 ! 10 2 {‘apple’:1 ,’banana’:2 , ‘peach’:3 , ‘orange’:10}’!
More on python •  Commercial Usage –  –  –  –  MVC Web programming via web server modules: Tornado, cherrypy ,… Mobile programming :PyObjC, ASE , … Easily connect to famous DB: MSSQL, Mysql , Oracle,… designed for non-relational DB linke Cassandra, MongoDB, CouchDB. What is Non-relational DB!? •  No relation between data, Provide list, vector, nested data "elds •  No force schema & type •  Java script base syntax instead of SQL •  Document-oriented , Key-Value and Object-oriented database
More on python •  Integrating Python With Other Languages –  SWIG - generate extension module from your .h "les –  F2PY - Fortran to Python Interface Generator –  Lython (archived page) - Lisp front-end for Python –  JPype Java for CPython •  Python interpreters –  Cpython a bytecode interpreter (Orginal) –  –  –  –  PyPy  a  JIT  Compiler,  more Speed  &  efficiency   ShedSkin  a  Python  to  C++  programming  language  compiler   Jython a Java implemented of Python   ironpython a .net implemented of python
Scienti"c module •  Numeric  Module   –  NumPy      Numerical  Python  adds  a  fast,  compact,  mul6dimensional  array   facility  to  Python   –  SciPy    Includes  modules  for  linear  algebra,  op6miza6on,  integra6on,   special  func6ons,  sta6s6cs,  and  others.     –  OpenOpt  a  framework  for  numerical  op6miza6on  and  systems  of  linear/ non-­‐linear  equa6ons.     –  ALGLIB    numerical  analysis  library  in  C++  and  C#,  with  Python  interfaces.     –  SpaceFuncs  -­‐  a  tool  for  2D,  3D,  N-­‐dimensional  geometric  modeling  with   possibili6es  of  parametrized  calcula6ons,  numerical  op6miza6on  and   solving  systems  of  geometrical  equa6ons  with  automa6c  differen6a6on.    
Scienti"c module •  Algorithm  Module     –  Mlpy    Machine  Learning  Python  and  high-­‐performance  Python   module  for  Predic6ve  Modeling   –  SciPy  for  signal  and  image  processing,  gene6c  algorithms   –  graph-­‐tool    A  python  module  for  efficient  analysis  of  graphs  (aka.   Networks)   –  Pyevolve is evolutionary algoritm. Machin learning.
Scienti"c module •  Grid  CompuAng  Module   –  PyGlobus  Globus  toolkit  bindings  for  python     –  PEG    Python  Extensions  for  the  Grid     –  Ganga    Grid  job  management  interface.     –  DIANE  Python  user-­‐level  middleware  layer  for  Grids.        
Scienti"c module •  Other  ScienAfic  Module     –  ScienAficPython  is  a  collec6on  of  Python  scien6fic  modules   –  Thuban  is  a  Python  Interac6ve  Geographic  Data  Viewer     –  Matplotlib    hp://matplotlib.sourceforge.net/  -­‐  matplotlib  is  a   python  2D  plo]ng  library     –  Biopython  -­‐  a  set  of  freely  available  tools  for  biological   computa6on  and  bioinforma6cs.   –  PyMol    3D  molecular  viewer  
Scienti"c module •  Exmaple  Usige  Pyevolve –  Installing pakages > apt-­‐get  install  python-­‐setuptools! > easy_install  pyevolve! Or instal .egg pakage > easy_install  /downloads/downloaded_package.egg  !
Scienti"c module •  Exmaple  Usige  Pyevolve
Refrences •  Python  Homepage      hJp://www.python.org/   •  Python  wiki      hJp://wiki.python.org/   •  Google  Code  University      hJp://code.google.com/edu/   •  Python    documentaAon     hJp://docs.python.org/
Thanks  for  your  aJenAon

Python: The Dynamic!

  • 1.
    csccit2011 University of Tabriz byOmid Mogharian omid.mogharian@gmail.com
  • 2.
    outline •  •  •  •  •  •  What is python? Whypython? Introduction to python Python programming: Tips & Tricks More on python Scienti"c module
  • 3.
    What is python? • Python is a Interpreted, Interactive, Portable, Functional / Object-Oriented programing language. •  Invented by “Guido Van Rossum” in 1991. •  free and open source develop by “python software foundation”, available at www.python.org •  "nal release: Python 2.7.2 , python 3.2.2
  • 4.
    Why python? •  •  •  •  •  •  Multi purposedesign (web, os. application ,scienti"c, …) Cross platform (wide portability) Both Functional & O.O programming Rapid in Prototyping, strong in enterprise system Integrate with other languages (c/c++, java, fortran, …) Dynamic, Extensible, readable.
  • 5.
    Why python? •  •  •  •  •  •  Many libraryand module Easy to use (simple & familiar syntax ,few restrictions & rules) Automatic memory management (Garbage Collector) Good element (Dictionary, List, … ) Good built-in algorithms (hashing , sorting , …) Many companies & institutions around the world use python (Google, Yahoo, NASA, YouTube, FriendFeed , …)
  • 6.
    Introduction to python • Start with python –  Set up •  Linux , mac os X. and most operating systems have Python •  For windows, download python installer and run it. –  Run •  Use interactive mode by type “python” in Terminal •  “python ["lename].py” run python code "les –  lDE •  Every text editor with a little understanding of code : notepad++,Gedit, jedit, … •  IDLE python editor releasing by “python.org” •  KOMODO is a good one!
  • 7.
    Introduction to python • Strings –  Concatenation “Hello” + “World” -> “HelloWorld” –  Repetition “Tabrizu” * 3 -> “TabrizuTabrizuTabrizu” –  Indexing “Tabrizu”[2] ->“b” , “Tabrizu”[-2] -> “z” –  Slicing “Tabrizu”[1:4] -> “abri” –  Size len(“Tabrizu”)-> 7 –  Comparison “Tabrizu” > “tabrizu” -> fasle –  Search “u” in “Tabrizu” -> true
  • 8.
    Introduction to python • Lists –  e.g. aList = [631, “python”, [331, “tb”]] –  Like indexable arrays, not like linked list –  Same operators as for strings –  More operations append(), insert(), pop(), reverse() and sort() •  Sets –  e.g. aSet=set([‘tabrizu’,’ploytechnic’,’tehran’]) –  add(x), remove(x), discard(x), pop(), clear(), issubset(), issuperset(), … –  Union ‘|’, intersection ‘&’, di#erence ‘#’
  • 9.
    Introduction to python • Tuples   –  e.g. aTuple = (631, “python”, (611, “SA”)) –  Unlike  lists  and  like  strings  &  set  tuples  are  immutable   •  Dic6onaries     –  e.g. adict= {“tabriz”:”python”,”tehran”:”Java”} –  Lookup    adict[“tabriz”] -> ”python”   –  Insert    adict[“value”] = 100   –  Delete    del adict[“value”] –  Presencie    adict.has_key(“tehran”) -> True –  Itera6ons    keys(), values(), items()
  • 10.
    Introduction to python • Variables –  No need to declare, Not typed but need to initialize –  Almost everything can be assigned to a variable (functions, modules, classes) –  All variable are reference (a=b means a & b refer to same object) •  Flow of Control –  if condition : statements (elif condition : statements) [else : statements] –  while condition : statements [else : statements] –  for var in sequence : statements [else : statements] –  Break & Continue
  • 11.
    Introduction to python • Functions –  def FunctionName(arg1, arg2, ...): Statements return (expression) •  Classes –  class ClassName(BaseClass1, BaseClass2...) : Statements –  x = ClassName() creates a new instance
  • 12.
  • 13.
  • 14.
    Introduction to python >this is a static function!
  • 15.
  • 16.
  • 17.
    Introduction to python > AttributeError:cls instance has no attribute 'name’!
  • 18.
    Introduction to python > lenof prob is 1 and this is a external function!
  • 19.
    Introduction to python >this is overwrite function!
  • 20.
    Introduction to python ><__main__.cls instance at 0x10aeac440>!
  • 21.
    Introduction to python • Modules –  Usage:  e.g.    import  datetime –  Partial usage: e.g. from datetime import time –  bult-in , installed and beside of code .py "les modules •  example > Python test.py jim! > Hello jim!
  • 22.
    Tips & Tricks Noneand empty cheaking   my_object = 'Test' # True example! # my_object = '' or my_object = None # False example! if len(my_object) > 0:! !print 'my_object is not empty'! ! if len(my_object): # 0 will evaluate to False! print 'my_object is not empty’! if my_object != '':! print 'my_object is not empty’! ! if my_object: # an empty string will evaluate to False! print 'my_object is not empty'
  • 23.
    Tips & Tricks Divitionand $oat numbers   5/2 5.0/2 float(5)/2 5//2 ! # # # # Returns Returns Returns Returns 2! 2.5! 2.5! 2! from __future__ import division! 5/2 # Returns 2.5! 5.0/2 # Returns 2.5! float(5)/2 # Returns 2.5! 5//2 # Returns 2
  • 24.
    Tips & Tricks Inone line!   list= [’tabriz', ’tehran', ’shiraz']! print 'The three are: %s.' % ', '.join(list)! # print the tree are tabriz, tehran, shiraz! ! validation= True if list else 'Test is False'! # validation is True! ! ! ! ! !
  • 25.
    Tips & Tricks lambda   def add(a,b): return a+b! add2 = lambda a,b: a+b squares = map(lambda a: a*a, [1,2,3,4])! Squares = a*a for a in [1,2,3,4]! squares is now [1,4,9,16]
  • 26.
    Tips & Tricks Lambda& one line for   numbers = [1,2,3,4,5]! numbers_under_4 = filter(lambda x: x < 4, numbers)! numbers_under_4 = [number for number in numbers if number < 4]! # numbers_under_4 = [1,2,3]! ! squares = map(lambda x: x*x, filter(lambda x: x < 4, numbers))! squares = [number*number for number in numbers if number < 4]! # square is now [1,4,9]
  • 27.
    Tips & Tricks oneline for Vs nested for   print [(x, y, x * y) for x in (0,1,2,3) for y in (0,1,2,3) if x < y]! # prints [(0, 1, 0), (0, 2, 0), (0, 3, 0), (1, 2, 2), (1, 3, 3), (2, 3, 6)]! ! for x in (0,1,2,3):! for y in (0,1,2,3):! if x < y:! print (x, y, x*y),! # prints (0, 1, 0) (0, 2, 0) (0, 3, 0) (1, 2, 2) (1, 3, 3) (2, 3, 6)! !
  • 28.
    Tips & Tricks Lambda…   numbers = [1,2,3,4,5]! ! result = reduce(lambda a,b: a*b, numbers)! ! result = 1! for number in numbers:! !result *= number! ! # result is now 120
  • 29.
    Tips & Tricks ….   ! ! strings = ['a', 'b', 'c', 'd', 'e’]! for index, string in enumerate(strings):! print index, string,! # prints '0 a 1 b 2 c 3 d 4 e’! ! numbers = [1,10,100,1000,10000]! if any(number < 10 for number in numbers):! print 'Success’! # Output: 'Success!'
  • 30.
    Tips & Tricks ….   ! ! if all(number < 10 for number in numbers):! print 'Success!’! # Output: (nothing)! ! ! test = True! result = ['Test is False','Test is True'][test]! # result is now 'Test is True’!
  • 31.
    Tips & Tricks Defaultvalue   ! def function(item, stuff = []):! stuff.append(item)! print stuff! ! function(1)! # prints '[1]’! function(2)! # prints '[1,2]' !!!! ! ! !
  • 32.
    Tips & Tricks Arbitrary  Numbers  of  Arguments   ! ! ! def do_something_else(a, b, c, *args, **kwargs):! print a, b, c, args, kwargs! ! ! do_something_else(1,2,3,4,5,6,7,8,9, timeout=1.5)! # prints '1, 2, 3, (4, 5, 6, 7, 8, 9), {"timeout": 1.5}'!
  • 33.
    Tips & Tricks Decorator   def decorator1(func):! return lambda: func() + 1! def decorator2(func):! def print_func():! print func()! return print_func! ! @decorator2! @decorator1! def function():! return 41! function()! ! function = decorator2(decorator1(function))! # prints '42'
  • 34.
    Tips & Tricks ! Dict  /  Object   ! class mydict(dict):! def __getattr__(self, attr):! if super(mydict,self).has_key(attr):! return super(mydict,self).__getitem__(attr)! ! def __setattr__(self,attr,value):! super(mydict,self).__setattr__(attr,value)! ! adict= {‘apple’:1 ,’banana’:2 , ‘peach’:3}! mdict=mydict(adict)! mdict.orange=10! print mdict.apple, mdict.orange , mdict[‘banana’] , mdict! # prints '1 ! 10 2 {‘apple’:1 ,’banana’:2 , ‘peach’:3 , ‘orange’:10}’!
  • 35.
    More on python • Commercial Usage –  –  –  –  MVC Web programming via web server modules: Tornado, cherrypy ,… Mobile programming :PyObjC, ASE , … Easily connect to famous DB: MSSQL, Mysql , Oracle,… designed for non-relational DB linke Cassandra, MongoDB, CouchDB. What is Non-relational DB!? •  No relation between data, Provide list, vector, nested data "elds •  No force schema & type •  Java script base syntax instead of SQL •  Document-oriented , Key-Value and Object-oriented database
  • 36.
    More on python • Integrating Python With Other Languages –  SWIG - generate extension module from your .h "les –  F2PY - Fortran to Python Interface Generator –  Lython (archived page) - Lisp front-end for Python –  JPype Java for CPython •  Python interpreters –  Cpython a bytecode interpreter (Orginal) –  –  –  –  PyPy  a  JIT  Compiler,  more Speed  &  efficiency   ShedSkin  a  Python  to  C++  programming  language  compiler   Jython a Java implemented of Python   ironpython a .net implemented of python
  • 37.
    Scienti"c module •  Numeric  Module   –  NumPy      Numerical  Python  adds  a  fast,  compact,  mul6dimensional  array   facility  to  Python   –  SciPy    Includes  modules  for  linear  algebra,  op6miza6on,  integra6on,   special  func6ons,  sta6s6cs,  and  others.     –  OpenOpt  a  framework  for  numerical  op6miza6on  and  systems  of  linear/ non-­‐linear  equa6ons.     –  ALGLIB    numerical  analysis  library  in  C++  and  C#,  with  Python  interfaces.     –  SpaceFuncs  -­‐  a  tool  for  2D,  3D,  N-­‐dimensional  geometric  modeling  with   possibili6es  of  parametrized  calcula6ons,  numerical  op6miza6on  and   solving  systems  of  geometrical  equa6ons  with  automa6c  differen6a6on.    
  • 38.
    Scienti"c module •  Algorithm  Module     –  Mlpy    Machine  Learning  Python  and  high-­‐performance  Python   module  for  Predic6ve  Modeling   –  SciPy  for  signal  and  image  processing,  gene6c  algorithms   –  graph-­‐tool    A  python  module  for  efficient  analysis  of  graphs  (aka.   Networks)   –  Pyevolve is evolutionary algoritm. Machin learning.
  • 39.
    Scienti"c module •  Grid  CompuAng  Module   –  PyGlobus  Globus  toolkit  bindings  for  python     –  PEG    Python  Extensions  for  the  Grid     –  Ganga    Grid  job  management  interface.     –  DIANE  Python  user-­‐level  middleware  layer  for  Grids.        
  • 40.
    Scienti"c module •  Other  ScienAfic  Module     –  ScienAficPython  is  a  collec6on  of  Python  scien6fic  modules   –  Thuban  is  a  Python  Interac6ve  Geographic  Data  Viewer     –  Matplotlib    hp://matplotlib.sourceforge.net/  -­‐  matplotlib  is  a   python  2D  plo]ng  library     –  Biopython  -­‐  a  set  of  freely  available  tools  for  biological   computa6on  and  bioinforma6cs.   –  PyMol    3D  molecular  viewer  
  • 41.
    Scienti"c module •  Exmaple  Usige  Pyevolve –  Installing pakages > apt-­‐get  install  python-­‐setuptools! > easy_install  pyevolve! Or instal .egg pakage > easy_install  /downloads/downloaded_package.egg  !
  • 42.
  • 43.
    Refrences •  Python  Homepage      hJp://www.python.org/   •  Python  wiki      hJp://wiki.python.org/   •  Google  Code  University      hJp://code.google.com/edu/   •  Python    documentaAon     hJp://docs.python.org/
  • 44.