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 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. 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. 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!
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
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
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'
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. 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
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. 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
Default value
!
def function(item, stuff = []):!
stuff.append(item)!
print stuff!
!
function(1)!
# prints '[1]’!
function(2)!
# prints '[1,2]' !!!!
!
!
!
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