Sunteți pe pagina 1din 36

Munchen Scientic Computing in Computer Science, Technische Universitat

Scientic Computing in Computer Science, Munchen Technische Universitat

Scripting with Python ... and beyond


Compact Course @ GRS
Tobias Neckel
June 03 - 07, 2013

Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 1

Munchen Scientic Computing in Computer Science, Technische Universitat

Part I Python Overview

Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 2

Munchen Scientic Computing in Computer Science, Technische Universitat

What Python is all about. . .

Python
Invented in 1990 as teaching language Designed for clearness and readability Named after Monty Python (not the snake)

Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 3

Munchen Scientic Computing in Computer Science, Technische Universitat

What Python is all about. . .


Python is. . .
High-level (really high-level) Truly object-oriented Interpreted Scalable Extensible Portable, available on Windows, Linux, Mac OS X, Amiga, HPC

machines and clusters, web servers, Palm and other Handhelds, Nokia Mobiles, .NET virtual machines, . . .

Versatile Easy to learn, understand, use, and maintain (really!) Free, open-source ...
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 4

Munchen Scientic Computing in Computer Science, Technische Universitat

What Python is all about. . .


Suitable for
OS scripting (Python beats Bash ;-)) Internet Programming Scientic Computing (up to whole Tsunami Simulations) Parallelisation GUI (Tkinter) Visualisation Rapid prototype development . . . and much, much more!

Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 5

Munchen Scientic Computing in Computer Science, Technische Universitat

What Python is all about. . .

Some more features


Dynamically typed Automatic garbage collection Different programming paradigmes possible (procedural, OO,

functional, aspect oriented, . . . )

Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 6

Munchen Scientic Computing in Computer Science, Technische Universitat

What Python is all about. . .

Some more features


Dynamically typed Automatic garbage collection Different programming paradigmes possible (procedural, OO,

functional, aspect oriented, . . . )

Note
Were assuming Python 2.5.X, 2.6.X, or 2.7.X The current version Python 3.X requires few changes

Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 6

Munchen Scientic Computing in Computer Science, Technische Universitat

Requirements

To be able to use all examples you require. . .


IPython (call ipython) NumPy and SciPy Pylab (as it ships with Matplotlib) Tkinter swig (Simplied Wrapper and Interface Generator)

independent of Python

Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 7

Munchen Scientic Computing in Computer Science, Technische Universitat

Part II Hands On. . .

Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 8

Munchen Scientic Computing in Computer Science, Technische Universitat

Lets get started. . .


Start the Python interpreter At prompt >>> type command, press <Enter> to confirm

$ python Python 2.7.3 ( default , Aug 1 2012 , 05:14:39) [ GCC 4.6.3] on linux2 Type " help " , " copyright " , " credits " or " license " for more information . >>> help Type help () for interactive help , or help ( object ) for help about object . >>> help ()
Welcome to Python 2.7! utility . [...] This is the online help

Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 9

Munchen Scientic Computing in Computer Science, Technische Universitat

Getting help

Vast online documentation at http://docs.python.org/ Interactive using


help() for interactive help, help(modules) for a list of all available modules help(object|command) for help on an object or command

Literature

David M. Beasley: Python - Essential Reference, Addison-Wesley Professional, 4th edition, 2009 Hans Petter Langtangen: A Primer on Scientic Programming with Python, Springer, 2009

Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 10

Munchen Scientic Computing in Computer Science, Technische Universitat

A rst Hello World!


Python simplify your Code Just type
>>> print " Hello World ! " Hello World ! Compare with Java, e.g.: public class Hello { public static void main ( String argv []){ System . out . println ( " Hello World ! " ); } }

$ javac Hello . java $ java Hello Hello World !


Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 11

Munchen Scientic Computing in Computer Science, Technische Universitat

Statements and assignments


>>> >>> >>> >>> >>> >>> >>> >>> >>> 3+4**2/8+1 (6*3.5)*2 -5 10 e -4 a =17 a a -1.5 b = " Hello World ! " print b print a , b , (4+5**0.5)

assignment: variableName = expression (different to math. =) Interactive session shows return values print prints variables and expressions as string

Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 12

Munchen Scientic Computing in Computer Science, Technische Universitat

3.5 Ways to Python

1. Start the Python interpreter with python 2. Use IPython: ipython 3. Run Python on a le 3.5. Execute as a script

Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 13

Munchen Scientic Computing in Computer Science, Technische Universitat

2. IPython
$ ipython Python 2.7.3 ( default , Aug 1 2012 , 05:14:39) Type " copyright " , " credits " or " license " for more information .
IPython 0.13.2. rc2 -- An enhanced Interactive Python . ? -> Introduction and overview of IPython s features . % quickref -> Quick reference . help -> Python s own help system . object ? -> Details about object . ? object also works , ?? prints more . In [1]: print " Hello World !" Hello World !

Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 14

Munchen Scientic Computing in Computer Science, Technische Universitat

2. IPython
Highlights
Enhanced interactive shell Additional shell syntax

magic functions, starting with % such as %psearch to search for function in namespace Access shell commands %cd Run scripts with run filename.py Log session, dene macros, . . . Pretty printing, toggle with %Pprint

Syntax highlighting Tab completion, string completion History

Access previous command blocks

Automatic indentation
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 15

Munchen Scientic Computing in Computer Science, Technische Universitat

3. Run Python on a File

File square_me.py: print 6**2 Then run

$ python square_me . py 36

Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 16

Munchen Scientic Computing in Computer Science, Technische Universitat

3.5. Execute as a Script


Shell script as before Just tell shell to execute python: # !/ usr / bin / python print 6**2 Then set executable ag and run

$ chmod u + x square_me . py $ ./ square_me . py 36

Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 17

Munchen Scientic Computing in Computer Science, Technische Universitat

Part III Data Types and Control Structures

Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 18

Munchen Scientic Computing in Computer Science, Technische Universitat

Built-in Python Types


Numeric Types bool boolean type
print True , False True == True True != True int integer 1+5 -12 Attention integer division: digits after the comma get lost! >>> 5/3 1 long arbitrary-precision integer 12345**100
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 19

Munchen Scientic Computing in Computer Science, Technische Universitat

Numeric Types (cont.)


float oating point (double precision) 3.14159265*5.6 1.5 e -10 complex complex numbers 1+4 j c = complex (2 ,3) print c d = 2 * ( c **3 - 3 j ) print d d . real d . imag

None type None special type (undened)


Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 20

Munchen Scientic Computing in Computer Science, Technische Universitat

General Remarks
Everything is an object (int, oat, tuple, classes, . . . ) Thus everything can have attributes and methods c = complex (2 ,3) print c . real , c . imag Dynamic typing: Type of a variable determined during Automatic conversion where necessary and possible a = 1234 type ( a ) b = 100 type ( b ) a = 1234**100 type ( a ) b = b *1.0 # equals b = float ( b )*1.0 type ( b )
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 21

assignment

Munchen Scientic Computing in Computer Science, Technische Universitat

Built-in Sequences
Strings
string type Sequence of characters Single, double or triple double (multiline) quotes " ... there lived a hobbit . " " a hobbit " a " hobbit " a \ hobbit \ """ In a hole in the ground there " lived " a hobbit """ Concatenation s1 = " In a hole in the ground " s2 = " there lived a hobbit " s = s1 + + s2 print s
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 22

Munchen Scientic Computing in Computer Science, Technische Universitat

Built-in Sequences Strings (2)


Replication " Hi ! " *3 Indexing and Slicing (immutable sequence type) s = " Hello Hobbit " s [3] s [ -2] s [2:4] s [6:] s [:6] s [0: -1:2] # stride 2 s [0::2] s [2] = 4 # error len ( s )

Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 23

Munchen Scientic Computing in Computer Science, Technische Universitat

Built-in Sequences Strings (3)


String formatting using % " Bilbo s % d . birthday " % (111) " Frodo , %s , and Bilbo ate % f apples " %( " Sam " ,1.5) Some format modiers %05 d % (13) % -5 d % (13) %+5 d % (13) % d % (13) % e % (13) % g %g , % f % % s % ( hi ) %% # fill 0 # left justified # sign # signed integer # floating point exponential (13 , 1e -6 , 1e -6) # string # escape %

Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 24

Munchen Scientic Computing in Computer Science, Technische Universitat

Built-in Sequences
Tuples Sequences of arbitrary objects (,) Immutable Indexing and slicing as before
l = (1 ,) l = (1 , " two " , (3 ,4 ,5)) l [0] l [ -1] l [1] = 2 # error len ( l ) min ( l ) # here : numbers smaller than strings l = ( " Hello " , " Hobbit " ) min ( l ) max ( l ) l2 = l + (6 ,7 ,8)

Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 25

Munchen Scientic Computing in Computer Science, Technische Universitat

Built-in Sequences
Lists Sequences of arbitrary objects [,] Mutable
l = [1 , " two " , (3 ,4 ,5) , 5] l [0] l [ -1] l [1] = 2 # works ! len ( l ) Operations on lists l = [0 ,1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9] l [2:4] = [10 , 11] l [1:7:2] = [ -1 , -2 , -3] del l [::2]

Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 26

Munchen Scientic Computing in Computer Science, Technische Universitat

Built-in Sequences
Lists (2) List methods
l = [0 ,1 ,2 ,3] l . append ( " four " ) l . extend ([5 ,6 ,7 ,8 ,9]) l . insert (8 , " four " ) l . count ( " four " ) l . sort () l . reverse () l . remove ( " four " ) l . pop () Integer ranges: range function range (10) range (5 , 10) range ( -10 , 20 , 3)
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 27

Munchen Scientic Computing in Computer Science, Technische Universitat

Control Flow
General
Indentation used to group blocks! Code within same block has to be same level Needs getting used to, but encourages readable code

if-statement
if x < y : print print elif x == print else : print print " x is smaller " x y: " both are equal " " y is smaller " y

Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 28

Munchen Scientic Computing in Computer Science, Technische Universitat

Comparison and Equality


Check for equality " Bilbo " == " Frodo " " Bilbo " != " Frodo " Comparison " Bilbo " " Bilbo " " Bilbo " " Bilbo " is and in " Bilbo " is " Frodo " # object identity " Bilbo " in [ " Frodo " , " Sam " , " Bilbo " ] # membership < " Frodo " > " Frodo " <= " Frodo " >= " Frodo "

Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 29

Munchen Scientic Computing in Computer Science, Technische Universitat

Comparison and Equality (2)

Combining and grouping (and, or, not) if ( " Bilbo " != " Frodo " and not (1 > 2 or 2 > 3)): print " Sam was here "

Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 30

Munchen Scientic Computing in Computer Science, Technische Universitat

Control Flow - for

Pythons for iterates over the items of a sequence type


for i in range (5 ,10): print " loop index : " , i a = ( " a " , " tuple " , " with " , 5 , " words " ) for i in a : print i

Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 31

Munchen Scientic Computing in Computer Science, Technische Universitat

Control Flow - break and while


break breakes out of the enclosing loop (for or while) continue continues with the lext iteration of the loop a = ( " let " , " us " , " find " , " Bilbo " , " again " ) for word in a : if word == " Bilbo " : print " found Bilbo " break print word while loops until condition is False a = 2048; exp = 0 while a > 1: a /= 2 # a = a / 2 exp +=1 # exp = exp + 1 print a , " = " , 2 , " ^ " , exp
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 32

Munchen Scientic Computing in Computer Science, Technische Universitat

Functions (and Procedures)


Functions are dened using def No return statement means returning None Call by reference (Note: Assignment creates a new local object) def hi (): print " Hello World ! " def faculty ( n ): fac = 1 for i in range (2 , n +1): fac = fac * i return fac Functions are objects and can be assigned, too f = faculty f (3)
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 33

Munchen Scientic Computing in Computer Science, Technische Universitat

Functions (2)
Default arguments def printme ( s = " Frodo " ): print s printme () printme ( " Bilbo " ) Keyword arguments def exp ( basis , exponent ): return basis ** exponent exp ( basis =2 , exponent =10) exp ( exponent =10 , basis =2)

Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 34

Munchen Scientic Computing in Computer Science, Technische Universitat

Up to now. . .

Variables Numeric types Sequence types (str, tuple, list; more tomorrow) if comparison for, while, break, continue Functions and parameters

Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 35

S-ar putea să vă placă și