Python. Tutorial. Jan Pöschko. March 22, Graz University of Technology

Similar documents
Python. chrysn

Algorithms for Uncertainty Quantification

ECE521 W17 Tutorial 1. Renjie Liao & Min Bai

Notater: INF3331. Veronika Heimsbakk December 4, Introduction 3

Introduction to Python and its unit testing framework


epistasis Documentation

Scripting Languages Fast development, extensible programs

Octave. Tutorial. Daniel Lamprecht. March 26, Graz University of Technology. Slides based on previous work by Ingo Holzmann

Python & Numpy A tutorial

1 Opening URLs. 2 Regular Expressions. 3 Look Back. 4 Graph Theory. 5 Crawler / Spider

VPython Class 2: Functions, Fields, and the dreaded ˆr

6. How Functions Work and Are Accessed. Topics: Modules and Functions More on Importing Call Frames

Lectures about Python, useful both for beginners and experts, can be found at (

Fundamentals of Computational Science

Agile modeling for INF5150

Introduction to Python

TensorFlow. Dan Evans

Read all questions and answers carefully! Do not make any assumptions about the code other than those that are clearly stated.

Practical Information

M o n i t o r i n g O c e a n C o l o u r P y t h o n p r o c e d u r e f o r d o w n l o a d

Best Practices. Nicola Chiapolini. Physik-Institut University of Zurich. June 8, 2015

COMS 6100 Class Notes

CS Exam 1 Study Guide and Practice Exam

Introduction to Python

Introduction to Python for Biologists

PYTHON, NUMPY, AND SPARK. Prof. Chris Jermaine

Practical Data Processing With Haskell

Introduction to Programming (Java) 3/12

CGWAS 2013: Simulating Stellar Collapse

Sapienza universita di Roma Dipartimento di Informatica e Sistemistica. User guide WSCE-Lite Web Service Composition Engine v 0.1.

NumPy 1.5. open source. Beginner's Guide. v g I. performance, Python based free open source NumPy. An action-packed guide for the easy-to-use, high

Tryton Technical Training

Lisp Introduction. Dr. Neil T. Dantam. Spring CSCI-498/598 RPM, Colorado School of Mines. Dantam (Mines CSCI, RPM) Lisp Spring / 88

Lab Course: distributed data analytics

Biology 559R: Introduction to Phylogenetic Comparative Methods Topics for this week:

2 Getting Started with Numerical Computations in Python

PYTHON AND DATA SCIENCE. Prof. Chris Jermaine

/home/thierry/columbia/msongsdb/pyreport_tutorials/tutorial1/tutorial1.py January 23, 20111

von Neumann Architecture

CS 420/594: Complex Systems & Self-Organization Project 1: Edge of Chaos in 1D Cellular Automata Due: Sept. 20

Appendix 4 Weather. Weather Providers

5-Star Analysis Tutorial!

(Multiscale) Modelling With SfePy

Department of Chemical Engineering University of California, Santa Barbara Spring Exercise 2. Due: Thursday, 4/19/09

HOW TO USE MIKANA. 1. Decompress the zip file MATLAB.zip. This will create the directory MIKANA.

Tutorial. Getting started. Sample to Insight. March 31, 2016

4th year Project demo presentation

Aalto University 2) University of Oxford

Computational Methods for Nonlinear Systems

Physics 750: Exercise 2 Tuesday, August 29, 2017

Lexical Analysis: DFA Minimization & Wrap Up

IAST Documentation. Release Cory M. Simon

Homework 9: Protein Folding & Simulated Annealing : Programming for Scientists Due: Thursday, April 14, 2016 at 11:59 PM

Administering your Enterprise Geodatabase using Python. Jill Penney

Practical Bioinformatics

Pytorch Tutorial. Xiaoyong Yuan, Xiyao Ma 2018/01

Satellite project, AST 1100

I. Numerical Computing

Linear Transformations

Structure. Background. them to their higher order equivalents. functionals in Standard ML source code and converts

Assignment 4: Object creation

Computational Methods for Nonlinear Systems

Python and Chemical Informatics

ZFL, Center of Remote Sensing of Land Surfaces, University of Bonn, Germany. Geographical Institute, University of Bonn, Germany

Extensibility Patterns: Extension Access

MATERIAL MECHANICS, SE2126 COMPUTER LAB 2 PLASTICITY

Predici 11 Quick Overview

Extended Introduction to Computer Science CS1001.py. Lecture 8 part A: Finding Zeroes of Real Functions: Newton Raphson Iteration

NLP Homework: Dependency Parsing with Feed-Forward Neural Network

High-Performance Scientific Computing

Experiment 1: Linear Regression

Tutorial Three: Loops and Conditionals

MODULE 2: QUANTUM MECHANICS. Practice: Quantum ESPRESSO

Creative Data Mining

Applied C Fri

Solving Polynomial Systems in the Cloud with Polynomial Homotopy Continuation

Modern Functional Programming and Actors With Scala and Akka

Molecular Visualization. Introduction

Modeling and Simulation in Python. Version 1.1

Subwatersheds File Geodatabase Feature Class

Lexical Analysis Part II: Constructing a Scanner from Regular Expressions

Marvin. Sketching, viewing and predicting properties with Marvin - features, tips and tricks. Gyorgy Pirok. Solutions for Cheminformatics

Pysolar Documentation

Statistics for Python

CS429: Computer Organization and Architecture

A GUI FOR EVOLVE ZAMS

Hidden Markov Model Documentation

Fin System, Inc. Company Report. Temperature Profile Calculators. Team 1 J. C. Stewards, Lead A. B. Williams, Documentation M. D.

A Practical Comparison of Agile Web Frameworks

Comp 11 Lectures. Mike Shah. July 26, Tufts University. Mike Shah (Tufts University) Comp 11 Lectures July 26, / 40

An Introduction to MAGMA

Worksheet 1: Integrators

A Brief Introduction To. GRTensor. On MAPLE Platform. A write-up for the presentation delivered on the same topic as a part of the course PHYS 601

LAST TIME..THE COMMAND LINE

arxiv: v2 [cs.ds] 9 Nov 2017

Automatic differentiation

SideNail. Martín Schonaker, Santiago Martínez

TDDD63 Project: API. September 13, 2014

Assignment 1: Molecular Mechanics (PART 1 25 points)

Transcription:

Tutorial Graz University of Technology March 22, 2010

Why? is: very readable easy to learn interpreted & interactive like a UNIX shell, only better object-oriented but not religious about it slower than C, but it is easy to integrate C, Fortran, Java Batteries included

The Zen of Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren t special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one and preferably only one obvious way to do it. Although that way may not be obvious at first unless you re Dutch. Now is better than never. Although never is often better than right now. If the implementation is hard to explain, it s a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea let s do more of those!

Installing included in most distributions of Linux and Mac OS X downloadable from http://www.python.org/download/ libraries: NumPy: http://sourceforge.net/projects/numpy/ matplotlib: http://sourceforge.net/projects/ matplotlib/files/matplotlib/ NetworkX: http://networkx.lanl.gov/install.html editors: Eclipse emacs, vim... (anything that knows how to handle tabs and spaces)

Invoking Interactive mode: Open a console/terminal window and run python (fancier alternative: ipython) Executing files: python myfile.py

Language basics n = 42 # i n t e g e r x = 3.14159 # f l o a t x = H e l l o world! # s t r i n g no variable declarations dynamically typed String delimeters: s = H e l l o world! s = H e l l o world! s = H e l l o world! # multi l i n e s t r i n g

Booleans True is true, False is false 0, "" and None are false, (almost) everything else is true not A A and B A or B Comparisons: ==,!=, <, <=, >, >= 2 == 2 1 < 2 <= 3 1 == 2 and 3 or 4 # = 4

Lists L = [ 1, 2, 3 ] L [ 0 ] # = 1 L [ 1 : 3 ] # = [ 2, 3 ] L [: 1] # = [ 1, 2 ] L. append ( 4 ) # > [ 1, 2, 3, 4 ] L += [ 5, 6 ] # > [ 1, 2, 3, 4, 5, 6 ] del L [ 5 ] # > [ 1, 2, 3, 4, 5 ] l e n ( L ) # = 5 L. r e v e r s e ( ) # > [ 5, 4, 3, 2, 1 ] L. s o r t ( ) # > [ 1, 2, 3, 4, 5 ] Variables only hold references to lists (like to everything else): M = L M[ 2 ] = A # > [ 1, 2, A, 4, 5 ] L [ 2 ] # > A

Dictionaries and sets Dictionaries: D = { Mozart : 1756, Schubert : 1797} D[ Mozart ] # = 1756 D. keys ( ) # = [ Schubert, Mozart ] D. v a l u e s ( ) # = [ 1 7 9 7, 1756] D. update ({ Beethoven : 1770}) D[ E i n s t e i n ] = 1879 E i n s t e i n i n D # = True l e n (D) # = 4 D. get ( Newton, unknown ) # = unknown Sets: s = s e t ( [ 1, h e l l o, world ] ) s. add ( 3 ) 2 i n s # = F a l s e

Control flow i f n == 0 : p r i n t n i s 0 e l i f n > 0 : p r i n t n i s p o s i t i v e e l s e : p r i n t n i s n e g a t i v e Indentation matters! Don t mix tabs and spaces configure your editor appropriately! while n > 0 : n = 1 f o r n i n [ 1, 2, 3, 4 ] : p r i n t n

Idioms Iterate over a dictionary and format strings: D = { Mozart : 1756, Schubert : 1797} f o r name, y e a r i n D. i t e r i t e m s ( ) : p r i n t %s was born i n %d % ( name, y e a r ) List comprehensions: quad = [ x 2 f o r x i n range ( 8 ) ] # = [ 0, 1, 4, 9, 16, 25, 36, 4 9 ] even = [ x 2 f o r x i n range ( 8 ) i f x % 2 == 0 ] # = [ 0, 4, 16, 3 6 ]

Files v a l u e s = [ [ 1, 0 ], [ 1, 1 ] ] # J o i n v a l u e s by ; and l i n e s by n e w l i n e s c s v t e x t = \n. j o i n ( ;. j o i n ( s t r ( v a l u e ) \ f o r v a l u e i n l i n e ) f o r l i n e i n v a l u e s ) # Write the t e x t i n t o a f i l e c s v f i l e = open ( f i l e. c s v, w ) c s v f i l e. w r i t e ( c s v t e x t ) c s v f i l e. c l o s e ( )

Functions: fac(n) = n! := n k=1 k def f a c ( n ) : i f n == 1 : return 1 e l s e : return n f a c ( n 1) def f a c ( n ) : r e s u l t = 1 f o r k i n range ( 1, n + 1 ) : r e s u l t = k return r e s u l t def f a c ( n ) : return r e d u c e ( lambda a, b : a b, range ( 1, n + 1 ), 1)

Functions: Parameters Parameters point to values (like all variables): def change ( a, b ) : a = b [ 0 ] = 0 a, b = 1, [ 1, 1 ] change ( a, b ) # > a = 1, b = [ 0, 1 ] Extra arguments (passed in as list): def sum ( v a l u e s ) : r e s u l t = 0 f o r v a l u e i n v a l u e s : r e s u l t += v a l u e return r e s u l t sum ( 1, 2, 5) # = 8 Keyword arguments (passed in as dictionary): **kwargs

Generators def s u b s e t s ( l i s t ) : i f not l i s t : y i e l d [ ] return f o r next i n s u b s e t s ( l i s t [ 1 : ] ) : y i e l d [ l i s t [ 0 ] ] + next y i e l d next f o r s e t i n s u b s e t s ( [ 1, 2, 3 ] ) : p r i n t s e t

Classes and objects c l a s s Animal : def i n i t ( s e l f, name ) : s e l f. name = name def s a y h e l l o ( s e l f ) : p r i n t I m %s % s e l f. name c l a s s Dog( Animal ) : def i n i t ( s e l f, name, owner ) : s u p e r (Dog, s e l f ). i n i t ( name ) s e l f. owner = owner def s a y h e l l o ( s e l f ) : p r i n t H e l l o %s % s e l f. owner dog = Dog( C h a r l y, Jan ) dog. s a y h e l l o ( )

Modules Any file (e.g. mymodule.py) is a module and can be imported: import mymodule mymodule. myfunction ( ) from mymodule import myfunction from mymodule import # r a t h e r d i s c o u r a g e d myfunction ( ) File-system directories can be used to create namespaces, if they contain a file init.py (which may contain initialization code): import mydir. mymodule from mydir. mymodule import myfunction

main Variable name contains the name of the current module. It equals " main " when the script is run directly from the command-line. Common idiom: def main ( ) : p r i n t H e l l o world! i f name == m a i n : main ( )

More advanced concepts exceptions multiple inheritance operator overloading metaclasses inline documentation and test code extensive runtime information

Regular expressions re is a module for handling regular expressions. import r e r e. f i n d a l l ( [ A Za z ]+, H e l l o world! ) # = [ H e l l o, world ] * 0 or more findall(pattern, string) + 1 or more match(pattern, string)? 0 or 1 sub(pattern, repl, string) [... ] certain characters split(pattern, string) [^... ] characters excluded... Pre-compiling regular expressions: WORD RE = r e. c o m p i l e ( [ A Za z ]+ ) WORD RE. f i n d a l l ( H e l l o world! )

URLs urllib2 is a module for opening URLs. from u r l l i b 2 import u r l o p e n u r l f i l e = u r l o p e n ( h t t p : / /www. g o o g l e. com ) c o n t e n t = u r l f i l e. read ( ) # = <! doctype html><html > [... ] < / s c r i p t > Basic HTTP authentication: import u r l l i b 2 a u t h h a n d l e r = u r l l i b 2. HTTPBasicAuthHandler ( ) a u t h h a n d l e r. add password ( realm= the realm, u r i= h t t p : / /www. example. com, u s e r= u s r, passwd= pwd ) opener = u r l l i b 2. b u i l d o p e n e r ( a u t h h a n d l e r ) u r l l i b 2. i n s t a l l o p e n e r ( opener ) u r l o p e n ( h t t p : / /www. example. com/ r e s t r i c t e d )

XML documents xml.dom is a module for parsing XML documents and accessing them using the Document Object Model. from xml. dom. minidom import p a r s e S t r i n g c o n t e n t = <tag a t t r = 1 > <sub>t e x t </sub></tag> dom = p a r s e S t r i n g ( c o n t e n t ) dom. c h i l d N o d e s [ 0 ]. g e t A t t r i b u t e ( a t t r ) # = 1 subs = dom. getelementsbytagname ( sub ) subs [ 0 ]. c h i l d N o d e s [ 0 ]. nodevalue # = t e x t

JSON data json is a module for parsing and exporting JSON data snippets (included in 2.6; use package simplejson in 2.5). import j s o n j s o n d a t a = { l i s t : [ 1, 2 ], key : v a l u e } j s o n. l o a d s ( j s o n d a t a )

NetworkX networkx is a module for the creation, manipulation, and study of the structure, dynamics, and functions of complex networks. import networkx as nx G = nx. Graph ( ) G. add node ( 1 ) G. add edge ( 1, 2) G. add edge ( 2, 3) Plot graphs: import m a t p l o t l i b. p y p l o t as p l t p l t. f i g u r e ( ) nx. draw (G) p l t. s a v e f i g ( graph. png )

NetworkX: Customized visualization p l t. f i g u r e ( ) p l t. a x i s ( o f f ) pos = nx. s p r i n g l a y o u t (G, i t e r a t i o n s =50) nx. d r a w n e t w o r k x e d g e s (G, pos ) nx. d r aw networkx n o d e s (G, pos, [ 1 ], n o d e c o l o r= r ) nx. d r aw networkx n o d e s (G, pos, [ 2, 3 ], n o d e c o l o r= b ) nx. d r a w n e t w o r k x l a b e l s (G, pos ) p l t. s a v e f i g ( graph. png, d p i =72)

Further reading Official tutorial: http://docs.python.org/tutorial/ tutorial at the University of Toronto: http: //www.cs.toronto.edu/~gpenn/csc401/401_python_web/ 2.6 Quick Reference: http://rgruet.free.fr/pqr26/pqr2.6.html http://docs.python.org/library/re.html http://docs.python.org/library/urllib2.html http://docs.python.org/library/xml.dom.html http://code.google.com/p/simplejson/ NetworkX: http://networkx.lanl.gov/contents.html