Part IV. More on Python. Tobias Neckel: Scripting with Bash and Python Compact Max-Planck, February 16-26,

Similar documents
STSCI Python Introduction. Class URL

Princeton University COS 333: Advanced Programming Techniques A Subset of Python 2.7

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

Python Tutorial. Day 1

Script language: Python Data and files

Babu Madhav Institute of Information Technology, UTU 2015

CS Programming Languages: Python

Introduction to Python for Plone developers

Advanced Algorithms and Computational Models (module A)

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes

Webgurukul Programming Language Course

Python review. 1 Python basics. References. CS 234 Naomi Nishimura

There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals:

GE PROBLEM SOVING AND PYTHON PROGRAMMING. Question Bank UNIT 1 - ALGORITHMIC PROBLEM SOLVING

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

PYTHON CONTENT NOTE: Almost every task is explained with an example

PYTHON FOR MEDICAL PHYSICISTS. Radiation Oncology Medical Physics Cancer Care Services, Royal Brisbane & Women s Hospital

Python Basics. Lecture and Lab 5 Day Course. Python Basics

Introductory Linux Course. Python I. Martin Dahlö UPPMAX. Author: Nina Fischer. Dept. for Cell and Molecular Biology, Uppsala University

Data type built into Python. Dictionaries are sometimes found in other languages as associative memories or associative arrays.

Python Training. Complete Practical & Real-time Trainings. A Unit of SequelGate Innovative Technologies Pvt. Ltd.

Python Programming Language

Script language: Python Data structures

Python INTRODUCTION: Understanding the Open source Installation of python in Linux/windows. Understanding Interpreters * ipython.

CIS192 Python Programming

Reading and writing files

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

Python. Executive Summary

Part III Appendices 165

Lecture no

IPSL python tutorial: some exercises for beginners

CSCE 110 Programming I

Variable and Data Type I

CIS192 Python Programming

Table of Contents. Preface... xxi

CIS192 Python Programming

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

About Python. Python Duration. Training Objectives. Training Pre - Requisites & Who Should Learn Python

CIS192 Python Programming. Robert Rand. August 27, 2015

Beyond Blocks: Python Session #1

Classifying malware using network traffic analysis. Or how to learn Redis, git, tshark and Python in 4 hours.

CIS192 Python Programming

UNIVERSITÀ DI PADOVA. < 2014 March >

Python Working with files. May 4, 2017

Senthil Kumaran S

Strings. Upsorn Praphamontripong. Note: for reference when we practice loop. We ll discuss Strings in detail after Spring break

Index. object lifetimes, and ownership, use after change by an alias errors, use after drop errors, BTreeMap, 309

What Version Number to Install

Here n is a variable name. The value of that variable is 176.

Data Handing in Python

Functions, Scope & Arguments. HORT Lecture 12 Instructor: Kranthi Varala

PYTHON FOR KIDS A Pl ayfu l I ntrodu ctio n to Prog r am m i ng J a s o n R. B r i g g s

LECTURE 4 Python Basics Part 3

Python Tutorial. Day 2

Python for Finance. Control Flow, data structures and first application (part 2) Andras Niedermayer

Introductory Linux Course. Python I. Pavlin Mitev UPPMAX. Author: Nina Fischer Dept. for Cell and Molecular Biology, Uppsala University

Advanced Python. Executive Summary, Session 1

Python: Short Overview and Recap

Python Reference (The Right Way) Documentation

1 Decorators. 2 Descriptors. 3 Static Variables. 4 Anonymous Classes. Sandeep Sadanandan (TU, Munich) Python For Fine Programmers July 13, / 19

Introduction to Python

Duration: Six Weeks Faculty : Mr Sai Kumar, Having 10+ Yrs Experience in IT

Programming to Python

Introduction to Python

LECTURE 2. Python Basics

COMP322 - Introduction to C++ Lecture 02 - Basics of C++

Introduction to Python! Lecture 2

OOP and Scripting in Python Advanced Features

Module 3: Strings and Input/Output

Variable and Data Type I

CS S-02 Python 1. Most python references use examples involving spam, parrots (deceased), silly walks, and the like

IAP Python - Lecture 2

Python 3 Quick Reference Card

Alastair Burt Andreas Eisele Christian Federmann Torsten Marek Ulrich Schäfer. October 6th, Universität des Saarlandes. Introduction to Python

COMP-520 GoLite Tutorial

ECE 364 Software Engineering Tools Laboratory. Lecture 4 Python: Collections I

sottotitolo A.A. 2016/17 Federico Reghenzani, Alessandro Barenghi

Modules and scoping rules

Files. Files need to be opened in Python before they can be read from or written into Files are opened in Python using the open() built-in function

The Pyth Language. Administrivia

06/11/2014. Subjects. CS Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / ) Beginning with Python

String Processing CS 1111 Introduction to Programming Fall 2018

And Parallelism. Parallelism in Prolog. OR Parallelism

LOON. Language Reference Manual THE LANGUAGE OF OBJECT NOTATION. Kyle Hughes, Jack Ricci, Chelci Houston-Borroughs, Niles Christensen, Habin Lee

Download Python from Any version will do for this class

COLLEGE OF ENGINEERING, NASHIK-4

CS Introduction to Computational and Data Science. Instructor: Renzhi Cao Computer Science Department Pacific Lutheran University Spring 2017

VALLIAMMAI ENGINEERING COLLEGE

An Introduction to Python

Programming with Python. May 4, 2017

Python. Jae-Gil Lee Based on the slides by K. Naik, M. Raju, and S. Bhatkar. December 28, Outline

L1/L2 NETWORK PROTOCOL TESTING

Exam 1 Format, Concepts, What you should be able to do, and Sample Problems

EE 355 Unit 17. Python. Mark Redekopp

Built-in Types of Data

AI Programming CS S-02 Python

Introduction to Python

Introduction to Python (All the Basic Stuff)

1 Strings (Review) CS151: Problem Solving and Programming

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

Transcription:

Part IV More on Python Compact Course @ Max-Planck, February 16-26, 2015 36

More on Strings Special string methods (excerpt) s = " Frodo and Sam and Bilbo " s. islower () s. isupper () s. startswith (" Frodo ") # try s. startswith (" Frodo ", 2) s. endswith (" Bilbo ") s = s. strip () s. upper () s = s. lower () s. capitalize () # capitalize first character s = s. center ( len (s )+4) # center ( padding default : space ) s. lstrip () s. rstrip (" ") s = s. strip () s. find (" sam ") s. rfind (" and ") Compact Course @ Max-Planck, February 16-26, 2015 37

More on Strings (2) Searching, splitting and joining (excerpt) s. find (" sam ") s. rfind (" and ") s. replace (" and ", "or") s. split () # or s. split ( None ); arbitrary numb. whitesp. s. split (" ") s. split (" and ") s. split (" and ", 1) s = """ Line by Line """ s. splitlines () ", ". join ([" sequence ", "of", " strings "]) Compact Course @ Max-Planck, February 16-26, 2015 38

More on Built-in Sequences Dictionaries Map keys to values, arbitrary types Only immutable objects as keys Can serve as database d = {} d[" Bilbo "] = " Hobbit " d[" Elrond "] = " Elf " d [42] = 1234 d. has_key (" Bilbo ") d. keys () # unordered d. items () d. values () del d [42] d. clear () Compact Course @ Max-Planck, February 16-26, 2015 39

More on Functions Functions have to be defined before actually called for the first time Note: Python is an interpreted language Variables Variables defined or assigned to in functions have local scope Global variables (surrounding context) can be accessed To modify global variables use global count = 0... def count_it (n): global count count += 1 In general: avoid global variables (pass as params instead) Compact Course @ Max-Planck, February 16-26, 2015 40

Call by Reference vs. Call by value Call by reference: address (id) of parameter is handed over Call by value: value of parameter is handed over In Python: always call by reference But: assignment changes reference within function >>> def add_one (x): >>> x = x + 1 >>> >>> x = 3 >>> add_one (x) >>> x 3 Compact Course @ Max-Planck, February 16-26, 2015 41

Call by Reference vs. Call by value (2) After assignment: local variable references to a new object. Using methods, the original object can be modified. >>> def append1 (l): >>> l = l + [4] >>> >>> def append2 (l): >>> l. append (4) >>> >>> l = [1,2,3] >>> append1 (l); l [1,2,3] >>> append2 (l); l [1,2,3,4] Compact Course @ Max-Planck, February 16-26, 2015 42

More on Functions (2) Return values Functions can have multiple return values (returned as tuple) def get_hobbits (): return " Bilbo ", " Frodo " h = get_hobbits () (a, b) = get_hobbits () Assignment rules correspond to slice assignment l = [4, 2] (a, b) = l # implicit type conversion a, b = l l [0:3] = (3, 2) # implicit type conversion Compact Course @ Max-Planck, February 16-26, 2015 43

More on Functions (3) Docstrings Functions (and classes, modules,...) can provide help text String after function header (can be multiline) def answer (): " Returns an answer to a question " print " answer " help ( answer ) Compact Course @ Max-Planck, February 16-26, 2015 44

Arithmetic Operations Classical operations x + y # Addition x - y # Subtraction x * y # Multiplication x / y # Division x // y # Truncated division x ** y # Exponentiation x % y # Modulo x -= 2; x *= 4;... Division differs for int and float (Python < 3.0) 7/4 7.0/4 Compact Course @ Max-Planck, February 16-26, 2015 45

More Operations General functions abs (x) divmod (x, y) # (x // y, x % y) pow (x, y [, modulo ]) # x**y % modulo round (x, [n]) # round to 10**( - n) Operations on integers x << y # Left shift x >> y # Right shift x & y # Bitwise and x y # Bitwise or x ^ y # Bitwise xor ~ x # Bitwise negation Compact Course @ Max-Planck, February 16-26, 2015 46

File I/O Opening files Create file object (text files) fd = open (" testfile. txt ") # read fd = open (" testfile. txt ", r ) # read fd = open (" testfile. txt ", w ) # write fd = open (" testfile. txt ", a ) # append Create file object (binary files) fd = open (" testfile. txt ", rb ) # read fd = open (" testfile. txt ", wb ) # write fd = open (" testfile. txt ", ab ) # append open has more options (encoding, how to handle newlines,... ) Compact Course @ Max-Planck, February 16-26, 2015 47

File I/O (2) Methods of file objects Reading fd. read () # all fd. read (n) # n Bytes fd. readline () # one line fd. readlines () # Writing fd. write (" New Text \n") fd. writelines ([" first line \n", " Second \n"]) Don t forget to write newlines Closing fd. close () Compact Course @ Max-Planck, February 16-26, 2015 48

File I/O (3) Iterating over textfile for loop over file line by line fd = open (" fulltext. txt ") for line in fd: # rather than : in fd. readlines () print line # or: while True : line = fd. readline () if not line : break print line Compact Course @ Max-Planck, February 16-26, 2015 49

File I/O (3) Iterating over textfile for loop over file line by line fd = open (" fulltext. txt ") for line in fd: # rather than : in fd. readlines () print line # or: while True : line = fd. readline () if not line : break print line Some more functions on file objects fd.tell() get current file position fd.seek(offset) set file to position fd.flush() flush output buffer. Note: buffered for efficiency Compact Course @ Max-Planck, February 16-26, 2015 49

Getting more... Modules Outsource functionality in separate.py files Import them as library module Example (tools.py): """ This module provides some helper tools. Try it. """ counter = 42 def readfile ( fname ): " Read text file. Returns list of lines " fd = open ( fname, r ) data = fd. readlines () fd. close () return data def do_nothing (): "Do really nothing " pass Compact Course @ Max-Planck, February 16-26, 2015 50

Modules (2) Import module import tools tools. do_nothing () print tools. counter Import module and change name import tools as t t. do_nothing () Import selected symbols to current namespace from tools import do_nothing, readfile from tools import counter as cntr do_nothing () print cntr Compact Course @ Max-Planck, February 16-26, 2015 51

Modules (3) Import all symbols to current namespace from tools import * do_nothing () print counter Modules can control which symbols are imported by from module import *: # module tools. py all = [ readfile, counter ] Then do_nothing() is unknown after import * Compact Course @ Max-Planck, February 16-26, 2015 52

Modules (3) Import all symbols to current namespace from tools import * do_nothing () print counter Modules can control which symbols are imported by from module import *: # module tools. py all = [ readfile, counter ] Then do_nothing() is unknown after import * Inspect namespace Inspect namespace of module with dir ( tools ) Compact Course @ Max-Planck, February 16-26, 2015 52

Modules (4) Getting help Access docstrings import tools help ( tools ) help ( tools. do_nothing ) Compact Course @ Max-Planck, February 16-26, 2015 53

Modules (4) Getting help Access docstrings import tools help ( tools ) help ( tools. do_nothing ) Execute module as main program tools.py should serve as program and module # tools.py... if name == main : print " tools.py executed " else : print " tools.py imported as module " Compact Course @ Max-Planck, February 16-26, 2015 53

Modules (5) Reload module When debugging a module reload with reload (Python<3.0) reload ( tools ) Module search path Modules have to be in current directory or in directory in search path import sys sys. path. append (" folder /to/ module ") import... Automatically extend sys.path by setting environment variable PYTHONPATH Compact Course @ Max-Planck, February 16-26, 2015 54

Packages Group modules Modules can be grouped together Folder structure determines modules, e.g.: tools / init. py # contents for " import tools " files. py # for " import tools. files " graphics. py # for " import tools. graphics " stringtools / init. py # for " import tools. stringtools "... further nesting If from tools import * should import submodules, tools/ init.py has to contain all = [" files ", " graphics "] Compact Course @ Max-Planck, February 16-26, 2015 55

Command-Line Options Using sys sys.argv is list of command-line options First one (sys.argv[0]) is program name import sys print " Executing : %s" % ( sys. argv [0]) if len ( sys. argv ) < 2: print " Not enough parameters " sys. exit (1) print " Parameters :" print ", ". join ( sys. argv [1:]) Parse parameters... Compact Course @ Max-Planck, February 16-26, 2015 56

Command-Line Options (2) Module argparse Class ArgumentParser in module argparse simplifies option parsing #!/ usr / bin / python import argparse p = argparse. ArgumentParser () # specify options p. add_argument ("-o", action =" store ", dest =" opt ") p. add_argument ("-v"," -- verbose ",action =" store_true ", dest =" verbose ", help =" Produce more output ") # parse options options = p. parse_args () if options. verbose : print " Starting program... " print options Compact Course @ Max-Planck, February 16-26, 2015 57

Module argparse (2) Program now supports Default help Two custom parameters Try (parameters.py):./ parameters.py./ parameters. py -h./ parameters.py -o " Enjoy it" -- verbose./ parameters.py -v file1. txt file2. txt Compact Course @ Max-Planck, February 16-26, 2015 58

Module argparse (3) Some parameters of add_argument One character "-x" and/or multiple character switches "--xyz" action can be store, store_true, store_false, append, count dest name of option default default value help help text type one of string (default), int, long, float, complex, choice choices = [ first, second, third ] for type= choice Compact Course @ Max-Planck, February 16-26, 2015 59

Module argparse (3) Some parameters of add_argument One character "-x" and/or multiple character switches "--xyz" action can be store, store_true, store_false, append, count dest name of option default default value help help text type one of string (default), int, long, float, complex, choice choices = [ first, second, third ] for type= choice Help text with set_usage Reference to program name with %prog p = argparse. ArgumentParser ( % prog [ options ] file (s) Do nice things with file (s) ) Compact Course @ Max-Planck, February 16-26, 2015 59

Standard Input, Output, and Error Module sys provides three standard file objects sys.stdin read only sys.stdout, sys.stderr write only import sys sys. stdout. write (" Enter line :\n") # = print "..." line = sys. stdin. readline () # or: line = raw_input (" Enter line :\ n") if error : sys. stderr. write (" Error!\n") write does not add newlines raw_input([text]) strips endling newline Input and output buffered Compact Course @ Max-Planck, February 16-26, 2015 60

More on Lists List comprehension Short notation to create lists even_squares = [] for i in range (10): if i%2 == 0: even_squares. append (i*i) even_squares = [ i **2 for i in range (10) if i %2==0] Compare: { i 2 i {0,..., 9}, i even } Compact Course @ Max-Planck, February 16-26, 2015 61

More on Lists List comprehension Short notation to create lists even_squares = [] for i in range (10): if i%2 == 0: even_squares. append (i*i) even_squares = [ i **2 for i in range (10) if i %2==0] Compare: { i 2 i {0,..., 9}, i even } Can contain more than one for... in... [if...] [(x,y. upper ()) for x in range (4) if x%2 == 0 for y in ["a", "b", "c"]] Compact Course @ Max-Planck, February 16-26, 2015 61

More on Lists (2) Advanced slice assignement Note: assigning slices of mutable sequences can change size l = range (5) l [1:3] = [7,8,9] l [4:6] = [6] Compact Course @ Max-Planck, February 16-26, 2015 62

More on Lists (2) Advanced slice assignement Note: assigning slices of mutable sequences can change size l = range (5) l [1:3] = [7,8,9] l [4:6] = [6] range and xrange range([i,] j [, stride]) creates list Memory allocated for whole list, even when only iterating over them, especially in loops xrange object calculates values when accessed (generator) for i in range (650000): do_something () for i in xrange (650000): do_something () Compact Course @ Max-Planck, February 16-26, 2015 62

Even more on Built-in Sequences set and frozenset set is mutable, frozenset is not s = set ([3,1,2,3,"foo ",2]) len (s) l = [2,8,7] # any iterable sequence s. difference (l) s. intersection (l) s. union (l) s. symmetric_difference (l) s. issubset ([3,"foo "]) s. issuperset ([3,"foo "]) For set s. add (42) s. remove (3) s. intersection_update (l) # and more methods... Compact Course @ Max-Planck, February 16-26, 2015 63

Even more on Functions Anonymous functions Can be defined using keyword lambda Lambda functions allow functional programming def inc (i): return i+1 inc = lambda (i): i+1 ( lambda i: i +1)(4) Common use: map function on list items / filter list l = range (10) map ( lambda x: x*x+1, l) filter ( lambda x: x %2==0, l) Compact Course @ Max-Planck, February 16-26, 2015 64