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 ...
What is python?	
•  Python is a Interpreted, Interactive, Portable,
Functional / Object-Oriented programing
language.	
•  ...
Why python?	
• 
• 
• 
• 
• 
• 

Multi purpose design (web, os. application ,scienti"c, …)	
Cross platform (wide portabilit...
Why python?	
• 
• 
• 
• 
• 
• 

Many library and module 	
Easy to use (simple & familiar syntax ,few restrictions & rules)...
Introduction to python	
•  Start with python	

–  Set up	
•  Linux , mac os X. and most operating systems have Python 	
• ...
Introduction to python	
•  Strings 	

–  Concatenation “Hello” + “World” -> “HelloWorld”	
–  Repetition “Tabrizu” * 3 -> “...
Introduction to python	
•  Lists	

–  e.g. aList = [631, “python”, [331, “tb”]]	

–  Like indexable arrays, not like linke...
Introduction to python	
•  Tuples	
  	

–  e.g. aTuple = (631, “python”, (611, “SA”))	
–  Unlike	
  lists	
  and	
  like	
...
Introduction to python	
•  Variables 	
–  No need to declare, Not typed but need to initialize 	
–  Almost everything can ...
Introduction to python	
•  Functions 	
–  def FunctionName(arg1, arg2, ...):	
Statements	
	return (expression)	

	
•  Clas...
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...
Tips & Tricks	
None and empty cheaking	
  
my_object = 'Test' # True example!
# my_object = '' or my_object = None # False...
Tips & Tricks	
Divition and $oat numbers	
  

5/2
5.0/2
float(5)/2
5//2
!
	

#
#
#
#

Returns
Returns
Returns
Returns

2!
...
Tips & Tricks	
In one line!	
  
list= [’tabriz', ’tehran', ’shiraz']!
print 'The three are: %s.' % ', '.join(list)!
# prin...
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])!
Squar...
Tips & Tricks	
Lambda & one line for 	
  
numbers = [1,2,3,4,5]!
numbers_under_4 = filter(lambda x: x < 4, numbers)!
numbe...
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]!
# pri...
Tips & Tricks	
Lambda …	
  
numbers = [1,2,3,4,5]!
!
result = reduce(lambda a,b: a*b, numbers)!
!
result = 1!
for number i...
Tips & Tricks	
….	
  

!
!
strings = ['a', 'b', 'c', 'd', 'e’]!
for index, string in enumerate(strings):!
print index, str...
Tips & Tricks	
….	
  
!

!
if all(number < 10 for number in numbers):!
print 'Success!’!
# Output: (nothing)!
!
!
test = T...
Tips & Tricks	
Default value	
  
!
def function(item, stuff = []):!
stuff.append(item)!
print stuff!
!
function(1)!
# prin...
Tips & Tricks	
Arbitrary	
  Numbers	
  of	
  Arguments	
  
!
!
!
def do_something_else(a, b, c, *args, **kwargs):!
print a...
Tips & Tricks	
Decorator	
  
def decorator1(func):!
return lambda: func() + 1!
def decorator2(func):!
def print_func():!
p...
Tips & Tricks	
!
Dict	
  /	
  Object	
  

!
class mydict(dict):!
def __getattr__(self, attr):!
if super(mydict,self).has_k...
More on python	
•  Commercial Usage	
– 
– 
– 
– 

MVC Web programming via web server modules: Tornado, cherrypy ,… 	
Mobil...
More on python	
•  Integrating Python With Other Languages	
–  SWIG - generate extension module from your .h "les	

–  F2P...
Scienti"c module	
•  Numeric	
  Module	
  	
–  NumPy	
  	
  	
  Numerical	
  Python	
  adds	
  a	
  fast,	
  compact,	
  m...
Scienti"c module	
•  Algorithm	
  Module	
  	
  
–  Mlpy	
  	
  Machine	
  Learning	
  Python	
  and	
  high-­‐performance...
Scienti"c module	
•  Grid	
  CompuAng	
  Module	
  
–  PyGlobus	
  Globus	
  toolkit	
  bindings	
  for	
  python	
  	
  
...
Scienti"c module	
•  Other	
  ScienAfic	
  Module	
  	
  
–  ScienAficPython	
  is	
  a	
  collec6on	
  of	
  Python	
  scie...
Scienti"c module	
•  Exmaple	
  Usige	
  Pyevolve 	
–  Installing pakages 	
> apt-­‐get	
  install	
  python-­‐setuptools!...
Scienti"c module	
•  Exmaple	
  Usige	
  Pyevolve
Refrences	
•  Python	
  Homepage	
  	
  
	
  hJp://www.python.org/	
  
•  Python	
  wiki	
  	
  
	
  hJp://wiki.python.org...
Thanks	
  for	
  your	
  aJenAon
Upcoming SlideShare
Loading in …5
×

Python: The Dynamic!

575 views

Published on

Quick introduction to Python programming language.
Presented in CSCCIT2011.

Published in: Technology
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
575
On SlideShare
0
From Embeds
0
Number of Embeds
13
Actions
Shares
0
Downloads
20
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Python: The Dynamic!

  1. 1. csccit2011 University of Tabriz by Omid Mogharian omid.mogharian@gmail.com
  2. 2. outline •  •  •  •  •  •  What is python? Why python? Introduction to python Python programming: Tips & Tricks More on python Scienti"c module
  3. 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. 4. 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.
  5. 5. 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 , …)
  6. 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. 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. 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. 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. 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. 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. 12. Introduction to python •  A simple example
  13. 13. Introduction to python
  14. 14. Introduction to python > this is a static function!
  15. 15. Introduction to python > yes!
  16. 16. Introduction to python > omid!
  17. 17. Introduction to python > AttributeError: cls instance has no attribute 'name’!
  18. 18. Introduction to python > len of prob is 1 and this is a external function!
  19. 19. Introduction to python > this is overwrite function!
  20. 20. Introduction to python > <__main__.cls instance at 0x10aeac440>!
  21. 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. 22. 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'
  23. 23. 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
  24. 24. 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! ! ! ! ! !
  25. 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. 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. 27. 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)! !
  28. 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. 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. 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. 31. Tips & Tricks Default value   ! def function(item, stuff = []):! stuff.append(item)! print stuff! ! function(1)! # prints '[1]’! function(2)! # prints '[1,2]' !!!! ! ! !
  32. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 42. Scienti"c module •  Exmaple  Usige  Pyevolve
  43. 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. 44. Thanks  for  your  aJenAon

×