Python: The Dynamic!

44
csccit2011 University of Tabriz by Omid Mogharian [email protected]

description

Quick introduction to Python programming language. Presented in CSCCIT2011.

Transcript of Python: The Dynamic!

csccit2011 University of Tabriz

by Omid [email protected]

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, ...):

Statementsreturn (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

•  example

•  Modules –  Usage:  e.g.    import  datetime–  Partial usage: e.g. from datetime import time–  bult-in , installed and beside of code .py "les modules

> Python test.py jim!> Hello jim!

Tips & Tricks

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'

None and empty cheaking  

Tips & Tricks

5/2 # Returns 2! 5.0/2 # Returns 2.5! float(5)/2 # Returns 2.5! 5//2 # Returns 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

Divition and $oat numbers  

Tips & Tricks

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!!!!!!

In one line!  

Tips & Tricks

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]

lambda  

Tips & Tricks

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]

Lambda & one line for  

Tips & Tricks

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)!!

one line for Vs nested for  

Tips & Tricks

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

Lambda …  

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

!def function(item, stuff = []):! stuff.append(item)! print stuff!!function(1)!# prints '[1]’!function(2)!# prints '[1,2]' !!!!!!!

Default value  

Tips & Tricks

!!!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}'!

Arbitrary  Numbers  of  Arguments  

Tips & Tricks

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'

Decorator  

Tips & Tricks !!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}’!!

Dict  /  Object  

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    h\p://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

Or instal .egg pakage

> easy_install  pyevolve !

> easy_install  /downloads/downloaded_package.egg   !

> apt-­‐get  install  python-­‐setuptools !

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