python and vpython - theoretical chemistry group … teorico modellistico 36 functions functions are...
TRANSCRIPT
Seminario Teorico Modellistico 2
What is Python?
It is a programming language created in 1990 by Guido Van Rossum
The Python Philosophy:
Seminario Teorico Modellistico 3
Why Python?✦ Designed to be easy to learn and master
•clean •clear syntax•uses white space to delimit blocks
humans generally do, so why not the language?? ✦ Short
• it is typically one-third one-fifth the size of equivalent C++ or Java code (less to type=less to debug)
✦ Highly portable• run almost everywhere• porting a Python code from one platform to another it is just
a matter of copy-paste✦ Extensible
• large connection of prebuilt and portable functionality, standard libraries
Seminario Teorico Modellistico 4
Interpreted LanguagePython is an interpreted language or a ”dynamic language”
interpreted compiled
source code statements
Byte code
source code statements
binary machine code
Python interpreterexecutes the program step-by-step
platformindependent
executable file
Seminario Teorico Modellistico 5
What can i do with Python?
Not only a scripting language, but also an implementing standalone program
It is famous to be a scripting language. The scripting refers a “glue” layer to control and direct other applications
•Internet scripting•Good match for graphical user interface programs (GUIs)•Interface for all commonly used database (Oracle)
•Numerical and scientific programming (NumPy)•3D scientific programming (VPython)•Game programming (Pygame)•Image processing (PyOpenGL)
Seminario Teorico Modellistico 6
Who uses Python?
Some of the most famous users:
•Google:make extensive use of Python in its web search system and employs the Python’s creator
•YouTube:its video sharing service is largely written in Python
•BitTorrent:the popular peer-to-peer file sharing system is a Python program
Seminario Teorico Modellistico 8
Python Shell✦ Modes:
• FilePython programs and modules are written as text files with a .py extension
Programs and modules are differentiated only by the way they are called:
•.py files executed directly are programs•.py files referenced via the import statement are modules
Seminario Teorico Modellistico 9
Object typeVariables do not need declaration
✦ Numbers✦ Strings✦ Lists✦ Dictionaries✦ Tuples
Variables must be created before they can be used
Seminario Teorico Modellistico 10
Numbers
✦ Floating point
✦ Integers ✦ Complex
✦ Tests
•100/3•100.0/3•100.0//3•100%3•divmod(100,3)
Seminario Teorico Modellistico 11
Operators
x < y, x <= y, x > y, x >= y magnitude comparison
x == y, x != y values equality operators
x + y addition, concatenation
x - y subtraction
x * y multiplication, repetition
x % y remainder
x / y, x // y division: true and floor
x ** y power
Seminario Teorico Modellistico 12
Strings
define a string using single, double or triple quotes
gives you the length of the string
[i] gives the letter in the i-th position
[i:j] gives the letters from i to j
triple quotes are useful for multi-line strings
✦ strings are used to record textual information
Seminario Teorico Modellistico 13
Strings
✦ Operations
S + C concatenation
S * 3 repeat
len(S) length
String method calls
S.find(‘pa’) search
S.rstrip() remove whitespace
S.split(‘,’) split on delimiter
S.replace(‘pa’,’xx’) replacement
S.lowerS.upperS.title
case conversion
Seminario Teorico Modellistico 15
Strings✦ Curiously strings can not be modified, are immutable
you can only use .replace() or turn them into lists
Seminario Teorico Modellistico 16
Containers
✦ Tuples ()
✦ Lists []
Different types of containers are availablethey are efficient, comfortable to use and versatile
✦ Dictionaries {}
Seminario Teorico Modellistico 17
Lists []
✦ List is the most general sequence provided by the language
✦ Lists are positionally ordered collections of arbitrarily typed object
✦ no fixed size
✦ mutable
✦ unlike strings, lists can contain any sort of object
Seminario Teorico Modellistico 19
✦ Operations
L = [] empty list
L = [1, 2, 3, 4] four items: indexes 0,..,3
L = [‘abs’, [‘def’, ‘ghi’]] nested sublist
L[i] index
L[i][j] index of index
L[i : j] slice
len(L) length
L1+ L2 concatenation
L * 3 repetition
L.append() append in last position
L.extend([])in last position more
than one item
L.insert(I, X)insert in I position the
X item
L.index(X)search index of X
item
L.count(X) count the X items
L.sort() sort the list
L.reverse() reverse the list
del L[i : j] del some items
L.pop() del last item
L.remove() del a specific item
Lists []
Seminario Teorico Modellistico 20
✦ lists indexes
python - introduction - Simone Campagna 5212/20/2011
range
! Range è una funzione per generare liste di interi:>>> print range(3)
[0, 1, 2]
>>> print range(3, 7)
[3, 4, 5, 6]
>>> print range(3, 10, 2)
[3, 5, 7, 9]
✦ range function generates lists
python - introduction - Simone Campagna 5412/20/2011
extended slices/1La sintassi dello slicing accetta ora un parametro stride, sempre separato da :>>> l = range(20)
>>> l[1:18]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]
>>> l[1:18:3]
[1, 4, 7, 10, 13, 16]
>>> l[1::3]
[1, 4, 7, 10, 13, 16, 19]
>>> l[:5:3]
[0, 3]
>>> l[::3]
[0, 3, 6, 9, 12, 15, 18]
>>>
Lists []
Seminario Teorico Modellistico 22
Dictionaries {}
✦ If lists are ordered collection of object, dictionaries are unordered collection
✦ Apart from lists, dictionaries are perhaps the most flexible data type in Python
✦ Dictionaries implement associative arrays, they associate an arbitrary value to an arbitrary key
✦ Dictionaries can contain all types of object, also heterogeneously
Seminario Teorico Modellistico 23
Dictionaries {}
python - introduction - Simone Campagna 6312/20/2011
dizionari/1
! I dizionari implementano array associativi; associano ad una chiave arbitraria un valore arbitrario:
>>> numero_zampe = {'gatto': 4, 'oca': 2, 'formica': 6, 'ragno': 8}
>>> print numero_zampe['formica']
6
>>> print numero_zampe
{'oca': 2, 'ragno': 8, 'formica': 6, 'gatto': 4}
>>>
Seminario Teorico Modellistico 24
Dictionaries {}
python - introduction - Simone Campagna 6412/20/2011
dizionari/2! Non sono necessariamente omogenei:>>> d = {}
>>> d['alfa'] = 3
>>> d[2.5] = 'xyz'
>>> d[3+4j] = [3, 4, 5]
>>> d[(1,2,3)] = { 'x': 2, 'y': 3, 'z': 1 }
>>> print d
{2.5: 'xyz', (1, 2, 3): {'y': 3, 'x': 2, 'z': 1}, 'alfa': 3, (3+4j): [3, 4, 5]}
>>>
✦ Dictionaries can be heterogeneous
Seminario Teorico Modellistico 25
Dictionaries
✦ some operators
python - introduction - Simone Campagna 6512/20/2011
dizionari/3>>> print d.keys()
[2.5, (1, 2, 3), 'alfa', (3+4j)]
>>> print d.values()
['xyz', {'y': 3, 'x': 2, 'z': 1}, 3, [3, 4, 5]]
>>> print d.items()
[(2.5, 'xyz'), ((1, 2, 3), {'y': 3, 'x': 2, 'z': 1}), ('alfa', 3), ((3+4j), [3, 4, 5])]
>>> d.has_key('alfa')
True
>>> d.has_key('beta')
False
>>>
python - introduction - Simone Campagna 6412/20/2011
dizionari/2! Non sono necessariamente omogenei:>>> d = {}
>>> d['alfa'] = 3
>>> d[2.5] = 'xyz'
>>> d[3+4j] = [3, 4, 5]
>>> d[(1,2,3)] = { 'x': 2, 'y': 3, 'z': 1 }
>>> print d
{2.5: 'xyz', (1, 2, 3): {'y': 3, 'x': 2, 'z': 1}, 'alfa': 3, (3+4j): [3, 4, 5]}
>>>
Seminario Teorico Modellistico 26
Tuples ()
✦ Tuple constructs simple groups of object
✦ Tuple are lists that can not be modified
✦ Tuple do not support all the methods of the lists, but share most of their properties
✦ Tuple are particularly useful to return multiple values from a function
Seminario Teorico Modellistico 27
Tuples ()
✦ Unlike lists tuples uses ()
python - introduction - Simone Campagna 4412/20/2011
tuple/6Lo slicing consente di accedere a “porzioni” della tupla:>>> a = (0, 1, 2, 3, 4)
>>> print a[1:3] # dal secondo elemento (incluso)
# al quarto (escluso)
(1, 2)
>>> print a[:2] # dal primo (incluso) al terzo (escluso)
(0, 1)
>>> print a[2:] # dal terzo (incluso) all'ultimo (incluso)
(2, 3, 4)
>>> print a[2:] + a[:2]
(2, 3, 4, 0, 1)
>>>
Seminario Teorico Modellistico 28
Flow control statements
✦ If elif else✦ for✦ while
Blocks are delimited by indentation
Seminario Teorico Modellistico 30
for for statements loops over sequences
python - introduction - Simone Campagna 7312/20/2011
for/1
! Il ciclo for consente di iterare su “oggetti iterabili”, come liste, tuple, set, dizionari, …
>>> for i in range(3):
... print i
...
0
1
2
>>>
Seminario Teorico Modellistico 31
for
python - introduction - Simone Campagna 7412/20/2011
for/2
>>> t = ('a', 'b', 10, 5.5)
>>> for i in t:
... print i
...
a
b
10
5.5
>>>
Seminario Teorico Modellistico 32
while
✦ while cycle is a generic cycle with a condition
python - introduction - Simone Campagna 8212/20/2011
while/1! Il ciclo while è il generico ciclo con una condizione:>>> i = 0
>>> while i < 4:
... print i
... i += 1
...
0
1
2
3
>>>
incremental operator
Seminario Teorico Modellistico 33
Break
✦ Break statements allows you to exit the loop
python - introduction - Simone Campagna 8412/20/2011
break
Break permette di uscire dal loop:>>> for i in range(10000):
... print i
... if i%3 == 2:
... break
...
0
1
2
>>>
Seminario Teorico Modellistico 34
Continue✦ continue statements allows you to go in the next
iteration
python - introduction - Simone Campagna 8512/20/2011
continue
Continue permette di passare all'iterazione successiva:>>> for i in range(4):
... if i == 1:
... continue
... print i
...
0
2
3
>>>
Seminario Teorico Modellistico 35
else clause
✦ else clause is available only when the loop does not end with a break statement
python - introduction - Simone Campagna 8612/20/2011
loops: else clause
! I loop (for e while) possono avere una clausola else, che viene eseguita solo se non si esce dal loop con un break; ovvero, se il loop completa naturalmente:
>>> for i in range(10):... if i > 3: break... print i... else:... print "finito!"...0123>>>
>>> for i in range(2):... if i > 3: break... print i... else:... print "finito!"...01finito!>>>
Seminario Teorico Modellistico 36
Functions
✦ Functions are defined with the def statements followed by the name of the function and the list of parameters
python - introduction - Simone Campagna 9812/20/2011
funzioni/2>>> def sum(a, b):
... return a+b
...
>>>
>>> print sum(3, 4)
7
>>> print sum("Ciao, ", "mondo!")
Ciao, mondo!
>>> print sum(3.2, 9.1)
12.3
>>> print sum(6, "ccc")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in sum
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>>
Seminario Teorico Modellistico 37
Functions
✦ return statement allows you to get back a variable, if you do not insert it you get back None
Seminario Teorico Modellistico 38
Debugging Python Code
✦ Do nothing
None of you ever have bugs in your code, but for less fortunate friends of yours who may, this is the strategy commonly used:
✦ Insert print statements
when you have a mistake in Python program, you get a useful and readable error message
read the error message and go fix tagged line and file
Seminario Teorico Modellistico 39
Documentation
✦ Python is very good documented http://docs.python.org/2.7/
✦ Tutorial: http://docs.python.org/2.7/tutorial/index.html
✦ Language reference: http://docs.python.org/2.7/reference/index.html
✦ Library reference: http://docs.python.org/2.7/library/index.html