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

Python: The Dynamic!

Jan 15, 2015

Download

Technology

Omid Mogharian

Quick introduction to Python programming language.
Presented in CSCCIT2011.
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Python: The Dynamic!

csccit2011 University of Tabriz

by Omid [email protected]

Page 2: Python: The Dynamic!

outline

•  What is python? •  Why python? •  Introduction to python

•  Python programming: Tips & Tricks •  More on python •  Scienti"c module

Page 3: Python: The Dynamic!

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

Page 4: Python: The Dynamic!

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.

Page 5: Python: The Dynamic!

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 , …)

Page 6: Python: The Dynamic!

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!

Page 7: Python: The Dynamic!

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

Page 8: Python: The Dynamic!

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 ‘#’

Page 9: Python: The Dynamic!

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

Page 10: Python: The Dynamic!

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

Page 11: Python: The Dynamic!

Introduction to python

•  Functions –  def FunctionName(arg1, arg2, ...):

Statementsreturn (expression)

•  Classes –  class ClassName(BaseClass1, BaseClass2...) : Statements

–  x = ClassName() creates a new instance

Page 12: Python: The Dynamic!

Introduction to python

•  A simple example

Page 13: Python: The Dynamic!

Introduction to python

Page 14: Python: The Dynamic!

Introduction to python

> this is a static function !

Page 15: Python: The Dynamic!

Introduction to python

> yes!

Page 16: Python: The Dynamic!

Introduction to python

> omid!

Page 17: Python: The Dynamic!

Introduction to python

> AttributeError: cls instance has no attribute 'name’ !

Page 18: Python: The Dynamic!

Introduction to python

> len of prob is 1 and this is a external function !

Page 19: Python: The Dynamic!

Introduction to python

> this is overwrite function !

Page 20: Python: The Dynamic!

Introduction to python

> <__main__.cls instance at 0x10aeac440> !

Page 21: Python: The Dynamic!

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!

Page 22: Python: The Dynamic!

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  

Page 23: Python: The Dynamic!

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  

Page 24: Python: The Dynamic!

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!  

Page 25: Python: The Dynamic!

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  

Page 26: Python: The Dynamic!

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  

Page 27: Python: The Dynamic!

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  

Page 28: Python: The Dynamic!

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 …  

Page 29: Python: The Dynamic!

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

….  

Page 30: Python: The Dynamic!

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

….  

Page 31: Python: The Dynamic!

Tips & Tricks

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

Default value  

Page 32: Python: The Dynamic!

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  

Page 33: Python: The Dynamic!

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  

Page 34: Python: The Dynamic!

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  

Page 35: Python: The Dynamic!

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

 

Page 36: Python: The Dynamic!

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

Page 37: Python: The Dynamic!

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.    

Page 38: Python: The Dynamic!

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.

Page 39: Python: The Dynamic!

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.    

   

Page 40: Python: The Dynamic!

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  

Page 41: Python: The Dynamic!

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 !

Page 42: Python: The Dynamic!

Scienti"c module

•  Exmaple  Usige  Pyevolve

Page 43: Python: The Dynamic!

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/

Page 44: Python: The Dynamic!

Thanks  for  your  aJenAon